Anne van Kesteren: Weblog 4.2

Weblog on W3C, WHATWG, HTML, CSS, DOM, XML, HTTP and more.

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.

16th February 2007

Browse through posts: main.

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.

    Permalink · 2007-02-16 12:07:41 · Bruce Boughton

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

    Permalink · 2007-02-16 21:22:56 · chris eidhof

  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

    Permalink · 2007-02-19 06:49:59 · Laurens Holst

  4. Prolog is better. :oP

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

    That's all.

    Permalink · 2007-02-24 07:28:58 · Kula bácsi

  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.

    Permalink · 2007-02-27 23:17:32 · Jacinto

  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

    Permalink · 2007-03-07 05:57:33 · Chris Eidhof

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

    Permalink · 2008-11-09 16:51:15 · LungZeno

Leave a Comment

a, abbr, b, blockquote, br, cite, code, dd, dfn, dl, dt, em, i, li, ol, p, pre, q, samp, strong, sub, sup, ul, and var are allowed as elements. They take some of their usual attributes as well.

Comments need to be well-formed XML and are moderated.