Last active
May 9, 2021 14:36
-
-
Save einarwh/d8b8ad672bbf6e987806f1c1a35a4813 to your computer and use it in GitHub Desktop.
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
defmodule Option do | |
def some(value) do | |
{:some, value } | |
end | |
def none() do | |
nil | |
end | |
def pure(value) do | |
some(value) | |
end | |
def map(option, function) do | |
case option do | |
{:some, value} -> {:some, function.(value) } | |
nil -> nil | |
_ -> throw("Illegal value: #{option} is not an option.") | |
end | |
end | |
def bind(option, function) do | |
case option do | |
{:some, value} -> function.(value) | |
nil -> nil | |
_ -> throw("Illegal value: #{option} is not an option.") | |
end | |
end | |
def apply(value_option, function_option) do | |
case { value_option, function_option } do | |
{ {:some, value}, {:some, function} } -> pure(function.(value)) | |
{ nil, _ } -> nil | |
{ _, nil } -> nil | |
_ -> throw("Illegal values: one or more of #{value_option} and #{function_option} is not an option.") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment