Skip to content

Instantly share code, notes, and snippets.

@tmiller
Last active March 13, 2018 12:51
Show Gist options
  • Save tmiller/527594436a0bf77d914c146bbddc5e4c to your computer and use it in GitHub Desktop.
Save tmiller/527594436a0bf77d914c146bbddc5e4c to your computer and use it in GitHub Desktop.
defmodule ErrorMonad do
def return(x) do
{:ok, x}
end
def and_then(m, f) do
case m do
{:ok, v} -> f.(v)
err -> err
end
end
end
defmodule Main do
def addFive(x) do
{:ok, x + 5}
end
def parseInt(x) do
case Integer.parse(x) do
{num, _} -> {:ok, num}
:error -> {:err, "Could not parse: #{x}"}
_ -> {:err, "Unkown error in parseInt/1"}
end
rescue
e -> {:err, e}
end
end
5
|> ErrorMonad.return
|> ErrorMonad.and_then(&Main.parseInt/1)
|> ErrorMonad.and_then(&Main.addFive/1)
|> IO.inspect
"abc"
|> ErrorMonad.return
|> ErrorMonad.and_then(&Main.parseInt/1)
|> ErrorMonad.and_then(&Main.addFive/1)
|> IO.inspect
"23"
|> ErrorMonad.return
|> ErrorMonad.and_then(&Main.parseInt/1)
|> ErrorMonad.and_then(&Main.addFive/1)
|> IO.inspect
# In Haskell you combine the `|>` and the `ErrorMonad.and_then` to form
# the `>>=` operator, so this example might look like the following pseudo
# code:
# "23"
# & ErrorMonad.return
# >>= Main.parseInt
# >>= Main.addFive
# >>= IO.inspect
#
# Note: In Haskell `&` is the same as `|>`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment