Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

image text in transcribed

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions