Created
August 4, 2013 21:08
-
-
Save Bamco/6151962 to your computer and use it in GitHub Desktop.
Ocaml list permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* 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