Monad.agda 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. module Monad where
  2. module Prelude where
  3. infixl 40 _∘_
  4. id : {A : Set} -> A -> A
  5. id x = x
  6. _∘_ : {A B C : Set} -> (B -> C) -> (A -> B) -> A -> C
  7. f ∘ g = \x -> f (g x)
  8. data Nat : Set where
  9. zero : Nat
  10. suc : Nat -> Nat
  11. module Base where
  12. data Monad (M : Set -> Set) : Set1 where
  13. monad : (return : {A : Set} -> A -> M A) ->
  14. (bind : {A B : Set} -> M A -> (A -> M B) -> M B) ->
  15. Monad M
  16. monadReturn : {M : Set -> Set} -> Monad M -> {A : Set} -> A -> M A
  17. monadReturn (monad ret bind) = ret
  18. monadBind : {M : Set -> Set} -> Monad M -> {A B : Set} -> M A -> (A -> M B) -> M B
  19. monadBind (monad ret bind) = bind
  20. module Monad {M : Set -> Set}(monadM : Base.Monad M) where
  21. open Prelude
  22. infixl 15 _>>=_
  23. -- Return and bind --------------------------------------------------------
  24. return : {A : Set} -> A -> M A
  25. return = Base.monadReturn monadM
  26. _>>=_ : {A B : Set} -> M A -> (A -> M B) -> M B
  27. _>>=_ = Base.monadBind monadM
  28. -- Other operations -------------------------------------------------------
  29. liftM : {A B : Set} -> (A -> B) -> M A -> M B
  30. liftM f m = m >>= return ∘ f
  31. module List where
  32. infixr 20 _++_ _::_
  33. -- The list datatype ------------------------------------------------------
  34. data List (A : Set) : Set where
  35. nil : List A
  36. _::_ : A -> List A -> List A
  37. -- Some list operations ---------------------------------------------------
  38. foldr : {A B : Set} -> (A -> B -> B) -> B -> List A -> B
  39. foldr f e nil = e
  40. foldr f e (x :: xs) = f x (foldr f e xs)
  41. map : {A B : Set} -> (A -> B) -> List A -> List B
  42. map f nil = nil
  43. map f (x :: xs) = f x :: map f xs
  44. _++_ : {A : Set} -> List A -> List A -> List A
  45. nil ++ ys = ys
  46. (x :: xs) ++ ys = x :: (xs ++ ys)
  47. concat : {A : Set} -> List (List A) -> List A
  48. concat = foldr _++_ nil
  49. -- List is a monad --------------------------------------------------------
  50. open Base
  51. monadList : Monad List
  52. monadList = monad ret bind
  53. where
  54. ret : {A : Set} -> A -> List A
  55. ret x = x :: nil
  56. bind : {A B : Set} -> List A -> (A -> List B) -> List B
  57. bind xs f = concat (map f xs)
  58. open Prelude
  59. open List
  60. module MonadList = Monad monadList
  61. open MonadList