Last active
March 16, 2018 15:27
-
-
Save ChristopherDavenport/b7ec83f344186181cab4e4e66a4296c3 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] | |
| } | |
| } |
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.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