Skip to content

Commit

Permalink
Make any and all short-circuiting
Browse files Browse the repository at this point in the history
  • Loading branch information
fcard committed Jun 20, 2015
1 parent ab6d485 commit e63b50b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 22 deletions.
33 changes: 11 additions & 22 deletions base/reduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -298,45 +298,34 @@ end

## all & any

function mapfoldl(f, ::AndFun, itr)
function any(f, itr)
for x in itr
!f(x) && return false
f(x) && return true
end
return true
return false
end

function mapfoldl(f, ::OrFun, itr)
function any(itr)
for x in itr
f(x) && return true
x && return true
end
return false
end

function mapreduce_impl(f, op::AndFun, A::AbstractArray{Bool}, ifirst::Int, ilast::Int)
while ifirst <= ilast
@inbounds x = A[ifirst]
function all(f, itr)
for x in itr
!f(x) && return false
ifirst += 1
end
return true
end

function mapreduce_impl(f, op::OrFun, A::AbstractArray{Bool}, ifirst::Int, ilast::Int)
while ifirst <= ilast
@inbounds x = A[ifirst]
f(x) && return true
ifirst += 1
function all(itr)
for x in itr
!x && return false
end
return false
return true
end

all(a) = mapreduce(IdFun(), AndFun(), a)
any(a) = mapreduce(IdFun(), OrFun(), a)

all(pred::Union{Callable,Func{1}}, a) = mapreduce(pred, AndFun(), a)
any(pred::Union{Callable,Func{1}}, a) = mapreduce(pred, OrFun(), a)


## in & contains

immutable EqX{T} <: Func{1}
Expand Down
10 changes: 10 additions & 0 deletions test/reduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,16 @@ prod2(itr) = invoke(prod, Tuple{Any}, itr)
@test reduce(&, fill(trues(5), 24)) == trues(5)
@test reduce(&, fill(falses(5), 24)) == falses(5)

# short-circuiting any and all

let c1 = 0, c2 = 0, A1 = collect(1:1000), A2 = collect(1:1000)
any(x->(c1+=1; x==10), A1)
all(x->(c2+=1; x!=10), A2)

@test c1 == 10
@test c2 == 10
end

# in

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

0 comments on commit e63b50b

Please sign in to comment.