更快的置换发生器

Ken*_*oom 7 optimization functional-programming scala list permutation

我为Scala列表编写了一个置换生成器,它生成给定列表的所有排列.到目前为止,基于这个Haskell实现,我得到了以下内容(我认为它比我尝试过的其他几个选项更有效).有没有办法让这个更有效率,或者我覆盖了所有的基础?

   /** For each element x in List xss, returns (x, xss - x) */
   def selections[A](xss:List[A]):List[(A,List[A])] = xss match {
      case Nil => Nil
      case x :: xs =>
         (x, xs) :: (for( (y, ys) <- selections (xs) )
            yield (y, x :: ys))
   }

   /** Returns a list containing all permutations of the input list */
   def permute[A](xs:List[A]):List[List[A]] = xs match {
      case Nil => List(Nil)

      //special case lists of length 1 and 2 for better performance
      case t :: Nil => List(xs)
      case t :: u :: Nil => List(xs,List(u,t))

      case _ => 
         for ( (y,ys) <- selections(xs); ps <- permute(ys))
            yield y :: ps
   }
Run Code Online (Sandbox Code Playgroud)

Eas*_*sun 3

在Scala 2.9中,临时添加了一些有用的方法到scala集合类,包括一个Seq.permutations,它生成这个seq的所有排列。请参阅链接文本。我有一个非递归实现,我认为它会有更好的性能。请参阅SeqLike.permutations 的非递归实现