Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulating only validation errors in Scalaz

Tags:

scala

scalaz

I am a beginner in the work of functional programming and I have a sequence of ValidationNEL[A,B] and I would like to accumulate the errors into a new ValidationNEL[A,B]. This depends on the fact that B is a mutable data structure coming from legacy code, and so it would be oververbose to hold a Seq[B].

I know from other posts that cumulating errors and success is possible through the sequence method: Processing a list of Scalaz6 Validation

From my understanding it all comes to writing a proper Applicative and maybe a proper Traverse.

  trait MA[M[_], A] extends PimpedType[M[A]] with MASugar[M, A] {

    def sequence[N[_], B](implicit a: A <:< N[B], t: Traverse[M], n: Applicative[N]): N[M[B]] =
    traverse((z: A) => (z: N[B]))

  def traverse[F[_],B](f: A => F[B])(implicit a: Applicative[F], t: Traverse[M]): F[M[B]] =
    t.traverse(f, value)
  }

How do I start? When I tried to look into Scalaz source code to find out how to implement my Applicative, I got extremely confused. I was not even able to find out which applicative allows accumulating both failures and success in Validation.

like image 936
Edmondo1984 Avatar asked Feb 18 '13 15:02

Edmondo1984


Video Answer


1 Answers

Late to the party, but as of Scalaz 7.0.4, we can do this:

  def takeLastSuccess[A, B](seq: Seq[ValidationNel[A, B]]) = {
      implicit val useLast = Semigroup.lastSemigroup[B]
      seq reduceLeft (_ +++ _)
  }
like image 55
AlecZorab Avatar answered Sep 25 '22 00:09

AlecZorab