| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Foldable functors |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
-- Note that currently the Foldable laws are not included here. |
| 8 |
|
| 9 |
{-# OPTIONS --cubical-compatible --safe #-} |
| 10 |
|
| 11 |
module Effect.Foldable where |
| 12 |
|
| 13 |
open import Algebra.Bundles.Raw using (RawMonoid) |
| 14 |
open import Algebra.Bundles using (Monoid) |
| 15 |
import Algebra.Construct.Flip.Op as Op |
| 16 |
open import Data.List.Base as List using (List; [_]; _++_) |
| 17 |
open import Effect.Functor as Fun using (RawFunctor) |
| 18 |
open import Function.Base using (id; flip) |
| 19 |
open import Function.Endo.Propositional using (∘-id-monoid) |
| 20 |
open import Level using (Level; Setω) |
| 21 |
open import Relation.Binary.Bundles using (Setoid) |
| 22 |
|
| 23 |
private |
| 24 |
variable |
| 25 |
f g c ℓ : Level |
| 26 |
A : Set f |
| 27 |
C : Set c |
| 28 |
|
| 29 |
|
| 30 |
------------------------------------------------------------------------ |
| 31 |
-- The type of raw Foldables: |
| 32 |
-- all fields can be given non-default implementations |
| 33 |
|
| 34 |
record RawFoldable (F : Set f → Set g) : Setω where |
| 35 |
field |
| 36 |
foldMap : (M : RawMonoid c ℓ) (open RawMonoid M) → |
| 37 |
(A → Carrier) → F A → Carrier |
| 38 |
|
| 39 |
fold : (M : RawMonoid f ℓ) (open RawMonoid M) → F Carrier → Carrier |
| 40 |
fold M = foldMap M id |
| 41 |
|
| 42 |
field |
| 43 |
foldr : (A -> C -> C) -> C -> F A -> C |
| 44 |
foldl : (C -> A -> C) -> C -> F A -> C |
| 45 |
toList : F A → List A |
| 46 |
|
| 47 |
|
| 48 |
------------------------------------------------------------------------ |
| 49 |
-- The type of raw Foldables, with default implementations a la haskell |
| 50 |
|
| 51 |
record RawFoldableWithDefaults (F : Set f → Set g) : Setω where |
| 52 |
field |
| 53 |
foldMap : (M : RawMonoid c ℓ) (open RawMonoid M) → |
| 54 |
(A → Carrier) → F A → Carrier |
| 55 |
|
| 56 |
foldr : (A -> C -> C) -> C -> F A -> C |
| 57 |
foldr {C = C} f z t = foldMap M₀ f t z |
| 58 |
where M = ∘-id-monoid C ; M₀ = Monoid.rawMonoid M |
| 59 |
|
| 60 |
foldl : (C -> A -> C) -> C -> F A -> C |
| 61 |
foldl {C = C} f z t = foldMap M₀ (flip f) t z |
| 62 |
where M = Op.monoid (∘-id-monoid C) ; M₀ = Monoid.rawMonoid M |
| 63 |
|
| 64 |
toList : F A → List A |
| 65 |
toList {A = A} = foldMap (List.++-[]-rawMonoid A) [_] |
| 66 |
|
| 67 |
rawFoldable : RawFoldable F |
| 68 |
rawFoldable = record |
| 69 |
{ foldMap = foldMap |
| 70 |
; foldr = foldr |
| 71 |
; foldl = foldl |
| 72 |
; toList = toList |
| 73 |
} |
| 74 |
|