Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created October 6, 2019 20:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/7edf5b70df4a28a34e1a081ac3557b47 to your computer and use it in GitHub Desktop.
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
Vector(Received : 3, Received : 5, Received : 4)
60
Vector(Received : 11, Received and zeroing: 11, Received : 4)
0
// 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