Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation of a small math type language that supports one variable

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.

like image 331
Algific Avatar asked Oct 11 '10 12:10

Algific


1 Answers

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 ....

like image 79
sdcvvc Avatar answered Nov 04 '22 21:11

sdcvvc