SICP Exercise 2.82 coercion with multiple arguments
Exercise 2.82. Show how to generalize apply-generic to handle coercion in the general case of multiple arguments. One strategy is to attempt to coerce all the arguments to the type of the first argument, then to the type of the second argument, and so on. Give an example of a situation where this strategy (and likewise the two-argument version given above) is not sufficiently general. (Hint: Consider the case where there are some suitable mixed-type operations present in the table that will not be tried.)
SOLUTION
The code and tests are here.
Explanation of why this strategy is not sufficiently general
Let's assume that we need to support the following operation on three arguments. This function expects the first two arguments x and y to be of any types and the third one "factor" to be an ordinary number. It multiples c1 and c2 and scales the result to the value of factor.
Suppose the following implementations exist in the op-table for the operation "mul-and-scale":
complex, complex, scheme-number
rational, rational, scheme-number
And suppose that there is no procedure for the following:
complex, rational, scheme-number
If apply-generic is called with the above permutation of arguments, it will first fail to find a procedure for it following which it will try to coerce it in the following ways:
complex, complex, complex
rational, rational, rational
scheme-number, scheme-number, scheme-number
None of these will work because there are no procedures for these permutations
But clearly, by coercing the 2nd argument only, this permutation can be coerced into the following permutation:
complex, complex, scheme-number for which which a procedure exists
Hence, the above is an example where this coercion strategy is not sufficiently general.
Comments
Post a Comment