Created
November 5, 2016 15:02
-
-
Save JoolsF/147d8dcb9d77ed4386e715394e4ef7f7 to your computer and use it in GitHub Desktop.
Very basic monad explanation
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
| /** | |
| * Simple Monad | |
| * | |
| * The key abstraction is the flatMap, which binds the computation through chaining. | |
| * Each invocation of flatMap returns the same data structure type (but of different value), | |
| * that serves as the input to the next command in chain. In the above snippet, flatMap | |
| * takes as input a closure (SomeType) => List[AnotherType] and returns a List[AnotherType]. | |
| * The important point to note is that all flatMaps take the same closure type as input and | |
| * return the same type as output. This is what "binds" the computation thread - every item | |
| * of the sequence in the for-comprehension has to honor this same type constraint. | |
| * | |
| * http://debasishg.blogspot.co.uk/2008/03/monads-another-way-to-abstract.html | |
| */ | |
| case class MyMonad[A](value: A) { | |
| def map[B](f: A => B) = new MyMonad(f(value)) | |
| def flatMap[B](f: A => MyMonad[B]) = f(value) | |
| override def toString = value.toString | |
| } | |
| //Example 1 - This.... | |
| for { | |
| a <- MyMonad(2) | |
| b <- MyMonad(3) | |
| } yield a + b | |
| // res: MyMonad[Int] = 5 | |
| // Is equivalent to this | |
| MyMonad(2) | |
| .flatMap(a => MyMonad(3) | |
| .map(b => a + b)) | |
| // res: MyMonad[Int] = 5 | |
| //Example 2 - This.... | |
| for { | |
| a <- MyMonad(2) | |
| b <- MyMonad(3) | |
| c <- MyMonad(4) | |
| } yield a + b + c | |
| // res: MyMonad[Int] = 9 | |
| // Is equivalent to this | |
| MyMonad(2) | |
| .flatMap(a => MyMonad(3) | |
| .flatMap(b => MyMonad(4) | |
| .map(c => a + b + c))) | |
| // res: MyMonad[Int] = 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment