Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala method to combine each element of an iterable with each element of another?

If I have this:

val a = Array("a ","b ","c ")
val b = Array("x","y")

I would like to know if such a method exists which would let me traverse the first collection, and for each of it's elements, walk the entire second collection. For example, if we take the array a, we would have a,x,a,y,b,x,b,y,c,x,c,y. I know of zip but from what I've seen it only works on collections of the same sizes, and it associates elements from same positions.

like image 457
Geo Avatar asked May 10 '11 20:05

Geo


People also ask

How to combine 2 List in Scala?

In order to concatenate two lists we need to utilize concat() method in Scala. In above syntax, l1 is list1 and l2 is list2. Below is the example to concat two lists in scala. Here, the identical elements are not removed.

What is Iterable type in Scala?

Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements.


1 Answers

Here's one more that does the same thing as @ziggystar's last edit but doesn't use indexed access of lists.

def combinationIterator[A](xs: Iterable[Iterable[A]]): Iterator[List[A]] = {
  xs.foldRight(Iterator(List[A]())) { (heads, tails) =>
    tails.flatMap { tail =>
      heads.map(head => head :: tail)
    }
  }
}

And the sugary version:

def combinationIterator[A](xs: Iterable[Iterable[A]]): Iterator[List[A]] = {
  (xs :\ Iterator(List[A]())) { (heads, tails) =>
    for (tail <- tails; head <- heads) yield head :: tail
  }
}
like image 101
Ian Tabolt Avatar answered Sep 26 '22 00:09

Ian Tabolt