[Haskell-beginners] explanation
Mihai Maruseac
mihai.maruseac at gmail.com
Wed Dec 1 21:20:36 CET 2010
Hi,
See inline comments
On Wed, Dec 1, 2010 at 9:34 PM, John Moore <john.moore54 at gmail.com> wrote:
>
> <snip>
>
> data Expression = Val Double
> | Add Expression Expression
> | Subtract Expression Expression
> | Multiply Expression Expression
> | Divide Expression Expression
> deriving Show
> evalStep :: Expression -> Expression
> evalStep (Val x)= (Val x)
We can pattern match to a constructor. Val is a constructor for
Expression, our evalStep receives an Expression as input and produces
another one, presumably the evaluated input.
In the above case, we know that if we try to evaluate a value (that's
what Val stands for) we obtain the exact same value back.
> evalStep (Add x y)
> = case x of
> (Val a) -> case y of
> (Val b) -> Val (a+b)
> left -> Add x (evalStep y)
> right -> Add (evalStep x)y
> <snip>
This case is a little more complicated. We want to do a single step of
evaluation for expressions like 2+3 and 2+3+4 (expressed in our
format, they would be Add (Double 2) (Double 3) and Add (Double 2)
(Add (Double 3) (Double 4)) or Add (Add (Double 2) (Double 3)) (Double
4)). because the later case in ambiguous, we have two imbricated cases
instead of only one. Each of the cases must look to see if we can
narrow down x or y to (Val something) because this will make the
evaluation progress.
Hope it's useful,
--
MM
More information about the Beginners
mailing list