/
either.hs
49 lines (38 loc) · 1.22 KB
/
either.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
data Address =
Address {
getHouseNumber :: Int,
getStreetName :: String
} deriving (Eq, Show)
type Error = String
streetNumberGreaterThanZero :: Int -> Either Error Int
streetNumberGreaterThanZero x
| x <= 0 = Left "Number must be greater than zero!"
| otherwise = Right x
notEmpty :: String -> Error -> Either Error String
notEmpty x err
| x == "" = Left err
| otherwise = Right x
streetNameNotEmpty :: String -> Either Error String
streetNameNotEmpty x = notEmpty x "Street name must not be empty!"
makeAddress :: Int -> String -> Either Error Address
makeAddress x y = do
number <- streetNumberGreaterThanZero x
name <- streetNameNotEmpty y
Right $ Address number name
--------- SECOND PART ----------
data Person =
Person {
getName :: String,
getAddress :: Address
} deriving (Eq, Show)
nameNotEmpty :: String -> Either Error String
nameNotEmpty x = notEmpty x "Name must not be empty!"
makePerson :: String -> Either Error Address -> Either Error Person
makePerson n a = do
name <- nameNotEmpty n
address <- a
Right $ Person name address
makePerson' :: String -> Either Error Address -> Either Error Person
makePerson' n a =
nameNotEmpty n >>= \name ->
(Person name) <$> a