Skip to content

Instantly share code, notes, and snippets.

@woupiestek
Last active January 4, 2016 15:49
Show Gist options
  • Save woupiestek/bb52fe2ade036d959b86 to your computer and use it in GitHub Desktop.
Save woupiestek/bb52fe2ade036d959b86 to your computer and use it in GitHub Desktop.
Build a logging monad with scalaz, apply it to futures and reproduce functionality of the futures monad.
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.language.higherKinds
import scalaz._
import Scalaz._
object LoggingMonadTransformerPOC extends App {
type LoggedT[F[_], A] = WriterT[F, List[String], A]
type LoggedFuture[A] = LoggedT[Future, A]
//this is the applicative behavior that we want WriterT to preserve
val example = for {
z <- (Future("left") |@| Future("right")) { (x: String, y: String) => x + " " + y }
} yield z
example.onSuccess { case x => println(x) }
val test: LoggedFuture[String] = for {
z <- (Future("left").liftM[LoggedT] |@| Future("right").liftM[LoggedT]) { (x: String, y: String) => x + " " + y }
} yield z
test.value.onSuccess { case x => println(x) }
//good interop with collections is also a must
val example2 = Future.traverse(0 to 10) { i => Future(i) }
example2.onSuccess { case x => println(x) }
val test2:LoggedFuture[Vector[Int]] = (0 to 10).toVector.traverse[LoggedFuture, Int] {
i: Int => Future(i).liftM[LoggedT]
}
test2.value.onSuccess { case x => println(x) }
}
@woupiestek
Copy link
Author

Tested with scala version 2.11.7 and scalaz version 7.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment