A polynomial
can be represented as a list of reals
.
Write functions eval, pow and polyToString so
that we can evaluate:
- val p = [1.0,2.0]; (* 2x + 1 *) val p = [1.0,2.0] : real list - eval(p,0.1); val it = 1.2 : real - val p3 = pow(3,p); val p3 = [1.0,6.0,12.0,8.0] : real list - eval(p3,0.1); val it = 1.728 : real - polyToString(p3); val it = "8.0x^3 + 12.0x^2 + 6.0x + 1.0" : string - polyToString [0.0,0.0,~1.0,0.0,0.0]; val it = "0.0x^4 + 0.0x^3 + ~1.0x^2 + 0.0x + 0.0" : string - polyToString [0.0]; val it = "0.0" : string - polyToString []; val it = "0.0" : stringYou will need to use the functions
Real.toString and
Int.toString to get strings for numbers. Don't ``open'' either
the ``Real'' or the ``Int'' structure because it will cause
overloading functions to misbehave.
Do not use if in any of your code for polynomials.
Our solution uses four additional functions, three of them at the
top-level (useful named functions), and one a helper for the
polyToString function.
Do Exercises 3 and 4 of Chapter 8 (page 131):
Exercise 3 Consider an unknown language with integer and real types in which 1+2, 1.0+2, 1+2.0, and 1.0+2.0 are all legal expressions.
![]()
Exercise 4 Consider an unknown language with integer and string types in which 1+2*3 evaluates to 7, "1"+"2"+"3" evaluates to "123", "1"+2+3 evaluates to "123" and 1+"2*3" has a type error. Describe a system of precedence, associativity, overloading and coercion that could account for this. In your system, what is the result of evaluating the expression "1"+2*3.
Print out your programming code. Put them with your answers to the book exercises. Turn them in at the beginning of lecture.