Skip to content

Commit e63b50b

Browse files
committed
Make any and all short-circuiting
fix #11750
1 parent ab6d485 commit e63b50b

File tree

2 files changed

+21
-22
lines changed

2 files changed

+21
-22
lines changed

Diff for: base/reduce.jl

+11-22
Original file line numberDiff line numberDiff line change
@@ -298,45 +298,34 @@ end
298298

299299
## all & any
300300

301-
function mapfoldl(f, ::AndFun, itr)
301+
function any(f, itr)
302302
for x in itr
303-
!f(x) && return false
303+
f(x) && return true
304304
end
305-
return true
305+
return false
306306
end
307307

308-
function mapfoldl(f, ::OrFun, itr)
308+
function any(itr)
309309
for x in itr
310-
f(x) && return true
310+
x && return true
311311
end
312312
return false
313313
end
314314

315-
function mapreduce_impl(f, op::AndFun, A::AbstractArray{Bool}, ifirst::Int, ilast::Int)
316-
while ifirst <= ilast
317-
@inbounds x = A[ifirst]
315+
function all(f, itr)
316+
for x in itr
318317
!f(x) && return false
319-
ifirst += 1
320318
end
321319
return true
322320
end
323321

324-
function mapreduce_impl(f, op::OrFun, A::AbstractArray{Bool}, ifirst::Int, ilast::Int)
325-
while ifirst <= ilast
326-
@inbounds x = A[ifirst]
327-
f(x) && return true
328-
ifirst += 1
322+
function all(itr)
323+
for x in itr
324+
!x && return false
329325
end
330-
return false
326+
return true
331327
end
332328

333-
all(a) = mapreduce(IdFun(), AndFun(), a)
334-
any(a) = mapreduce(IdFun(), OrFun(), a)
335-
336-
all(pred::Union{Callable,Func{1}}, a) = mapreduce(pred, AndFun(), a)
337-
any(pred::Union{Callable,Func{1}}, a) = mapreduce(pred, OrFun(), a)
338-
339-
340329
## in & contains
341330

342331
immutable EqX{T} <: Func{1}

Diff for: test/reduce.jl

+10
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,16 @@ prod2(itr) = invoke(prod, Tuple{Any}, itr)
201201
@test reduce(&, fill(trues(5), 24)) == trues(5)
202202
@test reduce(&, fill(falses(5), 24)) == falses(5)
203203

204+
# short-circuiting any and all
205+
206+
let c1 = 0, c2 = 0, A1 = collect(1:1000), A2 = collect(1:1000)
207+
any(x->(c1+=1; x==10), A1)
208+
all(x->(c2+=1; x!=10), A2)
209+
210+
@test c1 == 10
211+
@test c2 == 10
212+
end
213+
204214
# in
205215

206216
@test in(1, Int[]) == false

0 commit comments

Comments
 (0)