Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写类似Python生成器的Scala迭代递归_Python_Scala_Recursion_Generator - Fatal编程技术网

编写类似Python生成器的Scala迭代递归

编写类似Python生成器的Scala迭代递归,python,scala,recursion,generator,Python,Scala,Recursion,Generator,我可以很容易地用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 如何将

我可以很容易地用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的
迭代器能否在这里工作,还是我们真的需要求助于
continuation
(从未使用过,只是听说过它)?

您可以使用它获得非常类似的效果:

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
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)