-
Notifications
You must be signed in to change notification settings - Fork 1
/
Cow.hs
47 lines (41 loc) · 1.24 KB
/
Cow.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
module Cow where
data Cow = Cow
{ name :: String,
age :: Int,
weight :: Int
}
deriving (Eq, Show)
noEmpty :: [Char] -> Maybe [Char]
noEmpty "" = Nothing
noEmpty s = Just s
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
makeSphericalCow :: String -> Int -> Int -> Maybe Cow
makeSphericalCow 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)
-- sugar with do
-- note that this cannot be done with applicative b/c weightCheck expects a Cow and NOT a Maybe Cow
-- See for comparison: https://github.com/mtanzim/haskellbook/blob/53b33690d0b91db77448d0aec92ec6e6b828f88c/ch17/Validation.hs#L52
makeSphericalCow' :: String -> Int -> Int -> Maybe Cow
makeSphericalCow' name' age' weight' = do
nammy <- noEmpty name'
agey <- noNegative age'
weighty <- noNegative weight'
weightCheck (Cow nammy agey weighty)