From e4d09202ab7d3b0a4bc52213858ce939b0a2a6dd Mon Sep 17 00:00:00 2001 From: Sebastian Date: Thu, 17 Dec 2020 14:57:08 +1100 Subject: Add list.permutations --- src/gleam/list.gleam | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'src') 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 + } +} -- cgit v1.2.3