Skip to content

Instantly share code, notes, and snippets.

@jiamingd
Last active July 24, 2017 21:42
Show Gist options
  • Save jiamingd/338505faa98ea2bb5c65d1328065b217 to your computer and use it in GitHub Desktop.
Save jiamingd/338505faa98ea2bb5c65d1328065b217 to your computer and use it in GitHub Desktop.
Light weight of Functor & Monad in scala work
case class MyFunctor[K](contextValue: K) {
def map[T](f: K => T) : MyFunctor[T]= {
MyFunctor( f(this.contextValue) )
}
}
case class MyMonad[K](contextValue : K) {
def flatMap[T](f: K => MyMonad[T]) : MyMonad[T] = {
println(s"flatMap called: $contextValue ")
f(this.contextValue)
}
def map[T](f: K => T) : MyMonad[T]= {
//Only vanilla case
println(s"map called : $contextValue")
MyMonad( f(this.contextValue) )
}
}
for { m <- MyFunctor(1) } yield {
s"${m.toString()}:the value"
}
for {
c <- MyMonad("yes")
b <- MyMonad(2)
// map is called, by must be full monad def
// if(a ...) need impl withFilter im MyMonad
a <- MyMonad(100)
} yield {
println(s"$c, $b, $a")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment