Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering values on right side of scalaz disjunction

Tags:

scala

scalaz

I have a result consisting of a list of Vectors in a scalaz disjunction and I want to be able to examine and filter out elements from within the right side.

simplified example:

import scalaz._
import Scalaz._

type TL = Throwable \/ List[Vector[Int]]

val goodTL: TL = \/-(List(Vector(1,2,3),Vector(), Vector(2,3,4)))

If I want to remove empty element and also any values != 2 from populated elements I can do the following:

for {
  v <- goodTL
  f = v.flatten
} yield for {
  i <- f
  if i != 2
} yield i

giving a scalaz.\/[Nothing,List[Int]] = \/-(List(1, 3, 3, 4)) which is what I want but I would like to know if there is a less convoluted way of achieving this.

like image 714
Gavin Avatar asked Oct 19 '22 16:10

Gavin


1 Answers

Your version desugars to something very similar to the following:

goodTL.map(_.flatten.filter(_ != 2))

This is a case where I personally find the sugar-free version a lot clearer about what's going on.

like image 78
Travis Brown Avatar answered Oct 23 '22 00:10

Travis Brown