Created
May 23, 2012 16:44
-
-
Save komamitsu/2776294 to your computer and use it in GitHub Desktop.
2 permutations in OCaml
This file contains 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
let ($) f g = f g | |
let rec perm xs n l total = | |
if n <= 0 then l::total | |
else begin | |
List.flatten $ | |
List.map (fun c -> perm xs (n - 1) (c::l) total) xs | |
end | |
let rec perm2 xs n = | |
if n <= 0 then [[]] | |
else | |
List.flatten $ | |
List.map (fun acc -> | |
List.map (fun x -> x::acc) xs | |
) (perm2 xs (n - 1)) | |
let _ = | |
let p xs = | |
List.iter (fun l -> | |
List.iter (fun x -> Printf.printf "%d " x) l; | |
print_newline () | |
) xs in | |
let line () = print_endline "--------------------------" in | |
line (); | |
p $ perm [1; 2; 3] 2 [] []; | |
line (); | |
p $ perm2 [1; 2; 3] 2 | |
$ ocaml perm.ml | |
-------------------------- | |
1 1 | |
2 1 | |
3 1 | |
1 2 | |
2 2 | |
3 2 | |
1 3 | |
2 3 | |
3 3 | |
-------------------------- | |
1 1 | |
2 1 | |
3 1 | |
1 2 | |
2 2 | |
3 2 | |
1 3 | |
2 3 | |
3 3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment