【问题标题】:write Scala iterative recursion like Python generator像 Python 生成器一样编写 Scala 迭代递归
【发布时间】:2015-05-15 14:29:50
【问题描述】:

我可以使用生成器在 Python 中轻松编写返回迭代器的递归。

像这样的字符串置换函数:

def permute(string):
    if len(string)==1:
        yield string
    else:
        for i in range(len(string)):
            for p in permute(string[:i]+string[i+1:]):
                yield string[i]+p

如何将其翻译成 Scala 版本。 Scala 的iterator 可以在这里工作,还是我们真的需要求助于continuation(没用过,只是听说过)?

【问题讨论】:

    标签: python scala recursion generator


    【解决方案1】:

    您可以使用Stream 获得非常相似的效果:

    def permute[T](list: List[T]): Stream[List[T]] =
      if (list.size == 1) Stream(list)
      else for {
        i <- Stream.range(0, list.size)
        l <- list splitAt i match {
          case (left, el :: right) => permute(left ::: right) map (el :: _)
        }
      } yield l
    

    它适用于长序列的排列。例如,从第 10000 个排列开始,为 100 个元素的 10 个排列打印最后 10 个元素:

    scala> permute(1 to 100 toList) slice (10000, 10010) foreach {
      lst => println(lst.takeRight(10)) }
    List(91, 92, 94, 100, 99, 95, 97, 98, 93, 96)
    List(91, 92, 94, 100, 99, 95, 97, 98, 96, 93)
    List(91, 92, 94, 100, 99, 95, 98, 93, 96, 97)
    List(91, 92, 94, 100, 99, 95, 98, 93, 97, 96)
    List(91, 92, 94, 100, 99, 95, 98, 96, 93, 97)
    List(91, 92, 94, 100, 99, 95, 98, 96, 97, 93)
    List(91, 92, 94, 100, 99, 95, 98, 97, 93, 96)
    List(91, 92, 94, 100, 99, 95, 98, 97, 96, 93)
    List(91, 92, 94, 100, 99, 96, 93, 95, 97, 98)
    List(91, 92, 94, 100, 99, 96, 93, 95, 98, 97)
    

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 2018-11-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2016-05-03
      • 2011-10-06
      相关资源
      最近更新 更多