Sunday, 6 May 2012

Compute all permutations


The following permute function computes all permutations of the elements in the given list:
let rec distribute e = function
  | [] -> [[e]]
  | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]
let rec permute = function
  | [] -> [[]]
  | e::xs -> List.collect (distribute e) (permute xs)

No comments: