Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implying equality in a Haskell pattern match

I'm writing a function to simplify a Boolean expression. For example, Nand(A, A) == Not(A). I've tried to implement this particular rule using pattern matching, like so:

-- Operands equivalent - simplify!
simplify (Nand q q) = Not (simplify q)
-- Operands must be different, so recurse.
simplify (Nand q q') = Nand (simplify q) (simplify q')

Upon compiling, I get the error:

Conflicting definitions for `q'
Bound at: boolean.hs:73:21
          boolean:73:29
In an equation for `simplify'

I think I understand what's going on, and I've worked around it, but I'd just like to know:

  1. Why is this sort of pattern matching not possible?
  2. Is there an idiomatic workaround?

Full disclosure: this is related to homework, but the purpose of the course is not to learn Haskell, and I've solved it my own way anyway.

like image 762
Daniel Buckmaster Avatar asked Aug 23 '12 04:08

Daniel Buckmaster


1 Answers

The solution I've found is to use guards to check for equality of sub-structures:

simplify (Nand q q')
    -- Operands equivalent - simplify!
    | q == q' = Not (simplify q)
    -- Operands different - recurse.
    | otherwise = Nand (simplify q) (simplify q')
like image 170
Daniel Buckmaster Avatar answered Nov 16 '22 00:11

Daniel Buckmaster