diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/list.gleam | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 1af34e8..44d1510 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1052,3 +1052,27 @@ pub fn partition( ) -> tuple(List(a), List(a)) { do_partition(list, categorise, [], []) } + +/// Return all the permutations of a list +/// All values must be unique +/// +/// ## Examples +/// +/// > permutations([1, 2]) +/// [[1, 2], [2, 1]] +/// +pub fn permutations(l: List(a)) -> List(List(a)) { + case l { + [] -> [[]] + _ -> + map( + l, + fn(x) { + filter(l, fn(y) { y != x }) + |> permutations + |> map(append([x], _)) + }, + ) + |> flatten + } +} |