I have extended the any function as shown in the example below:
function Base.any(array::Matrix{Real})
checker = zeros(Bool, size(array)[1])
for i in axes(array, 1)
for j in axes(array, 2)
if array[i, j] == 1
checker[i] = true
break
end
end
end
return checker
end
The any function should now take in a Matrix that contains elements of the type Number, but when given the following matrix:
This is because in your first case you are imputing a Matrix{Int}, which is not a Matrix{Real}, then another any method is being called. You have to change your function to accept Matrix{<:Real}, which are the matrices for which the elements are any subtypes of Real.
With Matrix{Real} you are asking the function to only accept the matrices that are specifically of type Matrix{Real}, which are matrices that accept, on its elements, any type of real number.
(ps: calling your function with the second type of matrix doesn’t work here either, because it is a Matrix{Float64} which is not either a subtype of Matrix{Real}. Your method works, as is, if you explicitly set Real[ 0 0 1; 0 1 0 ; 0 0 1 ], such to get Matrix{Real}).
Finally, the error message (which is not great), is saying it is trying to test if a integer number is true or false, that is, using a integer where it expects a boolean. This occurs because the any function supports not providing the first argument (the function to be mapped to every element of the collection), and in that case it tests for true/false the array itself:
julia> any([true false])
true
julia> any(==(1),[1 0])
true
julia> any([1 0])
ERROR: TypeError: non-boolean (Int64) used in boolean context
I never extend basic functionality like this until I’m sure it’s (a) working as I hoped and (b) is operating in a sense consistent with the other methods. Start with your own function names first.
julia> any(x)
ERROR: TypeError: non-boolean (Int64) used in boolean context
Why in one case integers are considered “as booleans”, and in the other case don’t? (for the fun I created a PR that fixes this inconsistency, but that seem to be a deliberate choice, so probably that is not going to change).
Both your original version or the suggestion to implement Base.any(array::Matrix{<:Real}) are cases of type piracy (see examples). You have modified a function you do not “own” (is not originally defined in the code you’re working on) for a type that you also do not own.
Piracy risks breaking your entire Julia session (and anyone’s who uses your code) in subtle and insidious ways and is strongly discouraged. I recommend using the suggested call to any(==(1), A; dims=2), which is exactly equal to your version but more flexible and not a case of piracy.