Debian Codegraph @

src/Data/List/Effectful/Foldable.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- List is Foldable
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 module Data.List.Effectful.Foldable where
10
11 open import Algebra.Bundles using (Monoid)
12 open import Algebra.Bundles.Raw using (RawMonoid)
13 open import Algebra.Morphism.Structures using (IsMonoidHomomorphism)
14 open import Data.List.Base as List using (List; []; _∷_; _++_)
15 open import Effect.Foldable using (RawFoldableWithDefaults; RawFoldable)
16 open import Function.Base using (_∘_; id)
17 open import Level using (Level)
18 import Relation.Binary.PropositionalEquality.Core as ≡ using (_≡_; cong)
19
20 private
21 variable
22 a c ℓ : Level
23 A : Set a
24
25 ------------------------------------------------------------------------
26 -- Root implementation
27
28 module _ (M : RawMonoid c ℓ) where
29
30 open RawMonoid M
31
32 foldMap : (A → Carrier) → List A → Carrier
33 foldMap f [] = ε
34 foldMap f (x ∷ xs) = f x ∙ foldMap f xs
35
36 ------------------------------------------------------------------------
37 -- Basic implementation using supplied defaults
38
39 foldableWithDefaults : RawFoldableWithDefaults (List {a})
40 foldableWithDefaults = record { foldMap = λ M → foldMap M }
41
42 ------------------------------------------------------------------------
43 -- Specialised version using optimised implementations
44
45 foldable : RawFoldable (List {a})
46 foldable = record
47 { foldMap = λ M → foldMap M
48 ; foldr = List.foldr
49 ; foldl = List.foldl
50 ; toList = id
51 }
52
53 ------------------------------------------------------------------------
54 -- Properties
55
56 module _ (M : Monoid c ℓ) (f : A → Monoid.Carrier M) where
57
58 open Monoid M
59
60 private
61 h = foldMap rawMonoid f
62
63 []-homo : h [] ≈ ε
64 []-homo = refl
65
66 ++-homo : ∀ xs {ys} → h (xs ++ ys) ≈ h xs ∙ h ys
67 ++-homo [] = sym (identityˡ _)
68 ++-homo (x ∷ xs) = trans (∙-congˡ (++-homo xs)) (sym (assoc _ _ _))
69
70 foldMap-morphism : IsMonoidHomomorphism (List.++-[]-rawMonoid A) rawMonoid h
71 foldMap-morphism = record
72 { isMagmaHomomorphism = record
73 { isRelHomomorphism = record
74 { cong = reflexive ∘ ≡.cong h }
75 ; homo = λ xs _ → ++-homo xs
76 }
77 ; ε-homo = []-homo
78 }