Created
July 27, 2019 07:02
-
-
Save justinhj/3ac582f0a7b9c33541d53c6c7cfec1ef to your computer and use it in GitHub Desktop.
WriterT failing
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
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