Last active
November 28, 2017 12:57
-
-
Save bedekelly/d92ea02845bd3c5e36ffa1a45e2924b5 to your computer and use it in GitHub Desktop.
A simple exception monad in Elm
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 Html exposing (text) | |
type Result a | |
= Return a | |
| Raise Exception | |
type alias Exception = | |
String | |
unit : a -> Result a | |
unit a = | |
Return a | |
-- Create a "bind" operation to combine computations. | |
(>>=) : Result a -> (a -> Result b) -> Result b | |
(>>=) m k = | |
case m of | |
Raise e -> | |
Raise e | |
Return a -> | |
k a | |
-- The operation has low precedence to avoid death-by-parens. | |
infixr 0 >>= | |
{- Evaluate a simple integer-division expression. -} | |
type Term = Div Term Term | Const Int | |
eval : Term -> Result Int | |
eval t = case t of | |
Const a -> Return a | |
Div t1 t2 -> | |
eval t1 >>= \a -> eval t2 >>= \b -> | |
if b == 0 then Raise "division by zero!" | |
else Return (a // b) | |
main = text <| toString <| eval <| Div (Const 4) (Const 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment