Contents

Class Number


Inheritance:

Object  »
  Magnitude  »
    Number
      Float  »
      Fraction  »
      Integer  »
        LargePositiveInteger
          LargeNegativeInteger
        SmallInteger

Class Number holds the most general methods for dealing with numbers. Subclasses Float, Fraction, and Integer, and their subclasses, provide concrete representations of a numeric quantity.

All of Number's subclasses implement a double dispatch mechanism to support mixed-mode arithmetic and comparisons. It works as follows: If an arithmetic operation or a comparision

<receiver> op: <arg>

fails because of incompatible types, the <receiver> informs the <arg> about the failure. It is then the responsibility of the <arg> to resolve the type incompatibility.

adaptTo<typeOfReceiver>: leftOperand andSend: messageSelector

Rules for type adaption methods:

All of Number's subclasses participate in a simple type coercion mechanism that supports mixed-mode arithmetic and comparisons. It works as follows: If an arithmetic operation or a comparision

<receiver> op: <arg>

fails because of incompatible types, the <receiver> informs the <arg> about the failure. It is then the responsibility of the <arg> to resolve the type incompatibility.

(arg adaptTypeA: self) op: arg adaptToTypeA.

This gives the arg of typeB an opportunity to resolve the incompatibility, knowing exactly what two types are involved. If self is more general, then arg will be converted, and vice versa. This mechanism is extensible to any new number classes that one might wish to add to Squeak. The only requirement is that every subclass of Number must support a pair of conversion methods specific to each of the other subclasses of Number.

The principle of this pattern is to return a problem to the instance that caused the problem. The originator of the problem is expected to solve problem; it is provided with all information that is needed to find out what happened: The receiver of the messsage that detected the problem and the message selector.

The advantage of the pattern is that it makes arithmetic operations extensible in the following sense: To extend arithmetic to instances of a new class all necessary type coercions are implemented in the new class - additions to the Number classes are not needed. The new class has to implement some or all of the following messages:

message name
description
adaptToNumber:andSend:

This is the most general coercion operation. An implementation of this method is not needed in classes that define all three more specific coercion methods.

adaptToInteger:andSend:

A specialized coercion method that is sent from integers.

adaptToFraction:andSend:

A specialized coercion method that is sent from fractions.

adaptToFloat:andSend:

A specialized coercion method that is sent from floats.


Contents