Created
November 25, 2017 02:30
-
-
Save samidarko/bbf1adb18b43a8379d8042e90fe14953 to your computer and use it in GitHub Desktop.
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
data Expr = Val Int | Div Expr Expr deriving Show | |
eval :: Expr -> Int | |
eval (Val x) = x | |
eval (Div x y) = eval x `div` eval y | |
safeDiv :: Int -> Int -> Maybe Int | |
safeDiv n m = if m == 0 then Nothing else Just (n `div` m) | |
safeEval :: Expr -> Maybe Int | |
safeEval (Val x) = Just x | |
safeEval (Div x y) = | |
case safeEval x of | |
Nothing -> Nothing | |
Just x' -> case safeEval y of | |
Nothing -> Nothing | |
Just y' -> safeDiv x' y' | |
-- (>>=) :: Monad m => m a -> (a -> m b) -> m b | |
safeEval' :: Expr -> Maybe Int | |
safeEval' (Val x) = return x | |
safeEval' (Div x y) = do x' <- safeEval' x | |
y' <- safeEval' y | |
safeDiv x' y' | |
-- safeEval' (Div x y) = | |
-- safeEval' x >>= (\x' -> safeEval' y >>= (\y' -> safeDiv x' y')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment