Created
January 5, 2019 03:04
-
-
Save kendricktan/f87777b2c100fe8b3249cbf4d656a3d3 to your computer and use it in GitHub Desktop.
Maybe Monad COCO
This file contains hidden or 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
| 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