List of different types?

This problem represents a turning point between object-oriented and functional thinking. Sometimes even sophisticated Haskellers are still in this mental transition, and their designs often fall into the existential typeclass pattern, mentioned in Thomas’s answer.

A functional solution to this problem involves reifying the typeclass into a data type (usually once this is done, the need for the typeclass vanishes):

data Shape = Shape {
    intersect :: Ray -> Maybe Point,
    surfaceNormal :: Point -> Vector Double
}

Now you can easily construct a list of Shapes, because it is a monomorphic type. Because Haskell does not support downcasting, no information is lost by removing the representational distinction between Planes and Spheres. The specific data types become functions that construct Shapes:

plane :: Point -> Vector Double -> Shape
sphere :: Point -> Double -> Shape

If you cannot capture everything you need to know about a shape in the Shape data type, you can enumerate the cases with an algebraic data type, as Thomas suggested. But I would recommend against that if possible; instead, try to find the essential characteristics of a shape that you need rather than just listing off examples.

Leave a Comment