Forked from MassD/permutations_ins_into_all_positions.ml
Created
November 27, 2023 04:10
-
-
Save jgarte/6e116a9f7a76e5ceabf47792cc0153a3 to your computer and use it in GitHub Desktop.
A implementation for generating all permutations of a list, written 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
(* 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