Last active
July 24, 2017 21:42
-
-
Save jiamingd/338505faa98ea2bb5c65d1328065b217 to your computer and use it in GitHub Desktop.
Light weight of Functor & Monad in scala work
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
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