Created
October 6, 2019 20:06
-
-
Save fancellu/7edf5b70df4a28a34e1a081ac3557b47 to your computer and use it in GitHub Desktop.
Example code to show how Cats Writer can be used to add useful inline logging to some computation
This file contains 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
Vector(Received : 3, Received : 5, Received : 4) | |
60 | |
Vector(Received : 11, Received and zeroing: 11, Received : 4) | |
0 |
This file contains 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
// Example code to show how Cats Writer can be used to add useful inline logging to some computation | |
import cats._ | |
import cats.data._ | |
import cats.implicits._ | |
object WriterExample extends App { | |
type LOG = Vector[String] | |
type LOGWRITER[A] = Writer[LOG, A] | |
def log[A: Show](thing: A): LOGWRITER[A] = Writer(Vector(show"Received : $thing"), thing) | |
def logThenZero[A: Show : Monoid](thing: A): LOGWRITER[A] = Writer(Vector(show"Received and zeroing: $thing"), Monoid[A].empty) | |
def processWithLog(start: Int): LOGWRITER[Int] = | |
for { | |
a <- log(start) | |
b <- if (a > 10) logThenZero(a) else log(a + 2) | |
c <- log(4) | |
} yield a * b * c | |
val (logs, result): (LOG, Int) = processWithLog(3).run | |
println(logs) | |
println(result) | |
val (logs2, result2): (LOG, Int) = processWithLog(11).run | |
println(logs2) | |
println(result2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment