Checking if all the array's elements are positive

in the usual case i can make sure if all the array’s elements are positive using the nonneg(x)now it’s not working for me everytime i try to use it, an error raises with nonneg is not defined is it deprecated or what?

all(>=(0), x) , requires Julia 1.2 or 1.3

8 Likes

^ is right, if you prefer nonneg

nonneg(x::Real} = x >= zero(T)
v = [1, 2, 3]
all(nonneg, v)

(edited to reflect the comments that follow)

1 Like

Or just

nonneg(x) = x >= zero(x)
2 Likes

(I just prefer the more specific error message for nonreal types (say, String))

I missed the <:Real and thought they were identical. So then

nonneg(x::Real) = x >= zero(x)

I prefer to avoid type parameters unless they make the code simpler or more readable.

1 Like

me too i try as much as i can to stay away from type parameters.

well, you all are right to reserve type parameters for where they should be
I have edited my original response accordingly – with attribution.

1 Like

ah, I got an surprise (or not really since the second one is making a Boolean array first

julia> @btime all(>=(0), $x)
  458.635 ns (0 allocations: 0 bytes)
true

julia> @btime all($x .> 0)
  995.900 ns (3 allocations: 4.42 KiB)
true
1 Like