Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Standalone in Scala Constant folding is an operation that compilers often do to simplify (parts of) expressions that evaluate to constants. Fo instance, suppose one
Standalone in Scala
Constant folding is an operation that compilers often do to simplify (parts of) expressions that evaluate to constants. Fo instance, suppose one is given an expression of the form 23+x, represented as Plus(Multe(Const(2),Const(3)),Ident(x)) we could directly simplify it to 6+x or Plus ( Const (6), Ident (x)). In other words, we evaluate parts of an expression without needing to know the value of any of the identifiers. We will carry out constant folding according to some semantic rules that we will write below. Constant folding a constant does not change it. Constant folding a constant does not change it. Constant folding an identifier does not change it. Page 1 of 3 Last update: constFold(Ident(x))=Ident(x)(identfold) Constant folding a plus when both operands fold into constants. constFold(Plus(e1,e2))=Const(f1+12)constFold(e1)=Const(f1),constFold(e2)=Const(f2),(plus-const-fold-1) Constant folding a plus when one of the operands does not fold into constants. constFold (e1)=t1, constFold (e2)=t2, at least one of t1 or t2 is not Const constFold(Plus(01,02))=Plus(t1,t2) (plus - const - fold - 2) Similar rules apply (with a few modifications) for constant folding other cases Minus, Div, Mult. Do not worry about division by zero for this assignment. Also, there is no need to handle Sine/Cosine/Exp for this assignment. Throw an IllegalArgumentException if your expression has those functions in it. Programming tasks: (20 points) Write a function constFold that takes in an Expr and returns an expression after constant folding. - No loops can be used. - No vars can be used. - No return keyword. Your program should pass the following tests ( 5 points for each): import scala. language.implicitconversions implicit def toExpr (f: Double) : Expr = Const (f) implicit def toExpr (f: Int) : Expr = Const (f. toDouble) implicit def toExpr (s: String) : Expr = Ident (s) def p1 (e1: Expr, e2: Expr) = Plus (e1, e2) def ms (e1: Expr, e2: Expr) = Minus (e1, e2) r def st (e1: Expr, e2: Expr) = Mult (e1, e2) def dv (e1: Expr, e2: Expr) = Div (e1, e e2) /. you may put the above statements at the beginning of your Scala file, and the following statements in your main method / val e1 =st(pl(3,3),dv(3,2)) printin (e1) testWithmessage (constfold(e1), Const (9.0), " =1" )
Step by Step Solution
There are 3 Steps involved in it
Step: 1
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