Skip to content

Instantly share code, notes, and snippets.

@Bamco
Created August 4, 2013 21:08
Show Gist options
  • Save Bamco/6151962 to your computer and use it in GitHub Desktop.
Save Bamco/6151962 to your computer and use it in GitHub Desktop.
Ocaml list permutations
(* interleave 1 [2;3] = [ [1;2;3]; [2;1;3]; [2;3;1] ] *)
let rec interleave x lst =
match lst with
| [] -> [[x]]
| hd::tl -> (x::lst) :: (List.map (fun y -> hd::y) (interleave x tl))
(*permutations [1; 2; 3] = [[1; 2; 3]; [2; 1; 3]; [2; 3; 1]; [1; 3; 2]; [3; 1; 2]; [3; 2; 1]] *)
let rec permutations lst =
match lst with
| hd::tl -> List.concat (List.map (interleave hd) (permutations tl))
| _ -> [lst]
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment