Created
August 1, 2022 14:08
-
-
Save ianfun/f451435e8b4d475e0339f84e6f0d812c to your computer and use it in GitHub Desktop.
Identity Monad for Nim
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
# identity functor and monad for Nim https://hackage.haskell.org/package/base/docs/Data-Functor-Identity.html | |
type Identity*[T] = object | |
runIdentity*: T | |
# return(unit) for identity | |
proc identity*[T](a: T): Identity[T] = Identity[T](runIdentity: a) | |
proc `$`*[T](a: Identity[T]): string = | |
"Identity " & $(a.runIdentity) | |
# fmap :: Functor f => (a -> b) -> f a -> f b | |
proc fmap*[A, B](f: proc (i: A): B, i: Identity[A]): Identity[B] {.inline.} = | |
identity[B](f(i.runIdentity)) | |
# (>>=) :: Monad m => m a -> (a -> m b) -> m b | |
proc `>>=`*[A, B](i: Identity[A], f: proc (a: A): Identity[B]): Identity[B] {.inline.} = | |
f(i.runIdentity) | |
proc `>>`*[A, B](a: Identity[A], b: Identity[B]): Identity[B] {.inline.} = | |
b | |
echo identity(10) >> identity(5) | |
echo identity(10) >>= (proc (x: int): Identity[int] = identity (x + x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment