Answered step by step
Verified Expert Solution
Question
1 Approved Answer
In class we saw how to evaluate an expression given a map from identifiers to their values. def evalExpr (e: Expr, env: Hap[String, Double]):
In class we saw how to evaluate an expression given a map from identifiers to their values. def evalExpr (e: Expr, env: Hap[String, Double]): Double = ... In this assignment, you are asked to handle assignment statement. The Idea here is that the assignment statement takes an environment and modifies it. def evalstatement(s: Statement, env: Rap[String, Double]): Hap[String, Double] =... As an example consider the map env Hap("x"-> 20, "y" -> 35) The assignment statement z:-x+y Assignment("z", Plus (var("x"), Var("Y"))) Should return a map Hap("x"-> 20, "y" -> 35, "2" -> 55) The strategy should be as follows: (a) evaluate the expression in the RHS of the assignment statement, (D) add the entry that maps the declared variable to the new value and (c) return this map. https://docs.scala-lang.org/overviews/collections-2.13/maps.html In []: def evalExpr(e: Expr, env: Rap[String, Double]): Double = { def binFun(el: Expir, e2: Expr, op: (Double, Double) => Double): Double = { val vi evalExpr(el, env) } e match { case Plus (el, e2) => binFun(el, ez, _ + _ ), case Minus(el, e2) => binFun(el, e2, _) } val v2 = evalExpr(e2, env) op (v1, v2) } } case Star (el, e2) => binFun(el, e2, __) case Ver(v) => { if (env.contains(v)){ } else { throw new IllegalArgumentException(s"$v undefined variable.") } env(v) } case Const(f) => f def evalstatement(s: Statement, env: Rap[String, Double]): Nap[String, Double] =smatch { case Assignment(varliame, rhsExpr) => { // YOUR CODE HERE 222 In []: //BEGIN TEST def testlap (m1: Hap[String, Double], varname: String, testval: Double) = { m1.contains (varnamne) && m1(varname) == testval } val ml = Hap[String, Double]() val v1 = Assignment(x", Const(2.0)) val m2 = evalstatement(v1, m1) assert (testlap (m2, "x", 2.0), "TEST 1 PASSED!") passed (10) //END TEST val v2 = Assignment("y", Plus (Var("x"). Const(4.0))) val m3 = evelstatenment(v2, m2) assert (testisp(m3, "x", 2.0), "TEST 2.1 PASSED!") assert(testisp(m3, "y", 6.0), "TEST 2.2 PASSED!") val v3 = Assignment("z", Star(var(""), Var("x"))) val m4 = evalstatement(v3, m3) assert (testhop (n4, "x", 2.0), "TEST 3.1 PASSED!") assert(test ap(m4, "y", 6.0), "TEST 3.2 PASSED!") assert (testop(n4, "z", 12.0), "TEST 3.3 PASSED!")
Step by Step Solution
★★★★★
3.41 Rating (164 Votes )
There are 3 Steps involved in it
Step: 1
Heres the implementation for the evalstatement function scala def evalstatemen...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started