1
------------------------------------------------------------------------
2
-- The Agda standard library
4
-- The free monad construction on containers
5
------------------------------------------------------------------------
7
module Data.Container.FreeMonad where
10
open import Function using (_∘_)
11
open import Data.Empty using (⊥-elim)
12
open import Data.Sum using (inj₁; inj₂)
13
open import Data.Product
14
open import Data.Container
15
open import Data.Container.Combinator using (const; _⊎_)
17
open import Category.Monad
22
------------------------------------------------------------------------
24
-- The free monad construction over a container and a set is, in
25
-- universal algebra terminology, also known as the term algebra over a
26
-- signature (a container) and a set (of variable symbols). The return
27
-- of the free monad corresponds to variables and the bind operator
28
-- corresponds to (parallel) substitution.
30
-- A useful intuition is to think of containers describing single
31
-- operations and the free monad construction over a container and a set
32
-- describing a tree of operations as nodes and elements of the set as
33
-- leafs. If one starts at the root, then any path will pass finitely
34
-- many nodes (operations described by the container) and eventually end
35
-- up in a leaf (element of the set) -- hence the Kleene star notation
36
-- (the type can be read as a regular expression).
38
_⋆C_ : ∀ {c} → Container c → Set c → Container c
41
_⋆_ : ∀ {c} → Container c → Set c → Set c
44
do : ∀ {c} {C : Container c} {X} → ⟦ C ⟧ (C ⋆ X) → C ⋆ X
45
do (s , k) = sup (inj₂ s) k
47
rawMonad : ∀ {c} {C : Container c} → RawMonad (_⋆_ C)
48
rawMonad = record { return = return; _>>=_ = _>>=_ }
50
return : ∀ {c} {C : Container c} {X} → X → C ⋆ X
51
return x = sup (inj₁ x) (⊥-elim ∘ lower)
53
_>>=_ : ∀ {c} {C : Container c} {X Y} → C ⋆ X → (X → C ⋆ Y) → C ⋆ Y
54
sup (inj₁ x) _ >>= k = k x
55
sup (inj₂ s) f >>= k = do (s , λ p → f p >>= k)