Skip to content

Instantly share code, notes, and snippets.

@MassD
Last active August 29, 2015 14:20
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
A implementation for generating all permutations of a list, written in OCaml
(* note that in order to preserve certain order
and also show the conciseness of the implementation,
no tail-recursive is used *)
let ins_all_positions x l =
let rec aux prev acc = function
| [] -> (prev @ [x]) :: acc |> List.rev
| hd::tl as l -> aux (prev @ [hd]) ((prev @ [x] @ l) :: acc) tl
in
aux [] [] l
let rec permutations = function
| [] -> []
| x::[] -> [[x]] (* we must specify this edge case *)
| x::xs -> List.fold_left (fun acc p -> acc @ ins_all_positions x p ) [] (permutations xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment