aboutsummaryrefslogtreecommitdiff
path: root/aoc-2020-gleam/src/ext/listx.gleam
blob: 0a3d7c310dac3e78dee49e9b77d09f8dad801cf6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import gleam/pair
import gleam/iterator as iter
import gleam/result as res
import gleam/dict.{type Dict}
import ext/iteratorx as iterx

pub fn count(list: List(a), satisfying predicate: fn(a) -> Bool) -> Int {
  list
  |> iter.from_list
  |> iterx.count(satisfying: predicate)
}

pub fn counts(list: List(a)) -> Dict(a, Int) {
  list
  |> iter.from_list
  |> iterx.counts
}

fn set_helper(list: List(a), value: a, index: Int, counter: Int) -> List(a) {
  case list {
    [] -> []
    [_, ..t] if counter == index -> [value, ..t]
    [h, ..t] -> [h, ..set_helper(t, value, index, counter + 1)]
  }
}

pub fn set(list: List(a), value: a, at index: Int) -> List(a) {
  set_helper(list, value, index, 0)
}

pub fn index_of(list: List(a), value: a) -> Result(Int, Nil) {
  list
  |> iter.from_list
  |> iter.index
  |> iter.find(one_that: fn(elem) { pair.first(elem) == value })
  |> res.map(with: pair.second)
}