summaryrefslogtreecommitdiff
path: root/Haskell-book/13/Person.hs
blob: c104a5386e9069b0a5d64f0d68099d1f2bc5a9ba (plain)
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
module Person where

type Name = String
type Age = Integer

data Person = Person Name Age deriving Show

data PersonInvalid = NameEmpty
                   | AgeTooLow
                   | PersonInvalidUnknown String
                   deriving (Eq, Show)

mkPerson :: Name -> Age -> Either PersonInvalid Person
mkPerson name age
  | name /= "" && age > 0 = Right $ Person name age
  | name == "" = Left NameEmpty
  | not (age > 0) = Left AgeTooLow
  | otherwise =
      Left $ PersonInvalidUnknown $
          "Name was: " ++ show name ++ " Age was: " ++ show age

showPerson :: Either PersonInvalid Person -> String
showPerson (Left NameEmpty) = "Name is empty"
showPerson (Left AgeTooLow) = "Age is too low"
showPerson (Left (PersonInvalidUnknown e)) = e
showPerson (Right p) = "Yay! Successfully got a person: " ++ (show p)

gimmePerson :: IO ()
gimmePerson = do
    putStr "Enter your name: "
    name <- getLine
    putStr "Enter your age: "
    age <- getLine
    putStrLn $ showPerson $ mkPerson name (read age)