-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaybemonad.hs
85 lines (63 loc) · 1.52 KB
/
maybemonad.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
module MaybeMonad where
data Cow = Cow {
name :: String
, age :: Int
, weight :: Int
} deriving (Eq, Show)
noEmpty :: String -> Maybe String
noEmpty "" = Nothing
noEmpty str = Just str
noNegative :: Int -> Maybe Int
noNegative n | n >= 0 = Just n
| otherwise = Nothing
weightCheck :: Cow -> Maybe Cow
weightCheck c =
let w = weight c
n = name c
in if n == "Bess" && w > 499
then Nothing
else Just c
mkSphericalCow :: String
-> Int
-> Int
-> Maybe Cow
mkSphericalCow name' age' weight' =
case noEmpty name' of
Nothing -> Nothing
Just nammy ->
case noNegative age' of
Nothing -> Nothing
Just agey ->
case noNegative weight' of
Nothing -> Nothing
Just weighty ->
weightCheck (Cow nammy agey weighty)
--------------------
--
mkSphericalCow' :: String -> Int -> Int -> Maybe Cow
mkSphericalCow' name' age' weight' = do
nammy <- noEmpty name'
agey <- noNegative age'
weighty <- noNegative weight'
weightCheck (Cow nammy agey weighty)
---------
-- Applicative vs Monad
---------
f :: Integer -> Maybe Integer
f 0 = Nothing
f n = Just n
g :: Integer -> Maybe Integer
g i =
if even i
then Just (i + 1)
else Nothing
h :: Integer -> Maybe String
h i = Just ("10191" ++ show i)
doSomething n = do
a <- f n
b <- g a
c <- h b
pure (a, b, c)
doSomething' n =
let m = \(Just x) -> x
in pure (m $ f n, m $ g $ m $ f n, m $ h $ m $ g $ m $ f n)