Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Last active August 29, 2015 14:15
Show Gist options
  • Save AGhost-7/ee21cf364a534b4b1e59 to your computer and use it in GitHub Desktop.
Save AGhost-7/ee21cf364a534b4b1e59 to your computer and use it in GitHub Desktop.
Option/Maybe Monad in CoffeeScript
# Implementation defines behaviour instead of state.
None =
map: (func) -> None
flatMap: (func) -> None
forEach: (func) -> # Nothing!
getOrElse: (def) -> def
isDefined: () -> false
fold: (empty, notEmpty) -> empty()
Some = (val) ->
map: (func) -> Some(func(val))
flatMap: (func) -> func(val)
forEach: (func) -> func(val)
getOrElse: (def) -> val
isDefined: () -> true
fold:(empty, notEmpty) -> notEmpty(val)
Option = (val) ->
if val == undefined || val == null
None
else
Some(val)
# then you can...
maybe = Option(null)
maybe.forEach (val) ->
console.log(val)
maybe2 = Option(2)
maybe3 = maybe2.flatMap (val) ->
if val == 2
None
else
Some(val)
maybe3.fold(
() ->
console.log("nothing!")
(val) ->
console.log("Something " + val)
)
# > nothing!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment