aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorinoas <mail@inoas.com>2022-06-27 22:59:05 +0200
committerLouis Pilfold <louis@lpil.uk>2022-07-03 22:10:45 +0100
commit957b0dd730b16270c6d2b783825b629858571879 (patch)
treefcf86e4acab22b4631f4981a3365a83fd8f95ed3
parent286d7eae50913813b15088dece8b85e1b22b0735 (diff)
downloadgleam_stdlib-957b0dd730b16270c6d2b783825b629858571879.tar.gz
gleam_stdlib-957b0dd730b16270c6d2b783825b629858571879.zip
naming, attempt to add tests that proof short circuit
-rw-r--r--src/gleam/list.gleam25
-rw-r--r--test/gleam/list_test.gleam24
2 files changed, 32 insertions, 17 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index 3c73a56..38a6607 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -790,19 +790,15 @@ pub fn find_map(
pub fn all(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool {
case list {
[] -> True
- list -> all_tail_recursive(list, predicate, True)
+ list -> do_all(list, predicate, True)
}
}
-fn all_tail_recursive(
- list: List(a),
- predicate: fn(a) -> Bool,
- accumulator: Bool,
-) -> Bool {
+fn do_all(list: List(a), predicate: fn(a) -> Bool, accumulator: Bool) -> Bool {
case list {
+ // _ if accumulator == False -> False
[] -> accumulator
- [x, ..rest] ->
- all_tail_recursive(rest, predicate, accumulator && predicate(x))
+ [x, ..rest] -> do_all(rest, predicate, accumulator && predicate(x))
}
}
@@ -829,20 +825,15 @@ fn all_tail_recursive(
pub fn any(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool {
case list {
[] -> False
- list -> any_tail_recursive(list, predicate, False)
+ list -> do_any(list, predicate, False)
}
}
-fn any_tail_recursive(
- list: List(a),
- predicate: fn(a) -> Bool,
- accumulator: Bool,
-) -> Bool {
+fn do_any(list: List(a), predicate: fn(a) -> Bool, accumulator: Bool) -> Bool {
case list {
- _ if accumulator == True -> True
+ // _ if accumulator == True -> True
[] -> accumulator
- [x, ..rest] ->
- any_tail_recursive(rest, predicate, accumulator || predicate(x))
+ [x, ..rest] -> do_any(rest, predicate, accumulator || predicate(x))
}
}
diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam
index 82350a2..7373ef9 100644
--- a/test/gleam/list_test.gleam
+++ b/test/gleam/list_test.gleam
@@ -308,6 +308,18 @@ pub fn all_test() {
list.repeat(True, 16999)
|> list.all(fn(item) { item })
|> should.equal(True)
+
+ [1, 2, 3]
+ |> list.all(fn(x) {
+ case x {
+ 1 -> True
+ 2 -> False
+ // Crash to ensure we short-circuit
+ _ -> {
+ assert True = False
+ }
+ }
+ })
}
pub fn any_test() {
@@ -327,6 +339,18 @@ pub fn any_test() {
list.repeat(False, 16999)
|> list.any(fn(item) { item })
|> should.equal(False)
+
+ [1, 2, 3]
+ |> list.any(fn(x) {
+ case x {
+ 1 -> False
+ 2 -> True
+ // Crash to ensure we short-circuit
+ _ -> {
+ assert True = False
+ }
+ }
+ })
}
pub fn zip_test() {