Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Last active November 28, 2017 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bedekelly/d92ea02845bd3c5e36ffa1a45e2924b5 to your computer and use it in GitHub Desktop.
Save bedekelly/d92ea02845bd3c5e36ffa1a45e2924b5 to your computer and use it in GitHub Desktop.
A simple exception monad in Elm
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