Skip to content

Instantly share code, notes, and snippets.

@komamitsu
Created May 23, 2012 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komamitsu/2776294 to your computer and use it in GitHub Desktop.
Save komamitsu/2776294 to your computer and use it in GitHub Desktop.
2 permutations in OCaml
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