Created
June 28, 2012 03:42
-
-
Save imeredith/3008818 to your computer and use it in GitHub Desktop.
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
trait Monad[F[_], A] { | |
def map[B](f: A => B): F[B] | |
def flatMap[B](f: A => F[B]): F[B] | |
} | |
case class IntS[A](k: Int => (Int, A)) extends Monad[IntS, A] { | |
def map[B](f: A => B): IntS[B] = IntS((i: Int) => { | |
k(i) match { | |
case (s, a) => (s, f(a)) | |
} | |
}) | |
def flatMap[B](f: A => IntS[B]): IntS[B] = IntS((i: Int) => { | |
k(i) match { | |
case (s, a) => f(a).k(s) | |
} | |
}) | |
def print = k(0) match { | |
case (s, a) => println("state " + s + " value " + a) | |
} | |
} | |
object Main { | |
def main(args: Array[String]) { | |
val initial = IntS((i: Int) => (5, "test")) | |
initial.print | |
val second = initial.map(f=> f + "test") | |
second.print | |
val third = second.flatMap(f => IntS((i: Int) => (6, f))) | |
third.print | |
} | |
} |
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
state 5 value test | |
state 5 value testtest | |
state 6 value testtest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment