0

I made an operator for the xor-function, it looks like that:

op :: Integer -> Integer -> Maybe Integer
op x y
  | x == 0 && y == 0 = Just 0
  | x == 0 && y == 1 = Just 1
  | x == 1 && y == 0 = Just 1
  | x == 1 && y == 1 = Just 0
  | otherwise = Nothing

I used 0 and 1 instead of True and False but that shouldn't make a difference for the result. I read it forms a monoid but I don't understand why. Associativity is obvious and doesn't need a proof(I already made the proof by myself), but what is the identity element and why?

Edit: Here's one without numbers:

xor :: Bool -> Bool -> Bool
xor x y | x == True && y == False = True
        | x == False && y == True = True
        | otherwise = False
  • 6
    I would say the opposite: identity is trivially False, because `False ^ x == x`, which you can easily confirm exhaustively. But it's less obvious that associativity holds, and that could use a proof. Also, these maybe ints are a very strange way to encode bools. – amalloy Jul 06 '17 at 09:41
  • Hint: if you have integers `x` and `y`, then ``x `xor` y`` is the least significant bit of `x + y`. Separately, you should look at `Data.Bits` and also not use `Integer` to represent a Boolean value. – dfeuer Jul 06 '17 at 09:41
  • 4
    This cannot form a monoid (with an identity element), since the function should be of the type `X -> X -> X` with `X` the set over which the monoid is defined. – Willem Van Onsem Jul 06 '17 at 09:42
  • (Xor, False) is indeed a monoid (and even a group with an obvious inversion operator). Your code doesn't deal with booleans though. It isn't clear why you think it shouldn't make a difference. It obviously does. You had to introduce Maybe because of it. – n. m. could be an AI Jul 06 '17 at 10:21
  • 1
    Why don't you just make it like `xor :: Eq a => a -> a -> Bool` `xor x y = x /= y` – Redu Jul 06 '17 at 10:26
  • 2
    @Redu: or simply `xor = (/=)`. – Willem Van Onsem Jul 06 '17 at 10:27
  • @Redu, because that's silly. `Data.Bits` gets it right: `xor :: Bits a => a -> a -> a`. – dfeuer Jul 06 '17 at 15:24
  • @dfeuer you say silly but that's how exactly `xor` is [defined in the `Data.Bits` package](https://hackage.haskell.org/package/base-4.9.1.0/docs/src/Data.Bits.html#local-8214565720323817535). – Redu Jul 06 '17 at 15:35
  • 1
    @Redu only for `Bool`, not for all `Eq` types. – Li-yao Xia Jul 06 '17 at 19:46

1 Answers1

1

I made a stupid mistake in my proof, as amalloy said the identity is false. Here's the complete proof, I hope it's correct now.

mempty <> p = p
xor False p = p
-- For p = True:
xor False True = True
True = True
-- For p = False:
xor False False = False
False = False
-- Q.E.D