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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With