Benjamin Halsted // [bgh] todo, add something clever here.

31Mar/100

Erlang Programming Exercise: 3-8-2

For exercise 3-8-2 we are to create an evaluator. It should take the output (expressions) from 3-8-1 and returns its value. And to make the code a little bit easier to read, LHS and RHS are the left hand and right hand side of the expressions.

-module(threeeightytwo).
-export([evaluator/1]).

evaluate({plus, LHS, RHS}) ->
        evaluate(LHS) + evaluate(RHS);
evaluate({minus, LHS, RHS}) ->
        evaluate(LHS) - evaluate(RHS);
evaluate({unary_minus, Expression}) ->
        -1 * evaluate(Expression);
evaluate({num, Number}) ->
        Number.

eval(Results, []) ->
        lists:reverse(Results);
eval(Results, [Expression|List]) ->
        Result = evaluate(Expression),
        eval([Result|Results], List).

evaluator(Expressions) ->
        eval([], Expressions).

As you can see I return an array of results. This is because the return value from my 3-8-1 returns an array of expressions. Here is an example run:

1> T81 = threeeightyone:parser("((2+3)+(4+(5+6)))7(8+9)").
[{plus,{plus,{num,2},{num,3}},{plus,{num,4},{plus,{num,5},{num,6}}}},
 {num,7},
 {plus,{num,8},{num,9}}]
2> threeeightytwo:evaluator(T81).
[20,7,17]

I have three expressions as the argument to 3-8-1:

  1. ((2+3)+(4+(5+6)))
  2. 7
  3. (8+9)

And there are three values as the result from 3-8-2:

  1. 20
  2. 7
  3. 17

And we double check the results. Looks good!

Cheers,
-Halzy

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.