Full-blown algebraic datatypes
Full-blown algebraic datatypes combine the capabilities of both enumeration types and record types. Indeed, an ADT can have one or more data constructors, and each data constructor can have zero or more fields.
Shapes
The following Shape
datatype features two constructors with a number of fields:
data Shape = Circle Double | Rectangle Double Double
A shape can be either a circle with a given radius or a rectangle with a given width and height. The next function computes the area of such a shape:
area :: Shape -> Double area (Circle r) = pi * r**2 area (Rectangle w h) = w * h
This function has two equations, one with a pattern for each of the two Shape
constructors. This case analysis is a common template for writing functions over an ADT. The general shape of such a function for Shape
is as follows:
f :: Shape -> … f (Circle...