I am trying to write an evaluator for a Boolean expression . Here type of evalAExp :: AExp-> Maybe Int (i.e. Arithmetic expression evaluator). Arithmetic evaluator is working for me.
In Boolean Evaluator I want the type to be :: BExp -> Bool.
While compiling I get an error like Couldn't match expected type ``Bool' with actual type ``BExp'
In the pattern: Eq a1 a2
In an equation for ``evalBExp':
evalBExp (Eq a1 a2) = evalAExp (a1) == evalAExp (a2)
The end types of a BExp should be Bool.
How should I be declaring my BExp in this case. Is there a better way of going about it.
data BExp = Eq AExp AExp | Lt AExp AExp | Gt AExp AExp | ELt AExp AExp| EGt AExp AExp | And BExp BExp | Or BExp BExp | Bool
evalBExp True = True
evalBExp False = False
evalBExp (Eq a1 a2) = evalAExp (a1) == evalAExp (a2)
Here in evalBExp (Eq a1 a2) = evalAExp (a1) == evalAExp (a2)
I am comparing Just Int == Just Int and the resultant is a Bool. What should I be doing? I think there is a problem in the data BExp declaration itself for me.
Any Help
EDIT :
I changed my code to something like this.
data BExp = Eq AExp AExp | Lt AExp AExp | Gt AExp AExp | ELt AExp AExp| EGt AExp AExp | And BExp BExp | Or BExp BExp |Boolean Bool
evalBExp (Boolean True) = True
evalBExp (Boolean False) = False
evalBExp (Eq a1 a2) = (evalAExp (a1)) == (evalAExp (a2))
So I changed the type to Boolean Bool. Is this a better way of declaring a type . Why not simply Bool as earlier. Is there a better way to do this.
Entire Code
import qualified Data.Map as M
import Data.List
data AExp = Var Char | Value Int | Add AExp AExp | Mul AExp AExp | Sub AExp AExp
data BExp = Eq AExp AExp | Lt AExp AExp | Gt AExp AExp | ELt AExp AExp| EGt AExp AExp | And BExp BExp | Or BExp BExp |Boolean Bool
data AssignExp = AExp Char | BExp Char
data Statement = AssignExp | While BExp Statement
type Env = M.Map Char Int
env = M.fromList[('A',1),('B',2),('C',3)]
evalAExp :: AExp -> Maybe Int
evalAExp (Value x) = (Just x)
evalAExp (Var x) = M.lookup x env
evalAExp (Add a1 a2) =do
v2<-evalAExp a2;v1<-evalAExp a1
return (v1+v2)
evalAExp (Sub a1 a2) =do
v2<-evalAExp a2;v1<-evalAExp a1
return (v1-v2)
evalAExp (Mul a1 a2) = do
v1 <-evalAExp a1;v2 <- evalAExp a2
return (v1*v2)
evalBExp (Boolean True) = True
evalBExp (Boolean False) = False
evalBExp (Eq a1 a2) = (evalAExp (a1)) == (evalAExp (a2))
AExp
andevalAExp
defined ? – Sibi