Skip to content

Instantly share code, notes, and snippets.

@imeredith
Created June 28, 2012 03:42
Show Gist options
  • Save imeredith/3008818 to your computer and use it in GitHub Desktop.
Save imeredith/3008818 to your computer and use it in GitHub Desktop.
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
}
}
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