[Haskell-beginners] if statements
daniel.is.fischer at web.de
Sat Jan 23 13:33:10 EST 2010
Am Samstag 23 Januar 2010 18:40:10 schrieb John Moore:
> I'm trying to get a if statement to work but not sure if this is the
> right approach,
I think pattern matching and case .. of would be better suited.
> what I want to do in simple english is to evaluate one
> expression at a time for example. (3+2)+(4+5) I want it to return 5 +
> (4+5) then 5+9.
> data Expression = Val Integer
> | Add Expression Expression
> | Subtract Expression Expression
> | Multiply Expression Expression
> | Divide Expression Expression
> deriving Show
> evalStep :: Expression -> Expression
> evalStep (Val x)= (Val x)
> evalStep (Add x y) = do
> if x = isDigit
> then if y isDigit
> else evalStep x,y
-- evaluate one step only
evalStep (Add x y)
= case x of
(Val v) -> case y of
(Val w) -> Val (v+w)
other -> Add x (evalStep y)
other -> Add (evalStep x) y
evalStep (Subtract x y) ... -- analogously, also Multiply and Divide
evalStep e = e -- only Val left.
Voilà, the leftmost innermost compound expression is reduced if the
expression isn't fully evaluated. To completely evaluate:
eval :: Expression -> Expression
eval e@(Val _) = e
eval e = eval (evalStep e)
> I thinking about using recursion down a tree left then right but that
> seems very complicated.
> Any thoughts welcome!
More information about the Beginners