Haskell Maybe & Either
Haskell has no null. A value of type String is always a string. When a result might be missing, or a computation might fail, the type says so explicitly with Maybe or Either. The compiler then makes sure every caller handles the missing or failed case.
Maybe: a value that might be absent
data Maybe a = Nothing | Just aA Maybe Int is either Nothing or Just some Int. Many standard functions return one:
import Text.Read (readMaybe)
main :: IO ()
main = do
print (lookup "b" [("a", 1), ("b", 2)])
print (lookup "z" [("a", 1), ("b", 2)])
print (readMaybe "42" :: Maybe Int)
print (readMaybe "forty-two" :: Maybe Int)
print (safeDiv 10 2, safeDiv 1 0)
where
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv a b = Just (a `div` b)Just 2
Nothing
Just 42
Nothing
(Just 5,Nothing)
safeDiv turns a crash (division by zero) into an ordinary value that callers can inspect.
Getting values out of a Maybe
You cannot use a Maybe Int as an Int directly; you must say what happens in the Nothing case:
import Data.Maybe (fromMaybe, mapMaybe, catMaybes, isJust)
import Text.Read (readMaybe)
describeAge :: Maybe Int -> String
describeAge Nothing = "age unknown"
describeAge (Just a) = show a ++ " years"
main :: IO ()
main = do
putStrLn (describeAge (Just 30))
putStrLn (describeAge Nothing)
print (fromMaybe 0 (readMaybe "x9" :: Maybe Int)) -- default value
print (maybe "none" show (Just 3.5)) -- default + function
let inputs = ["10", "abc", "25", "", "7"]
print (mapMaybe readMaybe inputs :: [Int]) -- keep the parsed ones
print (catMaybes [Just 'a', Nothing, Just 'b'])
print (filter isJust [Just 1, Nothing])30 years
age unknown
0
"3.5"
[10,25,7]
"ab"
[Just 1]
| Function | Type | Use |
|---|---|---|
pattern matching / case |
full control | |
fromMaybe |
a -> Maybe a -> a |
supply a default |
maybe |
b -> (a -> b) -> Maybe a -> b |
default, or transform the value |
mapMaybe |
(a -> Maybe b) -> [a] -> [b] |
map and drop the Nothings |
catMaybes |
[Maybe a] -> [a] |
drop the Nothings |
isJust, isNothing |
Maybe a -> Bool |
test |
fromJust |
Maybe a -> a |
crashes on Nothing: avoid |
Chaining Maybe computations
What if several steps can each fail? Nested case expressions work, but they march off to the right:
import qualified Data.Map as Map
managerOf, emailOf :: Map.Map String String
managerOf = Map.fromList [("ana", "ben"), ("ben", "cleo")]
emailOf = Map.fromList [("ben", "ben@corp.io"), ("cleo", "cleo@corp.io")]
-- e-mail of the manager's manager
skipLevelEmail :: String -> Maybe String
skipLevelEmail person = do
boss <- Map.lookup person managerOf
bigBoss <- Map.lookup boss managerOf
Map.lookup bigBoss emailOf
main :: IO ()
main = do
print (skipLevelEmail "ana")
print (skipLevelEmail "ben")
print (skipLevelEmail "zoe")Just "cleo@corp.io"
Nothing
Nothing
The do block runs each step only if the previous one produced a Just; the first Nothing stops everything and becomes the result. This works because Maybe is a Monad, which you will understand fully in a few lessons. For now, enjoy that it reads like straight-line code.
Either: failure with a reason
Nothing says that something failed, but not why. Either carries an explanation:
data Either e a = Left e | Right aBy convention Left holds the error and Right holds the result ("right" as in "correct").
import Text.Read (readMaybe)
data SignupError = TooShort Int | MissingAt | BadAge String
deriving Show
validatePassword :: String -> Either SignupError String
validatePassword pw
| length pw < 8 = Left (TooShort (length pw))
| otherwise = Right pw
validateEmail :: String -> Either SignupError String
validateEmail e = if '@' `elem` e then Right e else Left MissingAt
parseAge :: String -> Either SignupError Int
parseAge s = case readMaybe s of
Just n | n >= 13 -> Right n
_ -> Left (BadAge s)
signup :: String -> String -> String -> Either SignupError (String, Int)
signup email pw ageText = do
e <- validateEmail email
_ <- validatePassword pw
age <- parseAge ageText
return (e, age)
main :: IO ()
main = do
print (signup "kim@mail.com" "correct-horse" "29")
print (signup "kim.mail.com" "correct-horse" "29")
print (signup "kim@mail.com" "short" "29")
print (signup "kim@mail.com" "correct-horse" "nine")Right ("kim@mail.com",29)
Left MissingAt
Left (TooShort 5)
Left (BadAge "nine")
Just like Maybe, a do block over Either stops at the first Left. The error type is your own data type, so callers can pattern match on exactly what went wrong.
Working with Either values
import Data.Either (lefts, rights, partitionEithers, either)
checkEven :: Int -> Either String Int
checkEven n = if even n then Right n else Left (show n ++ " is odd")
main :: IO ()
main = do
let results = map checkEven [4, 7, 10, 3]
print results
print (rights results)
print (lefts results)
print (partitionEithers results)
print (map (either length (* 100)) results)[Right 4,Left "7 is odd",Right 10,Left "3 is odd"]
[4,10]
["7 is odd","3 is odd"]
(["7 is odd","3 is odd"],[4,10])
[400,8,1000,8]
either f g handles both cases at once: f for a Left, g for a Right.
Tip: Use
Maybewhen the absence of a value is normal and needs no explanation (a lookup that may not find anything). UseEitherwhen the caller needs to know what went wrong.
Test yourself
What is the type of lookup 3 [(1, "one")]?
StringMaybe StringEither String Int[String]
By convention, what does Left hold in an Either?
- The success value
- The error
- The first argument
- Nothing
What is fromMaybe 1 Nothing + fromMaybe 1 (Just 5)?
- 2
- 6
- 5
- A type error