簡體   English   中英

像Python生成器一樣編寫Scala迭代遞歸

[英]write Scala iterative recursion like Python 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

我如何將其翻譯成Scala版本。 Scala的iterator可以在這里工作,還是我們真的需要訴諸於continuation (從未使用過,只是聽說過)?

您可以使用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

它適用於長序列的排列。 例如,打印最后10個元素,以從第10000個排列開始的100個元素的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM