Skip to content

Instantly share code, notes, and snippets.

@kendricktan
Created January 5, 2019 03:04
Show Gist options
  • Select an option

  • Save kendricktan/f87777b2c100fe8b3249cbf4d656a3d3 to your computer and use it in GitHub Desktop.

Select an option

Save kendricktan/f87777b2c100fe8b3249cbf4d656a3d3 to your computer and use it in GitHub Desktop.
Maybe Monad COCO
import math
class Maybe
data Just(n) from Maybe
data Nothing() from Maybe
@addpattern(fmap)
def fmap(f, Nothing()) = Nothing()
@addpattern(fmap)
def fmap(f, Just(n)) = Just(f(n))
def apply(f: Maybe, a: Maybe):
match (Just(ff), Just(aa)) in (f, a):
return Just(ff(aa))
else:
return Nothing()
def bind(f, Nothing()) = Nothing()
@addpattern
def bind(f, Just(a)) = f(a)
maybeValue = Just(10)
maybeFunction = Just(x -> x ** 2)
maybeFunction2 = Just(math.sqrt)
def valueToMaybe(v: int) -> Maybe:
if v < 100:
return Just(v)
return Nothing()
maybeValue |> fmap$(x -> x ** 2) |> apply$(maybeFunction) |> print
f = x -> x * 2
# Composition
(f..f..f..f)(5) |> print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment