Reputation: 8281
Given a value and a predicate, how to create a ValidationNel
?
Here is my code :
def toValidationNel[A, E](a: A)(f: A => Boolean, fail: => E) : ValidationNel[E, A] =
if (f(a)) fail.failureNel[A] else a.successNel[E]
Is there an existing combinator in scalaz ?
Upvotes: 1
Views: 105
Reputation: 139058
Scalaz includes an either
extension method for booleans that's similar to Either.cond
but arguably a little nicer:
import scalaz._, Scalaz._
def toValNel[A, E](a: A)(f: A => Boolean, fail: => E) : ValidationNel[E, A] =
f(a).either(a).or(fail.wrapNel).validation
I've never really liked the fact that the right side for Either.cond
comes on the left, and Scalaz's version makes the either-or-ness a little clearer to my eye, but it's also potentially harder for people who aren't familiar with Scalaz to understand at a glance. I don't see any strong reason to prefer one over the other, though.
Upvotes: 1
Reputation: 9820
You could use Either.cond
from scala.util.Either
:
import scalaz.ValidationNel
import scalaz.syntax.std.either._
import scalaz.syntax.nel._
def toValidationNel[A, E](a: A)(f: A => Boolean, fail: => E) : ValidationNel[E, A] =
Either.cond(f(a), a, fail.wrapNel).validation
Upvotes: 1