this repo has no description
1import gleam/int
2import gleam/list
3import gleam/result
4import gleam/string
5
6// Gets a char at an index
7pub fn get_char_at_index(str: String, idx: Int) -> String {
8 let assert Ok(char) =
9 str
10 |> string.to_graphemes
11 |> list_get_at(idx)
12
13 char
14}
15
16// Gets item at index in a list
17pub fn list_get_at(list: List(a), index: Int) -> Result(a, String) {
18 case index {
19 0 -> {
20 case list {
21 [x, ..] -> Ok(x)
22 _ -> Error("Overflowing index")
23 }
24 }
25 _ -> {
26 case list {
27 [_, ..y] -> list_get_at(y, index - 1)
28 _ -> Error("Overflowing index")
29 }
30 }
31 }
32}
33
34// Sets value at an index in a list
35pub fn list_set_at(
36 liste: List(a),
37 index: Int,
38 value: a,
39) -> Result(List(a), String) {
40 let #(head, tail) =
41 liste
42 |> list.split(index)
43
44 let popped = list.pop(tail, fn(_) { True })
45
46 case popped {
47 Error(_) -> Error("Index Overflow")
48 Ok(new_head) -> Ok(list.flatten([head, [value], new_head.1]))
49 }
50}
51
52// Creates a loop, somehow
53pub fn loop(
54 value: a,
55 condition: fn(a) -> Bool,
56 post: fn(a) -> a,
57 body: fn(a) -> b,
58) {
59 let res = body(value)
60 let new_value = post(value)
61 case condition(new_value) {
62 False -> res
63 True -> loop(new_value, condition, post, body)
64 }
65}
66
67pub fn create_int_range(start: Int, end: Int) -> List(Int) {
68 loop(
69 [start],
70 fn(lst) { list.last(lst) |> result.unwrap(0) < end },
71 fn(lst) {
72 list.append(lst, [list.last(lst) |> result.unwrap(0) |> int.add(1)])
73 },
74 fn(lst) { lst },
75 )
76}
77
78// Find indexes of items in a list that satisfies a predicate
79pub fn list_find_indexes(liste: List(a), predicate: fn(a) -> Bool) -> List(Int) {
80 let range = create_int_range(0, list.length(liste))
81
82 range
83 |> list.map(fn(idx) {
84 let assert Ok(val) = list_get_at(liste, idx)
85
86 #(idx, predicate(val))
87 })
88 |> list.filter(fn(x) { x.1 == True })
89 |> list.map(fn(x) { x.0 })
90}