[Haskell-beginners] Re: if statements

Christian Maeder Christian.Maeder at dfki.de
Mon Jan 25 06:54:03 EST 2010


John Moore schrieb:
>  
> data Expression = Val Integer
>                 | Add Expression Expression
>                 | Subtract Expression Expression
>                 | Multiply Expression Expression
>                 | Divide Expression Expression
>          deriving Show

After you've copied your code (several times) for the four cases
Add, Subtract, Multiply, and Divide, you may want to consider:

data Expression = Val Integer
   | OpExpr Op Expression Expression

data Op = Add | Subtract | Multiply | Divide

op2op :: Op -> Integer -> Integer -> Integer
op2op op = case op of
   Add -> (+)
   Subtract -> (-)
   Multiply -> (*)
   Divide -> div

(or: type Op = Integer -> Integer -> Integer)

Cheers Christian



More information about the Beginners mailing list