Evaluation of a small mathematical type language that supports one variable

I wrote a parser that reads string input. It works. I also wrote an evaluator that spills out the result. But there is one small detail that is difficult for me to cope with. Take a look at the following example:

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

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

My thoughts are that this will use an extra parameter for the eval function, which saves the result. But I do not see such a development. Notice I'm new to haskell, so be kind. Oh, this is homework. So don’t give me solutions, give me a hint.

+6
parsing haskell evaluation
source share
1 answer

Since expressions can read and write to the storage area, your evaluation function should receive the memory state as a parameter and return the new state to the result.

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

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

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

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

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

+5
source share

All Articles