-
Notifications
You must be signed in to change notification settings - Fork 0
/
sigfpe-invent-monad.hs
60 lines (38 loc) · 1.09 KB
/
sigfpe-invent-monad.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{-
f :: Int -> Int
f x = 2*x
g :: Int -> Int
g x = x+3
f' :: Int -> (Int, String)
f' x = (f x, "(*2)")
g' :: Int -> (Int, String)
g' x = (g x, "(+3)")
bind :: (Int -> (Int, String)) -> (Int , String) -> (Int, String)
bind ff (gx, gs) = let (fx, fs) = ff gx
in (fx, gs++fs)
-- ---------------------------------------------------------------------
-}
data W x = W x deriving Show
instance Functor W where
fmap f (W x) = W (f x)
instance Monad W where
return x = W x
W x >>= f = f x
bind :: (a -> W b) -> (W a -> W b)
bind f (W x) = f x
fPlus1 :: Int -> W Int
fPlus1 x = W (x+1)
-- g x (W y) = W (x+y)
g :: Int -> W Int -> W Int
g x wy = wy >>= (return . (+x))
-- g x wy = bind (return . (+x)) wy
-- g x wy = fmap (+x) wy
-------------------------------------------------------------------------------------------------
-- define a function
-- h :: W Int -> W Int -> W Int
-- h (W x) (W y) = W (x+y)
-- no unwrapping.
h :: W Int -> W Int -> W Int
h wx wy = bind (\x -> g x wy) wx
-- h wx wy = wx >>= (\x -> g x wy)
-- h wx wy = wx >>= flip g wy