[Haskell-beginners] Show how the evaluation works

Stephen Tetley stephen.tetley at gmail.com
Sun Nov 22 11:45:07 EST 2009


Hi John

You need some more /machinery/ in your evaluator.

One possibility is to make it a monadic evaluator - you could then
choose to use IO and print things as you go, or a writer monad which
'collects' (think logging) as evaluation progresses. The at the end
you'd show both the log and the answer.

The writer monad has a run function, which you would need to run the
extended evaluator with

runWriter :: Writer w a -> (a, w)

The result of runWriter is a pair of a (the answer) and w (the log).
Writer is more general than just logging, but in this instance logging
is close to what you might want.

Best wishes

Stephen



2009/11/22 John Moore <john.moore54 at gmail.com>:
> Hi All,
>
> I'm trying to work out how to show the steps in evaluating "How the function
> is calculated". In other words I want this program to actually print out the
> steps. For e.g. eval (Multiply(Add(Val 10) (Val 20)) (Val 3)    Which is add
> 10+20 and multiply by 3 = 90
>
> The program then produces( Prints out) something like
>
> working: eval (Multiply(Add(Val 10) (Val 20)) (Val 3)
> working Add(Val10) (Val 20)
> answer 1 Val 30
> answer 2 Val 90
>
> This is what I have so far but it wont even do the calculations. Any help
> appreciated.
>
> data Expression = Val Float
>                 | Add Expression Expression
>                 | Subtract Expression Expression
>                 | Multiply Expression Expression
>                 | Divide Expression Expression
>          deriving Show
> eval :: Expression -> Float
> eval (Val x) = x
> eval (Add x y) = eval x + eval y
> eval (Multiply x y) = eval x * eval y
> eval (Subtract x y) = eval x - eval y
> eval (Divide x y) = eval x / eval y
>
>
>
> John
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>


More information about the Beginners mailing list