From c656e71eb8dd9925200e4e36be51724b256c90e2 Mon Sep 17 00:00:00 2001 From: Scott Morrison Date: Tue, 12 Dec 2023 10:48:15 +1100 Subject: [PATCH] chore: make List.all and List.any short-circuit (#2972) Changes the implementation of `List.all` and `List.any` so they short-circuit. The implementations are tail-recursive. This replaces https://github.com/leanprover/std4/pull/392, which was going to do this with `@[csimp]`. --- src/Init/Data/List/Basic.lean | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Init/Data/List/Basic.lean b/src/Init/Data/List/Basic.lean index f7ed064025..1734d20172 100644 --- a/src/Init/Data/List/Basic.lean +++ b/src/Init/Data/List/Basic.lean @@ -557,16 +557,22 @@ def takeWhile (p : α → Bool) : (xs : List α) → List α /-- `O(|l|)`. Returns true if `p` is true for any element of `l`. * `any p [a, b, c] = p a || p b || p c` + +Short-circuits upon encountering the first `true`. -/ -@[inline] def any (l : List α) (p : α → Bool) : Bool := - foldr (fun a r => p a || r) false l +def any : List α -> (α → Bool) -> Bool + | [], _ => false + | h :: t, p => p h || any t p /-- `O(|l|)`. Returns true if `p` is true for every element of `l`. * `all p [a, b, c] = p a && p b && p c` + +Short-circuits upon encountering the first `false`. -/ -@[inline] def all (l : List α) (p : α → Bool) : Bool := - foldr (fun a r => p a && r) true l +def all : List α -> (α → Bool) -> Bool + | [], _ => true + | h :: t, p => p h && all t p /-- `O(|l|)`. Returns true if `true` is an element of the list of booleans `l`.