Scala中用于多个生成器的通用函数在for推导式中。

3

假设我想创建所有可能的字母组合"a"和"b"。对于长度为2的组合,使用for循环可以这样实现:

for {
   x <- Seq("a", "b") 
   y <- Seq("a", "b")
} yield x + y

对于长度为3的组合,它将是:
for {
   x <- Seq("a", "b") 
   y <- Seq("a", "b")
   z <- Seq("a", "b")
} yield x + y + z

相当相似。能否将此模式抽象出来,编写通用函数? 我可以想到这样的签名:
def genericCombine[A,B](length: Int, elements: Seq[A])(reducer: Seq[A] => B): Seq[B]

如何在for循环中使用参数化的生成器数量?

1个回答

4
这更像是带有替换的排列,而递归实现相当简单:
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

正常工作:

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)

(在实际应用中,您当然需要检查无效输入。)

能否将其转换为尾递归? :-} - Ashalynd
谢谢Travis!现在看起来确实很简单。 - michal
1
无论是尾递归还是非尾递归,都不重要,因为输出大小呈指数增长 :) - Ashalynd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接