Let's say I want to create all possible combinations of letters "a" and "b". For combinations of length 2 using for-comprehensions it will be:
for {
x <- Seq("a", "b")
y <- Seq("a", "b")
} yield x + y
And for combinations of length 3 it will be:
for {
x <- Seq("a", "b")
y <- Seq("a", "b")
z <- Seq("a", "b")
} yield x + y + z
Pretty similar. Is this possible to abstract this pattern and write generic function? I can think of such signature:
def genericCombine[A,B](length: Int, elements: Seq[A])(reducer: Seq[A] => B): Seq[B]
How can I parametrize number of generators used in for comprehension?
This is more like permutations with replacement than combinations, and a recursive implementation is fairly straightforward:
def select(n: Int)(input: List[String]): List[String] =
if (n == 1) input else for {
c <- input
s <- select(n - 1)(input)
} yield c + s
Which works as expected:
scala> select(2)(List("a", "b"))
res0: List[String] = List(aa, ab, ba, bb)
scala> select(3)(List("a", "b"))
res1: List[String] = List(aaa, aab, aba, abb, baa, bab, bba, bbb)
(You should of course check for invalid input in a real application.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments