Question: Complete using the OCaml programming language In this section, we'll work with a datatype that represents arithmetic expressions of a single variable. This is actually

Complete using the OCaml programming language

Complete using the OCaml programming language In this section, we'll work with

In this section, we'll work with a datatype that represents arithmetic expressions of a single variable. This is actually defined as two data types: (* Binary operators. *) type binop = Add | Sub | Mul | Div | Pow ; ; type expression = | Num of float | Var | Binop of expression * binop * expression | Neg of expression ; Num a represents the floating-point number a . Var represents the only variable, which we'll call x. Binop (e1, 0 , e2) represents a binary operation on subexpressions e1 and e2. The binary operation is given by o of type binop which can be Add, Sub, Mu1, Div, or Pow. Neg e is the negation of e (e.g., Neg (Num 1.0) represents -1). For example, we could represent 3.0x2+x+2.0 as Binop (Binop (Neg (Num 3.0), Mul, Binop (Var, Pow, Num 2.0)), Add, Binop (Var, Add, Num 2.0) (There are other ways we could represent it too.) Parsing expressions We've provided functions (below the definition of the data types, in a large block of code you can ignore) for parsing strings into expression datatypes. You may find this helpful when testing your code, unless you particularly like manually typing things like the expression above. The parser is reasonably robust, but not great, so you may need to fiddle around a bit to get your strings in the right format. We can get the above expression by running parse"3.x2+x+2.; Note that we use instead of to represent negation. This lets the parser distinguish between negation and subtraction. We also need to explicitly include the * between 3.0 and x2 rather than just concatenating the two like we do when writing math normally. Exercise Write a function evaluate : expression float float. The application evaluate e v should substitute v for x in the given expression and evaluate it to a float. For example, #evaluate(parse"3.x2+x+2.).-:float=2.#evaluate(parse"3.x2+x+2.)1.-:float=0.#evaluate(parse"3.x2+x+2.)2.-:float=8

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock 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 Databases Questions!