diff options
author | Sebastian Porto <s@porto5.com> | 2021-04-24 20:36:42 +1000 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-04-29 20:24:23 +0100 |
commit | 37279f753cb241016be2d3e25a0fa665072b643c (patch) | |
tree | 7d19bc498487a9a4e1c796976429d042721d8141 /src | |
parent | 1887709e22f969b43e7e9c2ff9918bd8bc9ec114 (diff) | |
download | gleam_stdlib-37279f753cb241016be2d3e25a0fa665072b643c.tar.gz gleam_stdlib-37279f753cb241016be2d3e25a0fa665072b643c.zip |
Add list.combinations
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/list.gleam | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 17ee57d..873f5ad 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1452,3 +1452,49 @@ pub fn last(list: List(a)) -> Result(a, Nil) { list |> reduce(fn(elem, _) { elem }) } + +/// Return unique combinations of elements in the list +/// +/// ## Examples +/// +/// ``` +/// > combinations_by([1, 2, 3], 2) +/// [[1, 2], [1, 3], [2, 3]] +/// +/// > combinations_by([1, 2, 3, 4], 3) +/// [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]] +/// ``` +/// +pub fn combinations_by(items: List(a), n: Int) -> List(List(a)) { + case n { + 0 -> [[]] + _ -> + case items { + [] -> [] + [x, ..xs] -> { + let first_combinations = + map(combinations_by(xs, n - 1), with: fn(com) { [x, ..com] }) + append(first_combinations, combinations_by(xs, n)) + } + } + } +} + +/// Return unique pair combinations of elements in the list +/// +/// ## Examples +/// +/// ``` +/// > combinations_by_2([1, 2, 3]) +/// [tuple(1, 2), tuple(1, 3), tuple(2, 3)] +/// ``` +/// +pub fn combinations_by_2(items: List(a)) -> List(tuple(a, a)) { + case items { + [] -> [] + [x, ..xs] -> { + let first_combinations = map(xs, with: fn(other) { tuple(x, other) }) + append(first_combinations, combinations_by_2(xs)) + } + } +} |