rivu
rivu

Reputation: 2504

scala: generating tuples from a list

I have a list val l=List(4,3,2,1), I am trying to generate a list of tuples of the format (4,3), (4,2) and so on.

Here's what I have so far:

for (i1<-0 to l.length-1;i2<-i1+1 to l.length-1) yield (l(i1),l(i2))

The output is : Vector((4,3), (4,2), (4,1), (3,2), (3,1), (2,1))

Two questions:

  1. It generates a Vector, not a List. How are these two different?

  2. Is this the idiomatic scala way of doing this? I am very new to Scala, so it's important to me that I learn right.

Upvotes: 3

Views: 810

Answers (1)

elm
elm

Reputation: 20405

On the first part of the question, the for comprehension implementation defines ranges 0 to l.length-1 and i1+1 to l.length-1 as IndexedSeq[Int] hence the yielded type is trait IndexedSeq[(Int, Int)] implemented by final class Vector.

On the second part, your approach is valid, yet consider the following where we do not use indexed references to the lists,

for (List(a,b,_*) <- xs.combinations(2).toList) yield (a,b)

Note that

xs.combinations(2).toList
List(List(4, 3), List(4, 2), List(4, 1), List(3, 2), List(3, 1), List(2, 1))

and so with List(a,b,_*) we pattern-match and extract the first two elements of each nested list (the _* indicates to ignore possible additional elements). Since the iteration is over a list, the for comprehension yields a list of duples.

Upvotes: 6

Related Questions