jaybee
jaybee

Reputation: 1925

fold that produces a tuple (avoiding multiple traversals of the input)

I have a list and want to use this to produce three lists. I can do this with two applications of filter:

val z_out = zs.filter(p1)
val z_in = zs.filter(p2)
val z_split = zs.diff(z_out union z_in)

Can I do this with one traversal of the list? As in:

val (z_out, z_in, z_split) = zs.foldLeft(...)

Upvotes: 1

Views: 894

Answers (1)

pedrofurla
pedrofurla

Reputation: 12783

You can, as long as the result of fold is a tuple:

scala> val (a,b,c) = Nil.foldLeft((1,2,3))((x,y) => x)
a: Int = 1
b: Int = 2
c: Int = 3

Upvotes: 1

Related Questions