aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSebastian <s@porto5.com>2020-12-17 14:57:08 +1100
committerLouis Pilfold <louis@lpil.uk>2020-12-17 10:17:03 +0000
commite4d09202ab7d3b0a4bc52213858ce939b0a2a6dd (patch)
tree30a043fdcc3164604dfe76ee97a01162bec3a487 /src
parent095d936bfcbf239d84e329b267aea0d6ebf15d33 (diff)
downloadgleam_stdlib-e4d09202ab7d3b0a4bc52213858ce939b0a2a6dd.tar.gz
gleam_stdlib-e4d09202ab7d3b0a4bc52213858ce939b0a2a6dd.zip
Add list.permutations
Diffstat (limited to 'src')
-rw-r--r--src/gleam/list.gleam24
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
+ }
+}