views:

113

answers:

1

I have written the parser that reads the string input. That works. I have also written the evaluator that spits out the result. But there is one small detail that I'm having trouble implementing. Look at the following example:

+(sw+(2,2),sr)

The sw construct of this tiny language is suppose to evaluate "+(2,2)" and store it somewhere. The sr construct would read this storage area. The whole expression over would evaluate to 8.

My thoughts on it would be to use an extra parameter for the function eval, that stores the result. But I can't see that working out. Note I am new to haskell, so be kind. Oh, this is homework. So don't give me a solution, give me a hint.

+4  A: 

Since expressions can read and write into storage area, your evaluation function should get state of memory as a parameter, and return new state in result.

 evaluate :: Expr -> Int -> (Float, Int)

[where Int is type of the storage, and Float is type of result, of course you can change that].

When implementing evaluate (Sum a b), you need to pass memory into evaluate a, get new value of memory and give it to evaluate b.

     |
     |  m
    \ /
|----------|   x
|evaluate a|--------|
|-----------        |
     |              |
     |  m'          |
    \ /            \ /
|----------|  y    ---
|evaluate b|----->| + |
|----------|       ---
     |              |
     |              |
    \ /            \ /
   final           final
   value of        result
   memory

Use pattern matching. You'd start with let (x,m') = evaluate a m in ....

sdcvvc
Thank you! I didn't use let expressions tough. But I got it to work.
Algific
Great job on answering a homework question the right way.
Davorak