Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created July 27, 2019 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinhj/3ac582f0a7b9c33541d53c6c7cfec1ef to your computer and use it in GitHub Desktop.
Save justinhj/3ac582f0a7b9c33541d53c6c7cfec1ef to your computer and use it in GitHub Desktop.
WriterT failing
import cats._
import cats.instances._
import cats.syntax._
import cats.data.Validated._
type ErrorOr[A] = Validated[String, A]
def logDivide(a: Int, b: Int) = WriterT[ErrorOr, String, Int](
divide[ErrorOr](a,b) match {
case Invalid(e) => Invalid("Division by zero\n")
case Valid(n) => Valid((s"Divided $a by $b\n", n))
}
)
def chain[A,B](fa: WriterT[ErrorOr, String, A], f : A => WriterT[ErrorOr, String, B]) : WriterT[ErrorOr, String, B] = {
fa.run match {
case Valid((l,a)) => {
f(a).tell(l)
}
case Invalid(err) => // Oh dear, no log here...
WriterT[ErrorOr, String, B](Invalid(err))// .tell(l)
}
}
val r1 = logDivide(10,2)
chain(r1, a => logDivide(20, a))
res96: WriterT[ErrorOr, String, Int] = Writ
erT(
Valid(
(
"""Divided 20 by 5
Divided 10 by 2
""",
4
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment