Last active
April 3, 2021 02:12
-
-
Save taegyunkim/31d6efe3a5037e145139e38a5c832a1d to your computer and use it in GitHub Desktop.
monad in 5 min
This file contains 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
-- Import this for fromJust | |
import Data.Maybe | |
data Expr = Val Int | Div Expr Expr | |
-- Example expressions | |
one = Val 1 | |
two = Div (Val 6) (Div (Val 3) (Val 1)) | |
three = Div (Val 6) (Val 2) | |
-- Naive implementation of division using Expr, doesn't handle division by 0. | |
-- eval :: Expr -> Int | |
-- eval (Val n) = n | |
-- eval (Div x y) = eval x `div` eval y | |
-- Safe division | |
safediv :: Int -> Int -> Maybe Int | |
safediv n m = if m == 0 then | |
Nothing | |
else | |
Just (n `div` m) | |
-- Verbose eval implementaion | |
-- eval :: Expr -> Maybe Int | |
-- eval (Val n) = Just n | |
-- eval (Div x y) = case eval x of | |
-- Nothing -> Nothing | |
-- Just n -> case eval y of | |
-- Nothing -> Nothing | |
-- Just m -> safediv n m | |
-- Little better with Maybe Monad | |
-- eval :: Expr -> Maybe Int | |
-- eval (Val n) = return n | |
-- eval (Div x y) = eval x >>= (\n -> | |
-- eval y >>= (\m -> | |
-- safediv n m)) | |
-- Combine with do | |
eval :: Expr -> Maybe Int | |
eval (Val n) = return n | |
eval (Div x y) = do n <- eval x | |
m <- eval y | |
safediv n m | |
main = putStrLn $ show $ fromJust $ eval one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment