Homework # 4
due March 29, 2:00 PM

Programming

A polynomial \( a_n x^n + \ldots + a_1 x + a_0 \) can be represented as a list of reals \( [a_0, a_1, \ldots, a_n] \). 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" : string
You 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.

Overloading and Polymorphism

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.
\begin{alphabate}
\item Explain how this could be the result of coercion, using ...
...sult from subtype polymorphism, with no overloading or coercion.
\end{alphabate}
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.

Submitting Your Work

Print out your programming code. Put them with your answers to the book exercises. Turn them in at the beginning of lecture.


About this document



John Boyland 2007-04-03