/
list.gleam
2152 lines (2040 loc) Β· 45.3 KB
/
list.gleam
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//// Lists are an ordered sequence of elements and are one of the most common
//// data types in Gleam.
////
//// New elements can be added and removed from the front of a list in
//// constant time, while adding and removing from the end requires traversing
//// the copying the whole list, so keep this in mind when designing your
//// programs.
////
//// There is a dedicated syntax for prefixing to a list:
////
//// ```gleam
//// let new_list = [1, 2, ..existing_list]
//// ```
////
//// And a matching syntax for getting the first elements of a list:
////
//// ```gleam
//// case list {
//// [first_element, ..rest] -> first_element
//// _ -> "this pattern matches when the list is empty"
//// }
//// ```
////
import gleam/int
import gleam/float
import gleam/order.{type Order}
import gleam/pair
import gleam/dict.{type Dict}
/// An error value returned by the `strict_zip` function.
///
pub type LengthMismatch {
LengthMismatch
}
/// Counts the number of elements in a given list.
///
/// This function has to traverse the list to determine the number of elements,
/// so it runs in linear time.
///
/// This function is natively implemented by the virtual machine and is highly
/// optimised.
///
/// ## Examples
///
/// ```gleam
/// length([])
/// // -> 0
/// ```
///
/// ```gleam
/// length([1])
/// // -> 1
/// ```
///
/// ```gleam
/// length([1, 2])
/// // -> 2
/// ```
///
pub fn length(of list: List(a)) -> Int {
do_length(list)
}
@target(erlang)
@external(erlang, "erlang", "length")
fn do_length(a: List(a)) -> Int
@target(javascript)
fn do_length(list: List(a)) -> Int {
do_length_acc(list, 0)
}
@target(javascript)
fn do_length_acc(list: List(a), count: Int) -> Int {
case list {
[_, ..list] -> do_length_acc(list, count + 1)
_ -> count
}
}
/// Creates a new list from a given list containing the same elements but in the
/// opposite order.
///
/// This function has to traverse the list to create the new reversed list, so
/// it runs in linear time.
///
/// This function is natively implemented by the virtual machine and is highly
/// optimised.
///
/// ## Examples
///
/// ```gleam
/// reverse([])
/// // -> []
/// ```
///
/// ```gleam
/// reverse([1])
/// // -> [1]
/// ```
///
/// ```gleam
/// reverse([1, 2])
/// // -> [2, 1]
/// ```
///
pub fn reverse(xs: List(a)) -> List(a) {
do_reverse(xs)
}
@target(erlang)
@external(erlang, "lists", "reverse")
fn do_reverse(a: List(a)) -> List(a)
@target(javascript)
fn do_reverse(list) {
do_reverse_acc(list, [])
}
@target(javascript)
fn do_reverse_acc(remaining, accumulator) {
case remaining {
[] -> accumulator
[item, ..rest] -> do_reverse_acc(rest, [item, ..accumulator])
}
}
/// Determines whether or not the list is empty.
///
/// This function runs in constant time.
///
/// ## Examples
///
/// ```gleam
/// is_empty([])
/// // -> True
/// ```
///
/// ```gleam
/// is_empty([1])
/// // -> False
/// ```
///
/// ```gleam
/// is_empty([1, 1])
/// // -> False
/// ```
///
pub fn is_empty(list: List(a)) -> Bool {
list == []
}
/// Determines whether or not a given element exists within a given list.
///
/// This function traverses the list to find the element, so it runs in linear
/// time.
///
/// ## Examples
///
/// ```gleam
/// [] |> contains(any: 0)
/// // -> False
/// ```
///
/// ```gleam
/// [0] |> contains(any: 0)
/// // -> True
/// ```
///
/// ```gleam
/// [1] |> contains(any: 0)
/// // -> False
/// ```
///
/// ```gleam
/// [1, 1] |> contains(any: 0)
/// // -> False
/// ```
///
/// ```gleam
/// [1, 0] |> contains(any: 0)
/// // -> True
/// ```
///
pub fn contains(list: List(a), any elem: a) -> Bool {
case list {
[] -> False
[first, ..] if first == elem -> True
[_, ..rest] -> contains(rest, elem)
}
}
/// Gets the first element from the start of the list, if there is one.
///
/// ## Examples
///
/// ```gleam
/// first([])
/// // -> Error(Nil)
/// ```
///
/// ```gleam
/// first([0])
/// // -> Ok(0)
/// ```
///
/// ```gleam
/// first([1, 2])
/// // -> Ok(1)
/// ```
///
pub fn first(list: List(a)) -> Result(a, Nil) {
case list {
[] -> Error(Nil)
[x, ..] -> Ok(x)
}
}
/// Returns the list minus the first element. If the list is empty, `Error(Nil)` is
/// returned.
///
/// This function runs in constant time and does not make a copy of the list.
///
/// ## Examples
///
/// ```gleam
/// rest([])
/// // -> Error(Nil)
/// ```
///
/// ```gleam
/// rest([0])
/// // -> Ok([])
/// ```
///
/// ```gleam
/// rest([1, 2])
/// // -> Ok([2])
/// ```
///
pub fn rest(list: List(a)) -> Result(List(a), Nil) {
case list {
[] -> Error(Nil)
[_, ..xs] -> Ok(xs)
}
}
fn update_group(
f: fn(element) -> key,
) -> fn(Dict(key, List(element)), element) -> Dict(key, List(element)) {
fn(groups, elem) {
case dict.get(groups, f(elem)) {
Ok(existing) -> dict.insert(groups, f(elem), [elem, ..existing])
Error(_) -> dict.insert(groups, f(elem), [elem])
}
}
}
/// Takes a list and groups the values by a key
/// which is built from a key function.
///
/// Does not preserve the initial value order.
///
/// ## Examples
///
/// ```gleam
/// import gleam/dict
///
/// [Ok(3), Error("Wrong"), Ok(200), Ok(73)]
/// |> group(by: fn(i) {
/// case i {
/// Ok(_) -> "Successful"
/// Error(_) -> "Failed"
/// }
/// })
/// |> dict.to_list
/// // -> [
/// // #("Failed", [Error("Wrong")]),
/// // #("Successful", [Ok(73), Ok(200), Ok(3)])
/// // ]
/// ```
///
/// ```gleam
/// import gleam/dict
/// group([1,2,3,4,5], by: fn(i) { i - i / 3 * 3 })
/// |> dict.to_list
/// // -> [#(0, [3]), #(1, [4, 1]), #(2, [5, 2])]
/// ```
///
pub fn group(list: List(v), by key: fn(v) -> k) -> Dict(k, List(v)) {
fold(list, dict.new(), update_group(key))
}
fn do_filter(list: List(a), fun: fn(a) -> Bool, acc: List(a)) -> List(a) {
case list {
[] -> reverse(acc)
[x, ..xs] -> {
let new_acc = case fun(x) {
True -> [x, ..acc]
False -> acc
}
do_filter(xs, fun, new_acc)
}
}
}
/// Returns a new list containing only the elements from the first list for
/// which the given functions returns `True`.
///
/// ## Examples
///
/// ```gleam
/// filter([2, 4, 6, 1], fn(x) { x > 2 })
/// // -> [4, 6]
/// ```
///
/// ```gleam
/// filter([2, 4, 6, 1], fn(x) { x > 6 })
/// // -> []
/// ```
///
pub fn filter(list: List(a), keeping predicate: fn(a) -> Bool) -> List(a) {
do_filter(list, predicate, [])
}
fn do_filter_map(
list: List(a),
fun: fn(a) -> Result(b, e),
acc: List(b),
) -> List(b) {
case list {
[] -> reverse(acc)
[x, ..xs] -> {
let new_acc = case fun(x) {
Ok(x) -> [x, ..acc]
Error(_) -> acc
}
do_filter_map(xs, fun, new_acc)
}
}
}
/// Returns a new list containing only the elements from the first list for
/// which the given functions returns `Ok(_)`.
///
/// ## Examples
///
/// ```gleam
/// filter_map([2, 4, 6, 1], Error)
/// // -> []
/// ```
///
/// ```gleam
/// filter_map([2, 4, 6, 1], fn(x) { Ok(x + 1) })
/// // -> [3, 5, 7, 2]
/// ```
///
pub fn filter_map(list: List(a), with fun: fn(a) -> Result(b, e)) -> List(b) {
do_filter_map(list, fun, [])
}
fn do_map(list: List(a), fun: fn(a) -> b, acc: List(b)) -> List(b) {
case list {
[] -> reverse(acc)
[x, ..xs] -> do_map(xs, fun, [fun(x), ..acc])
}
}
/// Returns a new list containing only the elements of the first list after the
/// function has been applied to each one.
///
/// ## Examples
///
/// ```gleam
/// map([2, 4, 6], fn(x) { x * 2 })
/// // -> [4, 8, 12]
/// ```
///
pub fn map(list: List(a), with fun: fn(a) -> b) -> List(b) {
do_map(list, fun, [])
}
/// Combines two lists into a single list using the given function.
///
/// If a list is longer than the other the extra elements are dropped.
///
/// ## Examples
///
/// ```gleam
/// map2([1, 2, 3], [4, 5, 6], fn(x, y) { x + y })
/// // -> [5, 7, 9]
/// ```
///
/// ```gleam
/// map2([1, 2], ["a", "b", "c"], fn(i, x) { #(i, x) })
/// // -> [#(1, "a"), #(2, "b")]
/// ```
///
pub fn map2(
list1: List(a),
list2: List(b),
with fun: fn(a, b) -> c,
) -> List(c) {
do_map2(list1, list2, fun, [])
}
fn do_map2(
list1: List(a),
list2: List(b),
fun: fn(a, b) -> c,
acc: List(c),
) -> List(c) {
case list1, list2 {
[], _ | _, [] -> reverse(acc)
[a, ..as_], [b, ..bs] -> do_map2(as_, bs, fun, [fun(a, b), ..acc])
}
}
/// Similar to `map` but also lets you pass around an accumulated value.
///
/// ## Examples
///
/// ```gleam
/// map_fold(
/// over: [1, 2, 3],
/// from: 100,
/// with: fn(memo, i) { #(memo + i, i * 2) }
/// )
/// // -> #(106, [2, 4, 6])
/// ```
///
pub fn map_fold(
over list: List(a),
from acc: acc,
with fun: fn(acc, a) -> #(acc, b),
) -> #(acc, List(b)) {
fold(over: list, from: #(acc, []), with: fn(acc, item) {
let #(current_acc, items) = acc
let #(next_acc, next_item) = fun(current_acc, item)
#(next_acc, [next_item, ..items])
})
|> pair.map_second(reverse)
}
fn do_index_map(
list: List(a),
fun: fn(a, Int) -> b,
index: Int,
acc: List(b),
) -> List(b) {
case list {
[] -> reverse(acc)
[x, ..xs] -> {
let acc = [fun(x, index), ..acc]
do_index_map(xs, fun, index + 1, acc)
}
}
}
/// Returns a new list containing only the elements of the first list after the
/// function has been applied to each one and their index.
///
/// The index starts at 0, so the first element is 0, the second is 1, and so
/// on.
///
/// ## Examples
///
/// ```gleam
/// index_map(["a", "b"], fn(x, i) { #(i, x) })
/// // -> [#(0, "a"), #(1, "b")]
/// ```
///
pub fn index_map(list: List(a), with fun: fn(a, Int) -> b) -> List(b) {
do_index_map(list, fun, 0, [])
}
fn do_try_map(
list: List(a),
fun: fn(a) -> Result(b, e),
acc: List(b),
) -> Result(List(b), e) {
case list {
[] -> Ok(reverse(acc))
[x, ..xs] ->
case fun(x) {
Ok(y) -> do_try_map(xs, fun, [y, ..acc])
Error(error) -> Error(error)
}
}
}
/// Takes a function that returns a `Result` and applies it to each element in a
/// given list in turn.
///
/// If the function returns `Ok(new_value)` for all elements in the list then a
/// list of the new values is returned.
///
/// If the function returns `Error(reason)` for any of the elements then it is
/// returned immediately. None of the elements in the list are processed after
/// one returns an `Error`.
///
/// ## Examples
///
/// ```gleam
/// try_map([1, 2, 3], fn(x) { Ok(x + 2) })
/// // -> Ok([3, 4, 5])
/// ```
///
/// ```gleam
/// try_map([1, 2, 3], fn(_) { Error(0) })
/// // -> Error(0)
/// ```
///
/// ```gleam
/// try_map([[1], [2, 3]], first)
/// // -> Ok([1, 2])
/// ```
///
/// ```gleam
/// try_map([[1], [], [2]], first)
/// // -> Error(Nil)
/// ```
///
pub fn try_map(
over list: List(a),
with fun: fn(a) -> Result(b, e),
) -> Result(List(b), e) {
do_try_map(list, fun, [])
}
/// Returns a list that is the given list with up to the given number of
/// elements removed from the front of the list.
///
/// If the element has less than the number of elements an empty list is
/// returned.
///
/// This function runs in linear time but does not copy the list.
///
/// ## Examples
///
/// ```gleam
/// drop([1, 2, 3, 4], 2)
/// // -> [3, 4]
/// ```
///
/// ```gleam
/// drop([1, 2, 3, 4], 9)
/// // -> []
/// ```
///
pub fn drop(from list: List(a), up_to n: Int) -> List(a) {
case n <= 0 {
True -> list
False ->
case list {
[] -> []
[_, ..xs] -> drop(xs, n - 1)
}
}
}
fn do_take(list: List(a), n: Int, acc: List(a)) -> List(a) {
case n <= 0 {
True -> reverse(acc)
False ->
case list {
[] -> reverse(acc)
[x, ..xs] -> do_take(xs, n - 1, [x, ..acc])
}
}
}
/// Returns a list containing the first given number of elements from the given
/// list.
///
/// If the element has less than the number of elements then the full list is
/// returned.
///
/// This function runs in linear time but does not copy the list.
///
/// ## Examples
///
/// ```gleam
/// take([1, 2, 3, 4], 2)
/// // -> [1, 2]
/// ```
///
/// ```gleam
/// take([1, 2, 3, 4], 9)
/// // -> [1, 2, 3, 4]
/// ```
///
pub fn take(from list: List(a), up_to n: Int) -> List(a) {
do_take(list, n, [])
}
/// Returns a new empty list.
///
/// ## Examples
///
/// ```gleam
/// new()
/// // -> []
/// ```
///
pub fn new() -> List(a) {
[]
}
/// Joins one list onto the end of another.
///
/// This function runs in linear time, and it traverses and copies the first
/// list.
///
/// ## Examples
///
/// ```gleam
/// append([1, 2], [3])
/// // -> [1, 2, 3]
/// ```
///
pub fn append(first: List(a), second: List(a)) -> List(a) {
do_append(first, second)
}
@target(erlang)
@external(erlang, "lists", "append")
fn do_append(a: List(a), b: List(a)) -> List(a)
@target(javascript)
fn do_append(first: List(a), second: List(a)) -> List(a) {
do_append_acc(reverse(first), second)
}
@target(javascript)
fn do_append_acc(first: List(a), second: List(a)) -> List(a) {
case first {
[] -> second
[item, ..rest] -> do_append_acc(rest, [item, ..second])
}
}
/// Prefixes an item to a list. This can also be done using the dedicated
/// syntax instead
///
/// ```gleam
/// let existing_list = [2, 3, 4]
///
/// [1, ..existing_list]
/// // -> [1, 2, 3, 4]
///
/// prepend(to: existing_list, this: 1)
/// // -> [1, 2, 3, 4]
/// ```
///
pub fn prepend(to list: List(a), this item: a) -> List(a) {
[item, ..list]
}
// Reverses a list and prepends it to another list
fn reverse_and_prepend(list prefix: List(a), to suffix: List(a)) -> List(a) {
case prefix {
[] -> suffix
[first, ..rest] -> reverse_and_prepend(list: rest, to: [first, ..suffix])
}
}
fn do_concat(lists: List(List(a)), acc: List(a)) -> List(a) {
case lists {
[] -> reverse(acc)
[list, ..further_lists] ->
do_concat(further_lists, reverse_and_prepend(list: list, to: acc))
}
}
/// Joins a list of lists into a single list.
///
/// This function traverses all elements twice.
///
/// ## Examples
///
/// ```gleam
/// concat([[1], [2, 3], []])
/// // -> [1, 2, 3]
/// ```
///
pub fn concat(lists: List(List(a))) -> List(a) {
do_concat(lists, [])
}
/// This is the same as `concat`: it joins a list of lists into a single
/// list.
///
/// This function traverses all elements twice.
///
/// ## Examples
///
/// ```gleam
/// flatten([[1], [2, 3], []])
/// // -> [1, 2, 3]
/// ```
///
pub fn flatten(lists: List(List(a))) -> List(a) {
do_concat(lists, [])
}
/// Maps the list with the given function into a list of lists, and then flattens it.
///
/// ## Examples
///
/// ```gleam
/// flat_map([2, 4, 6], fn(x) { [x, x + 1] })
/// // -> [2, 3, 4, 5, 6, 7]
/// ```
///
pub fn flat_map(over list: List(a), with fun: fn(a) -> List(b)) -> List(b) {
map(list, fun)
|> concat
}
/// Reduces a list of elements into a single value by calling a given function
/// on each element, going from left to right.
///
/// `fold([1, 2, 3], 0, add)` is the equivalent of
/// `add(add(add(0, 1), 2), 3)`.
///
/// This function runs in linear time.
///
pub fn fold(
over list: List(a),
from initial: acc,
with fun: fn(acc, a) -> acc,
) -> acc {
case list {
[] -> initial
[x, ..rest] -> fold(rest, fun(initial, x), fun)
}
}
/// Reduces a list of elements into a single value by calling a given function
/// on each element, going from right to left.
///
/// `fold_right([1, 2, 3], 0, add)` is the equivalent of
/// `add(add(add(0, 3), 2), 1)`.
///
/// This function runs in linear time.
///
/// Unlike `fold` this function is not tail recursive. Where possible use
/// `fold` instead as it will use less memory.
///
pub fn fold_right(
over list: List(a),
from initial: acc,
with fun: fn(acc, a) -> acc,
) -> acc {
case list {
[] -> initial
[x, ..rest] -> fun(fold_right(rest, initial, fun), x)
}
}
fn do_index_fold(
over: List(a),
acc: acc,
with: fn(acc, a, Int) -> acc,
index: Int,
) -> acc {
case over {
[] -> acc
[first, ..rest] ->
do_index_fold(rest, with(acc, first, index), with, index + 1)
}
}
/// Like fold but the folding function also receives the index of the current element.
///
/// ## Examples
///
/// ```gleam
/// ["a", "b", "c"]
/// |> index_fold([], fn(acc, item, index) { ... })
/// ```
///
pub fn index_fold(
over over: List(a),
from initial: acc,
with fun: fn(acc, a, Int) -> acc,
) -> acc {
do_index_fold(over, initial, fun, 0)
}
/// A variant of fold that might fail.
///
/// The folding function should return `Result(accumulator, error)`.
/// If the returned value is `Ok(accumulator)` try_fold will try the next value in the list.
/// If the returned value is `Error(error)` try_fold will stop and return that error.
///
/// ## Examples
///
/// ```gleam
/// [1, 2, 3, 4]
/// |> try_fold(0, fn(acc, i) {
/// case i < 3 {
/// True -> Ok(acc + i)
/// False -> Error(Nil)
/// }
/// })
/// // -> Error(Nil)
/// ```
///
pub fn try_fold(
over collection: List(a),
from accumulator: acc,
with fun: fn(acc, a) -> Result(acc, e),
) -> Result(acc, e) {
case collection {
[] -> Ok(accumulator)
[first, ..rest] ->
case fun(accumulator, first) {
Ok(result) -> try_fold(rest, result, fun)
Error(_) as error -> error
}
}
}
pub type ContinueOrStop(a) {
Continue(a)
Stop(a)
}
/// A variant of fold that allows to stop folding earlier.
///
/// The folding function should return `ContinueOrStop(accumulator)`.
/// If the returned value is `Continue(accumulator)` fold_until will try the next value in the list.
/// If the returned value is `Stop(accumulator)` fold_until will stop and return that accumulator.
///
/// ## Examples
///
/// ```gleam
/// [1, 2, 3, 4]
/// |> fold_until(0, fn(acc, i) {
/// case i < 3 {
/// True -> Continue(acc + i)
/// False -> Stop(acc)
/// }
/// })
/// // -> 6
/// ```
///
pub fn fold_until(
over collection: List(a),
from accumulator: acc,
with fun: fn(acc, a) -> ContinueOrStop(acc),
) -> acc {
case collection {
[] -> accumulator
[first, ..rest] ->
case fun(accumulator, first) {
Continue(next_accumulator) -> fold_until(rest, next_accumulator, fun)
Stop(b) -> b
}
}
}
/// Finds the first element in a given list for which the given function returns
/// `True`.
///
/// Returns `Error(Nil)` if no such element is found.
///
/// ## Examples
///
/// ```gleam
/// find([1, 2, 3], fn(x) { x > 2 })
/// // -> Ok(3)
/// ```
///
/// ```gleam
/// find([1, 2, 3], fn(x) { x > 4 })
/// // -> Error(Nil)
/// ```
///
/// ```gleam
/// find([], fn(_) { True })
/// // -> Error(Nil)
/// ```
///
pub fn find(
in haystack: List(a),
one_that is_desired: fn(a) -> Bool,
) -> Result(a, Nil) {
case haystack {
[] -> Error(Nil)
[x, ..rest] ->
case is_desired(x) {
True -> Ok(x)
_ -> find(in: rest, one_that: is_desired)
}
}
}
/// Finds the first element in a given list for which the given function returns
/// `Ok(new_value)`, then returns the wrapped `new_value`.
///
/// Returns `Error(Nil)` if no such element is found.
///
/// ## Examples
///
/// ```gleam
/// find_map([[], [2], [3]], first)
/// // -> Ok(2)
/// ```
///
/// ```gleam
/// find_map([[], []], first)
/// // -> Error(Nil)
/// ```
///
/// ```gleam
/// find_map([], first)
/// // -> Error(Nil)
/// ```
///
pub fn find_map(
in haystack: List(a),
with fun: fn(a) -> Result(b, c),
) -> Result(b, Nil) {
case haystack {
[] -> Error(Nil)
[x, ..rest] ->
case fun(x) {
Ok(x) -> Ok(x)
_ -> find_map(in: rest, with: fun)
}
}
}
/// Returns `True` if the given function returns `True` for all the elements in
/// the given list. If the function returns `False` for any of the elements it
/// immediately returns `False` without checking the rest of the list.
///
/// ## Examples
///
/// ```gleam
/// all([], fn(x) { x > 3 })
/// // -> True
/// ```
///
/// ```gleam
/// all([4, 5], fn(x) { x > 3 })
/// // -> True
/// ```
///
/// ```gleam
/// all([4, 3], fn(x) { x > 3 })
/// // -> False
/// ```
///
pub fn all(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool {
case list {
[] -> True
[first, ..rest] ->
case predicate(first) {
True -> all(rest, predicate)
False -> False
}
}
}
/// Returns `True` if the given function returns `True` for any the elements in
/// the given list. If the function returns `True` for any of the elements it
/// immediately returns `True` without checking the rest of the list.
///
/// ## Examples
///
/// ```gleam
/// any([], fn(x) { x > 3 })
/// // -> False
/// ```
///
/// ```gleam
/// any([4, 5], fn(x) { x > 3 })
/// // -> True
/// ```
///
/// ```gleam
/// any([4, 3], fn(x) { x > 4 })
/// // -> False
/// ```
///
/// ```gleam
/// any([3, 4], fn(x) { x > 3 })
/// // -> True
/// ```
///
pub fn any(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool {
case list {
[] -> False
[first, ..rest] ->