Permutations: Difference between revisions

→‎{{header|Scala}}: Partial function using for-comprehension
(→‎{{header|Scala}}: Partial function using for-comprehension)
Line 4,465:
List(3, 1, 2)
List(3, 2, 1)
 
 
The following function returns all the unique permutation of a list:
 
<pre>
<lang scala> def permutations[T](list: List[T]):List => Traversable[List[T]] = {
listcase matchNil {=> List(Nil)
case Nilxs => Nil{
for {
case elem :: Nil => List(list)
i <- 0 until xs.length
case head :: tail => list.distinct.foldLeft(List[List[T]]()) ((lst, elem)=> lst ++ ((permutations(list.diff(List(elem)))).map((l)=> (elem :: l))))
ys <- permutations(xs.take(i) ++ xs.drop(1 + i))
}</pre>
} yield {
xs(i) :: ys
}
}
}</lang>
 
=={{header|Scheme}}==
Anonymous user