We have seen how to define a unified arithmetic system that encompasses ordinary numbers, complex numbers, rational numbers, and any other type of number we might decide to invent, but we have ignored an important issue. The operations we have defined so far treat the different data types as being completely independent. Thus, there are separate packages for adding, say, two ordinary numbers, or two complex numbers. What we have not yet considered is the fact that it is meaningful to define operations that cross the type boundaries, such as the addition of a complex number to an ordinary number. We have gone to great pains to introduce barriers between parts of our programs so that they can be developed and understood separately. We would like to introduce the cross-type operations in some carefully controlled way, so that we can support them without seriously violating our module boundaries.
One way to handle cross-type operations is to design a different procedure for each possible combination of types for which the operation is valid. For example, we could extend the complex-number package so that it provides a procedure for adding complex numbers to ordinary numbers and installs this in the table using the tag (complex scheme-number):[49]
;; to be included in the complex package
(define (add-complex-to-schemenum z x)
(make-from-real-imag (+ (real-part z) x)
(imag-part z)))
(put 'add '(complex scheme-number)
(lambda (z x) (tag (add-complex-to-schemenum z x))))
This technique works, but it is cumbersome. With such a system, the cost of introducing a new type is not just the construction of the package of procedures for that type but also the construction and installation of the procedures that implement the cross-type operations. This can easily be much more code than is needed to define the operations on the type itself. The method also undermines our ability to combine separate packages additively, or least to limit the extent to which the implementors of the individual packages need to take account of other packages. For instance, in the example above, it seems reasonable that handling mixed operations on complex numbers and ordinary numbers should be the responsibility of the complex-number package. Combining rational numbers and complex numbers, however, might be done by the complex package, by the rational package, or by some third package that uses operations extracted from these two packages. Formulating coherent policies on the division of responsibility among packages can be an overwhelming task in designing systems with many packages and many cross-type operations.
Coercion
In the general situation of completely unrelated operations acting on completely unrelated types, implementing explicit cross-type operations, cumbersome though it may be, is the best that one can hope for. Fortunately, we can usually do better by taking advantage of additional structure that may be latent in our type system. Often the different data types are not completely independent, and there may be ways by which objects of one type may be viewed as being of another type. This process is called coercion. For example, if we are asked to arithmetically combine an ordinary number with a complex number, we can view the ordinary number as a complex number whose imaginary part is zero. This transforms the problem to that of combining two complex numbers, which can be handled in the ordinary way by the complex-arithmetic package.
In general, we can implement this idea by designing coercion procedures that transform an object of one type into an equivalent object of another type. Here is a typical coercion procedure, which transforms a given ordinary number to a complex number with that real part and zero imaginary part:
(define (scheme-number->complex n)
(make-complex-from-real-imag (contents n) 0))
We install these coercion procedures in a special coercion table, indexed under the names of the two types:
(put-coercion 'scheme-number 'complex scheme-number->complex)
(We assume that there are put-coercion and get-coercion procedures available for manipulating this table.) Generally some of the slots in the table will be empty, because it is not generally possible to coerce an arbitrary data object of each type into all other types. For example, there is no way to coerce an arbitrary complex number to an ordinary number, so there will be no general complex->scheme-number procedure included in the table.
Once the coercion table has been set up, we can handle coercion in a uniform manner by modifying the apply-generic procedure of
section 2.4.3. When asked to apply an operation, we first check whether the operation is defined for the arguments’ types, just as before. If so, we dispatch to the procedure found in the operation-and-type table. Otherwise, we try coercion. For simplicity, we consider only the case where there are two arguments.[50] We check the coercion table to see if objects of the first type can be coerced to the second type. If so, we coerce the first argument and try the operation again. If objects of the first type cannot in general be coerced to the second type, we try the coercion the other way around to see if there is a way to coerce the second argument to the type of the first argument.
Finally, if there is no known way to coerce either type to the other type, we give up.
Here is the procedure:
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(if (= (length args) 2)
(let ((type1 (car type-tags))
(type2 (cadr type-tags))
(a1 (car args))
(a2 (cadr args)))
(let ((t1->t2 (get-coercion type1 type2))
(t2->t1 (get-coercion type2 type1)))
(cond (t1->t2
(apply-generic op (t1->t2 a1) a2))
(t2->t1
(apply-generic op a1 (t2->t1 a2)))
(else
(error "No method for these types"
(list op type-tags))))))
(error "No method for these types"
(list op type-tags)))))))
This coercion scheme has many advantages over the method of defining explicit cross-type operations, as outlined above. Although we still need to write coercion procedures to relate the types (possibly n2 procedures for a system with n types), we need to write only one procedure for each pair of types rather than a different procedure for each collection of types and each generic operation.[51] What we are counting on here is the fact that the appropriate transformation between types depends only on the types themselves, not on the operation to be applied.
On the other hand, there may be applications for which our coercion scheme is not general enough. Even when neither of the objects to be combined can be converted to the type of the other it may still be possible to perform the operation by converting both objects to a third type. In order to deal with such complexity and still preserve modularity in our programs, it is usually necessary to build systems that take advantage of still further structure in the relations among types, as we discuss next.
Hierarchies of types
The coercion scheme presented above relied on the existence of natural relations between pairs of types. Often there is more “global” structure in how the different types relate to each other. For instance, suppose we are building a generic arithmetic system to handle integers, rational numbers, real numbers, and complex numbers. In such a system, it is quite natural to regard an integer as a special kind of rational number, which is in turn a special kind of real number, which is in turn a special kind of complex number. What we actually have is a so-called hierarchy of types, in which, for example, integers are a subtype of rational numbers (i.e., any operation that can be applied to a rational number can automatically be applied to an integer). Conversely, we say that rational numbers form a supertype of integers. The particular hierarchy we have here is of a very simple kind, in which each type has at most one supertype and at most one subtype. Such a structure, called a tower, is illustrated in figure 2.25.
If we have a tower structure, then we can greatly simplify the problem of adding a new type to the hierarchy, for we need only specify how the new type is embedded in the next supertype above it and how it is the supertype of the type below it. For example, if we want to add an integer to a complex number, we need not explicitly define a special
coercion procedure integer->complex. Instead, we define how an integer can be transformed into a rational number, how a rational number is transformed into a real number, and how a real number is transformed into a complex number. We then allow the system to transform the integer into a complex number through these steps and then add the two complex numbers.
We can redesign our apply-generic procedure in the following way: For each type, we need to supply a raise procedure, which “raises” objects of that type one level in the tower. Then when the
system is required to operate on objects of different types it can successively raise the lower types until all the objects are at the same level in the tower. (Exercises 2.83 and 2.84
concern the details of implementing such a strategy.)
Another advantage of a tower is that we can easily implement the notion that every type “inherits” all operations defined on a supertype. For instance, if we do not supply a special procedure for finding the real part of an integer, we should nevertheless expect that real-part will be defined for integers by virtue of the fact that integers are a subtype of complex numbers. In a tower, we can arrange for this to happen in a uniform way by modifying apply-generic. If the required operation is not directly defined for the type of the object given, we raise the object to its supertype and try again. We thus crawl up the tower, transforming our argument as we go, until we either find a level at which the desired operation can be
performed or hit the top (in which case we give up).
Yet another advantage of a tower over a more general hierarchy is that it gives us a simple way to “lower” a data object to the simplest representation. For example, if we add 2 + 3i to 4 - 3i, it would be nice to obtain the answer as the integer 6 rather than as the complex number 6 + 0i. Exercise 2.85 discusses a way to implement such a lowering operation. (The trick is that we need a general way to distinguish those objects that can be lowered, such as 6 + 0i, from those that cannot, such as 6 + 2i.)
Inadequacies of hierarchies
If the data types in our system can be naturally arranged in a tower, this greatly simplifies the problems of dealing with generic operations on different types, as we have seen. Unfortunately, this is usually not the case. Figure 2.26 illustrates a more complex arrangement of mixed types, this one showing relations among different types of geometric figures. We see that, in general, a type may have more than one subtype. Triangles and quadrilaterals, for instance, are both subtypes of polygons. In addition, a type may have more than one supertype. For example, an isosceles right triangle may be regarded either as an isosceles triangle or as a right triangle. This multiple-supertypes issue is particularly thorny, since it means that there is no unique way to “raise” a type in the hierarchy. Finding the “correct” supertype in which to apply an operation to an object may involve considerable searching through the entire type network on the part of a procedure such as apply-generic. Since there generally are multiple subtypes for a type, there is a similar problem in coercing a value “down” the type
hierarchy. Dealing with large numbers of interrelated types while still preserving modularity in the design of large systems is very difficult, and is an area of much current research. [52]
(scheme-number complex). [back]Exercises

Comments
vexyGEyQTwdshChALZP
Cheers pal. I do appecritae the writing.
moncler long down xatbogzp
ugg outlet The United Nations (the organisation, not the system) and each specialised agency (as all the other organisations in the UN System are called) are highly autonomous from one another. fluid between the two layers, which can restrict the heart pumping action. I baught an aprtment and am the sole person on the mortgage. Ugg boots ugg australia site we provide the best price ugg with the fastest delivery the most comfortable ugg and the best service is waiting for you welcome.. ugg soldes
uggsaleonlinefinland.com Timberland boots will be perhaps the roughest sneakers currently. Ok, here my fear. The off brands like Bearpaws arent good. An occasional drink with the team after completing a milestone is OK, but don’t make it a habit. 鈾erhaps something similar is happening with the strange “ringing rocks”. With Robert Duffy, Jacobs’ creative collaborator, and business partner since the mid-1980s, he formed Jacobs Duffy Designs Inc which continues to this day.. They sell their own versions of shoes, jeans, t-shirts, sweaters, glasses frames—if you can wear it, a designer will have made it.. This is spun from fine yarns and thus creates a smooth feel.
www.canadagoosefranceoutlet.fr The competition prevailing in the corporate world is not hidden from any person.
gijaajzr doudoune moncler femme pas cher
toms shoes on sale very low priced release selling price sites
About the heals with Tornado Sand with a drop in toms sale River’s ratables base, occupants in the room asked about that can classroom admins diligently strategy her 2013-14 expense plan. Toms Beach reps own said all of the township’s ratable build includes a break down reduction for the assessed 20 percent simply because of the devastation abandoned located in Sandy’s wake up. Which in turn deprivation means lesser return to get intended for city and county, regional and school supporting. A little local people in your Plank siding regarding Studying matching soon pointed out interest this faculty reps “I wouldn’t want to stay in your own situation. I see Sandy’s toy with The year 2013 is seen as a duty raise,Inside announced occupant Dennis Galante, people who speech within the meeting’s criminal idea fraction. “How keep these things balance between the mentors, leadership, office personnel, college students and taxpayers,Inches tall Galante says. “I’m supplying you with the latest require just like a american. I must comprehend organization trimmed shelling out.Throughout “There works as a cutting edge real truth in the industry,Inches width forum Commander in chief David Giovine told me with regards to the irs terrain sticking to Soft sand. Township authorities enjoy announced they will grab the state of hawaii for any more help help balance money subsequent Black sand. “I understandthat the college region was already hold of Toms Pond in doing what the actual township looks to and just what they’re just shopping for by our family,With Giovine says. Homeowner Nels Luthman, exactly who documented the fact that region “does a proper job retaining outlays over,Inches tall hinted at an Barrier relating to University education speak to california for the moment toward change initial funds which goes toward worse and thus underperforming “Abbott districts” towards Sandy-striken towns, cities, Luthman stated. “I’m assured you will be active to pursuing that money considering that income tax burden are going to be high on this town and fork over above and beyond our individual fair share to successfully zones across the mention for about Thirty years,” Luthman discussed. Of the 2012-13 the school 365 days, the very 18-school native area is working even on a $204 , 000, 000 financial plan, another $4 million amplify above the 2011-12 budget. toms shoes Body of water gained close to $67 500, alternatively close to Thirty three pct in their cash, from express support. Town’s dwelling tax bill composed over $133 million, or perhaps a in relation to 65 %, to the $204 million when cheap business earnings. Superintendent of colleges Candid Roselli revealed that often the centre knows the wide ranging cost has an affect on and the man anticipates you becomes aware of tips about how “efficient efficient as a considerate schools area.With Those district’s more or less less for every university student and simply administrator expenses are proof of where, depending on the superintendent. “We have proven to be excellent and in addition we achieve assess price tag actually, very closely,Centimeter Roselli exclaimed. The very cities most typically associated with Toms Pond, Towards the south Toms Ocean, This tree Sea and moreover Beachwood each individual one include the localised school centre and also improvements on their ratables connect with the create the college spending budget. The state run consists of as yet to release the cost calendar for that professional training areas 2013-14 insurance plans, thought game board manhood John Torrone. In 2011, your capacity to purchase was actually qualified at the end of Objective. Torrone, who else this as the an affiliate consumers sat down with if perhaps the snowboard was basically see-through adequate with relieving cheap personas, told me that a different e-commerce lessons high which allows deck players to review financial position body shape incredibly easily. Consumers thanks to madd this will be welcomed to get hold of Business Director William Doering, Roselli asserted.
Post new comment