CSCI305.github.io

CSCI 305: Programming Languages

Polymorphism

Reading: Webster Ch. 8

Instructions

  1. Watch This Video - (10:30)
  2. Watch This Video - (10:46)
  3. Watch This Video - (06:54)
  4. Review the Lecture Slides
  5. Complete the Out of Class Exercise
  6. Check your learning
  7. Attend Class and complete the In Class Exercises
  8. Check your learning

Out of Class Exercise

Exercise 1

Consider an unknown language with a left-associative + operator that is overloaded to have the following types: int * real -> real, int * int -> int, real * int -> real, and real * real -> real. Suppose the variable i has type int and the variable r has type real. For each + operator in each of the following expressions, say which type of + is used:

Check Your Learning:

Solution:

In this case, the type of + operator is int * real -> real

In this case, the second + operator, in (r + i), is of type real * int -> real which then makes the first + operator of type int * real -> real.

Exercise 2

Write an ML function definition for each of the following functions. Try to predict what polytype ML will infer for each function. Then check your predictions using the ML language system. What is the polytype determined by ML for each case?

Check Your Learning:

Solution:

In Class Exercises

Exercise 1

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?

Check Your Learning:

Solution:

Both the + and * operators are left-associative but the * operator has higher precedence than the + operator, when working with integers. When the left operand of the + operation is a string it has right-associativity. Furthermore, when the left operand of the + operator is a string the right operand is coerced into a string and the operation works as in string concatenation. When the left operand is an integer the operator attempts to perform addition and thus, if a string is the right operand, an error will occur as there is no guaranteed method of coercing a string into an integer. Finally, in this scheme, the evaluation of "1" + 2 * 3 would evaluate to "16" as the * operator still has higher precedence than the + operator which would evaluate to an intermediate expression: "1" + 6, which then evaluates according to the string concatenation operation and coerces 6 to "6" leading to the final answer of "16".

Exercise 2

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.

Check Your Learning:

Solution: