Search code examples
juliaboolean-operations

Julia: calculate an inner product using boolean algebra


I've got two boolean vectors a = [1,1,1] and b = [0,1,1] where obviously 1 stands for true and 0 for false.

I want to calculate their inner product using Boolean algebra. The result I want is therefore

1*0 + 1*1 + 1*1 = 0 + 1 + 1 = 0

because addition plays the role of exclusive or (XOR).

I know that the product part can be done like this

a = [true, true, true] # could also use ones(Bool, 3)
b = [false, true, true]

bitwise_prod = a .& b

but I don't know how to do the sum. Any ideas?


Solution

  • I've actually found a good way now. First of all I don't need to use Boolean variables

    a = [1, 1, 1]  # or ones(Int, 3)
    b = [0, 1, 1]
    

    I can then use reduce with the xor function.

    reduce(xor, a .& b)
    

    Note that I tried using the bitwise xor operator $ that is found in the documentation (inside an anonymous function) but this operator is deprecated and Julia 0.6.2 suggests the xor function instead. I do think having the function name makes it very neat.