Created
December 8, 2013 02:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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