Tuple subclassing example
Factor handbook » The language » Objects » Tuples » Tuple subclassing

Next:When not to use tuple subclassing


Rectangles, parallelograms and circles are all shapes. We support two operations on shapes:
Computing the area
Computing the perimeter

Rectangles and parallelograms use the same algorithm for computing the area, whereas they use different algorithms for computing perimeter. Also, rectangles and parallelograms both have width and height slots. We can exploit this with subclassing:
USING: accessors kernel math math.constants math.functions ; GENERIC: area ( shape -- n ) GENERIC: perimeter ( shape -- n ) TUPLE: shape ; TUPLE: circle < shape radius ; M: circle area radius>> sq pi * ; M: circle perimeter radius>> 2 * pi * ; TUPLE: quad < shape width height ; M: quad area [ width>> ] [ height>> ] bi * ; TUPLE: rectangle < quad ; M: rectangle perimeter [ width>> 2 * ] [ height>> 2 * ] bi + ; : hypot ( a b -- c ) [ sq ] bi@ + sqrt ; TUPLE: parallelogram < quad skew ; M: parallelogram perimeter [ width>> 2 * ] [ [ height>> ] [ skew>> ] bi hypot 2 * ] bi + ;