Forked from ChristopherDavenport/LoggingInPureFunctions.scala
Created
March 16, 2018 15:06
-
-
Save julianpeeters/10e7bc255d23873fbf21e5757e792f0f to your computer and use it in GitHub Desktop.
Pure Logging
This file contains hidden or 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
| 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] | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment