Skip to content

Instantly share code, notes, and snippets.

@julien-truffaut
Created July 17, 2014 19:30
Show Gist options
  • Save julien-truffaut/75689efab0c97fafcd8b to your computer and use it in GitHub Desktop.
Save julien-truffaut/75689efab0c97fafcd8b to your computer and use it in GitHub Desktop.
LSUG 17/06/2014
package monocle
import scala.concurrent.Future
case class State[S, A](f: S => (S, A)) {
def apply(s: S): (S, A) = f(s)
def map[B](g: A => B): State[S, B] = State[S, B] { s =>
val (t, a) = f(s)
(t, g(a))
}
def flatMap[B](g: A => State[S, B]): State[S, B] = State[S, B]{ s =>
val (t, a) = f(s)
val state2 = g(a)
state2.f(t)
}
def getState(s: S): S = f(s)._1
}
object State {
def put[S](s: S): State[S, Unit] = State(_ => (s, ()))
def modify[S](f: S => S): State[S, Unit] = State(s => (f(s), ()))
}
object StateExample extends App {
import State._
val s = for {
_ <- put(3)
_ <- modify[Int](_ + 1)
} yield ()
type Seed = Int
val rng: State[Seed, Int] = State(seed => (seed+1, seed))
//
// println(s.getState(99999))
// print(put(3).getState(0))
println(rng(0))
val pair: State[Seed, (Int, Int)] = for {
random1 <- rng
random2 <- rng
} yield (random1, random2)
val pair2 = rng flatMap( random1 =>
rng.map(random2 =>
(random1, random2)
)
)
println(pair(0)) // (2, (0, 1))
println(pair2(0))
val o: Option[Future[Int]] = Some(Future.successful(3))
import scala.concurrent.ExecutionContext.Implicits.global
val f2: Future[Option[Int]] = o match {
case Some(f) => f.map(Some(_))
case None => Future.successful(None)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment