Question: Write an evaluator for a program (list of statements + return expression) that evaluates the program and returns the final value of the return

Write an evaluator for a program (list of statements + return expression) that evaluates the program and ]: def evalProgram (p: Program): Double = p match { } case CalcProgram (1stOfStatement, returnExpr) => { //

Write an evaluator for a program (list of statements + return expression) that evaluates the program and returns the final value of the return expression after the statements in the program are run one by one. We explain how to evaluate a program step by step on an example program x15 //Stmtl yx 10 // Stmt 2 Z y5 // Stmt 3 x+y+ z // Return expression This program should return the value 30. The key idea is this: a) Start with an empty environment map to begin with. b) Execute each statement in the list of statements from beginning to end. When you execute the statement, do so with the current map and the return value is the next map. c) Evaluate the return expression on the final map after you have executed all the statements. Complete the code below. You can use loops and var for now. We will show you how to avoid it later. Here is how you iterate through each element of a list in scala: for (item { // YOUR CODE HERE } ??? } ]://BEGIN TEST val v1 val v2 Assignment ("x", Const(2.0)) Assignment("y", Plus (Var("x"), Const(4.0))) val v3 = Assignment ("z", Var("y")) val pl = CalcProgram (List (v1, v2, v3), Var("z")) print (evalProgram (pl)) assert (evalProgram (pl) == 6) passed (5) //END TEST ]://BEGIN TEST val vvl Assignment("x", Const(2.0)) val vv2 = Assignment ("y", Star (Var("x"), Var("x"))) val vv3 = Assignment ("z", Star (Var("y"), Var("y"))) Assignment ("w", Star (Var("z"), Var("z"))) val vv4 val p2 CalcProgram (List (vvl, vv2, vv3, vv4), Var("w")) print (evalProgram (p2)) assert (evalProgram (p2) passed(5) //END TEST == 256)

Step by Step Solution

3.36 Rating (149 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

scala def evaluateProgramstatements ListString returnExpression String Int var environme... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!