Skip to content

Instantly share code, notes, and snippets.

@linstantnoodles
Created December 20, 2012 19:51
Show Gist options
  • Save linstantnoodles/4348046 to your computer and use it in GitHub Desktop.
Save linstantnoodles/4348046 to your computer and use it in GitHub Desktop.
generate all sublists of a list
(*let A = [1;2;3]
* genSublists A will yield
* [[1]; [1; 2]; [1; 3]; [1; 2; 3];[2]; [2; 3]; [3]; []] *)
let rec gen list head =
match list with
[] -> []
| first::rest -> let start = (head @ [first]) in
let rec append list =
match list with
[] -> []
| first'::rest' -> [start@[first']] @ append rest' in
append rest @ (gen rest start);;
let rec genSublists list =
match list with
[] -> [[]]
| first::rest as a -> [[first]] @ (gen a []) @ (genSublists rest);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment