Anne van Kesteren

Implementing “xor” in Haskell

Started following a course on Haskell at university. Nothing is what it seems, but apparently it’s all very logical. I grasp the basic idea now and implemented a few “functions.” One of the them is the “xor” operator. Three iterations:

module ModuleXor where

xor :: Bool -> Bool -> Bool
xor x y | x == True && y == False = True
        | x == False && y == True = True
        | otherwise = False

xor' :: Bool -> Bool -> Bool
xor' True False = True
xor' False True = True
xor' _ _ = False

xor'' :: Bool -> Bool -> Bool
xor'' True a = not a
xor'' False a = a

Using it is quite easy:

Et cetera.

Comments

  1. Oh, Haskell... how that language haunted the early weeks of my term last year! It's really quite a nice paradigm once you get into the right mindset, though my appreciation of it fell apart somewhat once I got to the hacks imposed for non-functional things such as IO.

    Posted by Bruce Boughton at

  2. Nice! Let me know if you need any help. Haskell's really, really cool.

    Posted by chris eidhof at

  3. I like xor' best, I think, because pattern matching is cool :). Although I suppose the shortest would be to do do something like:

    xor''' :: Bool -> Bool -> Bool
    xor''' a b = (a || b) && not (a && b)

    Anyway, I really liked that Haskell course :). It's a fun language, and I love programming functionally, even though I never use it much in practice (although, with JS 2.0 getting some distinct functional programming elements in it, that might change :)).

    ~Grauw

    Posted by Laurens Holst at

  4. Prolog is better. :oP

    xor(true, false).
    xor(false, true).

    That's all.

    Posted by Kula bácsi at

  5. I wish they taught Haskell at... (name withheld to protect the guilty) my university. I had to teach myself. Everything sort of clicked when I realized there was a connection with mathematical induction.

    Posted by Jacinto at

  6. Actually, there is even a one-liner that will do the same:
    xor = (/=)
    Or, if you only want it to work on Booleans:
    xor = (/=) :: Bool -> Bool -> Bool

    Posted by Chris Eidhof at

  7. xor only is (/=) for Bool.
    xor :: Bool -> Bool -> Bool
    xor = (/=)

    Posted by LungZeno at