Skip to content

Commit

Permalink
Make any and all always short-circuit
Browse files Browse the repository at this point in the history
  • Loading branch information
ararslan committed Dec 15, 2016
1 parent 38ff38c commit cd230e1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
22 changes: 12 additions & 10 deletions base/reduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -579,11 +579,12 @@ true
```
"""
any(f::Any, itr) = any(Predicate(f), itr)
any(f::Predicate, itr) = mapreduce_sc_impl(f, |, itr)
any(f::typeof(identity), itr) =
eltype(itr) <: Bool ?
mapreduce_sc_impl(f, |, itr) :
reduce(or_bool_only, false, itr)
function any(f::Predicate, itr)
for x in itr
f(x) && return true
end
return false
end

"""
all(p, itr) -> Bool
Expand All @@ -596,11 +597,12 @@ true
```
"""
all(f::Any, itr) = all(Predicate(f), itr)
all(f::Predicate, itr) = mapreduce_sc_impl(f, &, itr)
all(f::typeof(identity), itr) =
eltype(itr) <: Bool ?
mapreduce_sc_impl(f, &, itr) :
reduce(and_bool_only, true, itr)
function all(f::Predicate, itr)
for x in itr
f(x) || return false
end
return true
end

## in & contains

Expand Down
9 changes: 9 additions & 0 deletions test/reduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ let c = [0, 0], A = 1:1000
@test c == [10,10]
end

# 19151 - always short circuit
let c = Int[], d = Int[], A = 1:9
all((push!(c, x); x < 5) for x in A)
@test c == collect(1:5)

any((push!(d, x); x > 4) for x in A)
@test d == collect(1:5)
end

# any and all with functors

immutable SomeFunctor end
Expand Down

0 comments on commit cd230e1

Please sign in to comment.