Skip to content

Instantly share code, notes, and snippets.

@ChristopherDavenport
Last active March 16, 2018 15:27
Show Gist options
  • Select an option

  • Save ChristopherDavenport/b7ec83f344186181cab4e4e66a4296c3 to your computer and use it in GitHub Desktop.

Select an option

Save ChristopherDavenport/b7ec83f344186181cab4e4e66a4296c3 to your computer and use it in GitHub Desktop.
Pure Logging
import cats._
import cats.data._
import cats.implicits._
import cats.effect._
import scala.util.Try
object LoggingInPureFunctions {
// Writer[Vector[String], ?]
// type VectorWriter[A] = Writer[Vector[String], A]
// List[A]
def pureTransformation(x: Int, y: String): Writer[Vector[String], Option[Double]] = {
for {
_ <- Writer.tell(Vector(s"Got $y"))
} yield Try(y.length.toDouble / x.toDouble).toOption
}
def withPureTransformations(l: List[(Int, String)]): IO[List[Option[Double]]] = {
val traversed: Writer[Vector[String], List[Option[Double]]] = l.traverse{case (x, y) => pureTransformation(x, y)}
val (vec, list) : (Vector[String], List[Option[Double]]) = traversed.run
val logging : IO[Unit] = vec.traverse_(log => IO(println(log)))
logging *> list.pure[IO]
}
}
import cats.implicits._
import cats.effect._
object Main {
def main(args: Array[String]): Unit = {
LoggingInPureFunctions.withPureTransformations(
List(
1 -> "Yellow",
3 -> "Monkeys",
0 -> "Oh Noes!"
)
).flatMap{ listOfOptions =>
IO(println(s"Result Was: $listOfOptions"))
}.handleErrorWith(e => IO(println("Got Error")))
.unsafeRunSync
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment