Reducing BitArray with xor

I am trying to xor a number of BitArray{1} vectors

julia> a=BitArray([1 1;1 0])
 2×2 BitArray{2}:
  true   true
  true  false
julia> reduce(⊻, a, dims=1)
ERROR: MethodError: no method matching reducedim_init(::typeof(identity), ::typeof(xor), ::BitArray{2}, ::Int64)

However, other similar operators works fine:

julia> reduce(&, a, dims=1)
1×2 BitArray{2}:
 true  false

julia> reduce(|, a, dims=1)
1×2 BitArray{2}:
 true  true

Is there something missing in Base regarding xor ?

See the docstring of reduce (emphasis mine):

reduce(f, A; dims=:, [init])

Reduce 2-argument function f along dimensions of A. dims is a vector specifying the
dimensions to reduce, and the keyword argument init is the initial value to use in the
reductions. For +, *, max and min the init argument is optional.

That said, the error message could be nicer. And there is no reason it could not be extended to xor I guess. Perhaps open an issue?

Thanks @Tamas_Papp. I tried this, but still no luck …

julia> reduce(⊻, a, dims=1, init=BitVector([0,0]))
ERROR: MethodError: no method matching xor(::BitArray{1}, ::Bool)

It works if you initialize it with just a bool, e.g.:

julia> a=BitArray([1 1;1 0])
2×2 BitArray{2}:
 true   true
 true  false
julia> reduce(⊻, a, dims=1, init=false)
1×2 BitArray{2}:
 false  true

(Granted I found that quite suprising as your approach seemed intuitive to me too…)
Cheers

I guess a PR clarifying the docs would be very useful.

3 Likes

the solution above stopped working for me somehow - maybe this is usefull for anyone in the future :stuck_out_tongue:

function (^)(l::BitArray, r::BitArray)
   xorArray = BitArray(fill(0, (1,consts.sn)))

   for (index, leftValue) = enumerate(l)
       if leftValue && !r[index] || !leftValue && r[index]
           xorArray[index] = 1
       end
   end

   return xorArray
end