EitherT filter with error in Scalaz

327 views Asked by At

Assume we have EitherT[F, String, A]. The withFilter function of Scalaz uses the zero of String's Monoid in order to fill in Left if the filter fails.

Therefore, there is no meaningful error message.

How could I implement something of the form where Left would be "Not positive".

val a: Either[Future, String, Int] = -1.point[EitherT[Future, String, ?]]

val foo = for {
  aa <- a
  if aa >= 0
} yield aa

Are the filter and withFilter methods on EitherT just hacks to fulfill the for-comprehension demands?

1

There are 1 answers

0
Peter Neyens On BEST ANSWER

You can use EitherT#ensure :

import scalaz._, Scalaz._

val xs: List[String \/ Int] =
  List(1.right, 2.right, -5.right, "other error".left, 3.right, -4.right)

EitherT(xs).ensure("not positive")(_ > 0)

// EitherT(List(\/-(1), \/-(2), -\/(not positive), -\/(other error), \/-(3), -\/(not positive)))