Search code examples
haskelloperatorsexpressiontyping

Defining logic operators in Haskell


In my homework I have to define the logic operators as follows:
Using this data structure:

data MyBool = Cierto|Falso deriving (Show,Eq) -- Cierto = True and Falso = False
data PQR = A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z deriving (Show,Eq)
data Formula = VarProp PQR 
             |Neg Formula -- logic not
             |Formula :|: Formula -- logic or
             |Formula :&: Formula -- logic and... etc
             |Formula :->: Formula
             |Formula :<->: Formula deriving (Show,Eq)

And I have to define functions that tell me if a given formula is True or False, so for example if I write (Cierto :&: Falso) the answer has to be: Falso.

According to my teacher the function has to be called in this case :&: and has to receive MyBool types so I tried to implemented like this:

infixr 3 :&:
(:&:) :: MyBool -> MyBool -> MyBool
Cierto :&: x = x
Falso :&: x = Falso

but when I try to load it it says:

Invalid type signature

I don't know what I doing wrong here.


Solution

  • Your professor is forcing you to create an Abstract Syntax Tree(AST) for boolean operators. if you have not heard the words "Abstract Syntax Tree" prior to this, it is time to ask someone what the heck is going on.

    What you in fact want to do is write a function (called say eval) with the type Formula -> Formula. In looking at the definition, I also believe you have left a line out of data Formula that should be something like VarLiteral MyBool. It looks like you AST is a way of writing programs which operate on MyBool's and supports the typical boolean operations along with :->: assign (?).

    I've written a few AST evaluators in Haskell (though nothing this corny :) ) and it feels like there are a few pieces missing in your question. My best advice for you, given what I have in front of me, is to say that this assignment is one level more abstract than you think it is.

    Best of Luck