Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

for comprehension - Generalised lazy permutations in Scala

I want to create a generic permutations function.

def permutation(size: Int): Stream[List[Int]] = ...

permutation(1)   # same as: for { x <- (1 to 10).toStream } yield List(x)
permutation(2)   # same as: for { x <- (1 to 10).toStream;
                                  y <- (1 to 10).toStream; } yield List(x,y)

Can I get dynamically nested for-comprehensions behavior on the fly for arbitrary depth.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this gives a generalised version of what you are asking for:

def permutation[X](iter: Iterable[X], len: Int) = {
  def acc(items: List[X], count: Int): Stream[List[X]] = {
    if (count == 0) Stream(items) else iter.toStream.flatMap( x => acc(x :: items, count - 1))
  }

  acc(List.empty[X], len)
}

Example usages:

scala> permutaion(1 to 3, 3)
res4: Stream[List[Int]] = Stream(List(1, 1, 1), ?)

scala> permutaion(1 to 3, 3).toList
res5: List[List[Int]] = List(List(1, 1, 1), ?)
res5: List[List[Int]] = List(List(1, 1, 1), List(2, 1, 1), List(3, 1, 1), List(1, 2, 1), List(2, 2, 1), List(3, 2, 1), List(1, 3, 1), List(2, 3, 1), List(3, 3, 1), List(1, 1, 2), List(2, 1, 2), List(3, 1, 2), List(1, 2, 2), List(2, 2, 2), List(3, 2, 2), List(1, 3, 2), List(2, 3, 2), List(3, 3, 2), List(1, 1, 3), List(2, 1, 3), List(3, 1, 3), List(1, 2, 3), List(2, 2, 3), List(3, 2, 3), List(1, 3, 3), List(2, 3, 3), List(3, 3, 3))

scala> permutation("abc", 3)
res6: Stream[List[Char]] = Stream(List(a, a, a), ?)

scala> permutation("abc", 3).toList
res7: List[List[Char]] = List(List(a, a, a), List(b, a, a), List(c, a, a), List(a, b, a), List(b, b, a), List(c, b, a), List(a, c, a), List(b, c, a), List(c, c, a), List(a, a, b), List(b, a, b), List(c, a, b), List(a, b, b), List(b, b, b), List(c, b, b), List(a, c, b), List(b, c, b), List(c, c, b), List(a, a, c), List(b, a, c), List(c, a, c), List(a, b, c), List(b, b, c), List(c, b, c), List(a, c, c), List(b, c, c), List(c, c, c))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...