Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Created December 8, 2013 02:46
Show Gist options
  • Select an option

  • Save MichaelXavier/7852776 to your computer and use it in GitHub Desktop.

Select an option

Save MichaelXavier/7852776 to your computer and use it in GitHub Desktop.
Contrived example of using the Maybe monad to make inherently unsafe operations safe by representing failures as Nothing. You can turn a sequence of functions that produce Maybes into an imperative chunk of code that only has to handle the success case.
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:xs) = Just x
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (div x y)
divideHeads :: [Int] -> [Int] -> Maybe Int
divideHeads xs ys = do
-- using Maybe monad, Nothing will safely terminate early
x <- safeHead xs
y <- safeHead ys
safeDiv x y
main :: IO ()
main = do
print (divideHeads [] []) -- Nothing, can't head empty
print (divideHeads [4, 2] [2]) -- Just 2
print (divideHeads [1, 2] [0, 5]) -- Nothing from divide by zero
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment