Skip to content

Commit 283893c

Browse files
committed
Add solutions for chapter exercise seven
1 parent ea2c9cd commit 283893c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

12-monads-and-more/12.05-exercises.hs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,43 @@ instance Functor ZipList where
2929
instance Applicative ZipList where
3030
pure x = Z $ repeat x
3131
Z fs <*> Z xs = Z [f x | (f, x) <- zip fs xs]
32+
33+
-----------------------------------------------------------------------------
34+
-- 5.
35+
-- What?
36+
37+
-----------------------------------------------------------------------------
38+
-- 6.
39+
instance Monad ((->) a) where
40+
return = pure
41+
mx >>= f = \x -> f (mx x) x
42+
43+
-----------------------------------------------------------------------------
44+
-- 7.
45+
data Expr a = Var a
46+
| Val Int
47+
| Add (Expr a) (Expr a)
48+
deriving Show
49+
50+
instance Functor Expr where
51+
fmap f (Var x) = Var (f x)
52+
fmap _ (Val x) = Val x
53+
fmap f (Add x y) = Add (fmap f x) (fmap f y)
54+
55+
instance Applicative Expr where
56+
pure = Var
57+
_ <*> Val x = Val x
58+
Val x <*> _ = Val x
59+
Var f <*> Var x = Var (f x)
60+
Var f <*> Add x y = Add (fmap f x) (fmap f y)
61+
Add f g <*> x = Add (f <*> x) (g <*> x)
62+
63+
instance Monad Expr where
64+
return = pure
65+
Val x >>= _ = Val x
66+
Var x >>= f = f x
67+
Add x y >>= f = Add (x >>= f) (y >>= f)
68+
69+
-----------------------------------------------------------------------------
70+
-- 8.
71+

0 commit comments

Comments
 (0)