The 'Display' classIn a traditional, interactive text-based Haskell environment, such as Hugs or GHCi, when an expression is typed at the prompt, it is converted into a string and shown on the output device. The conversion into a string takes place by the implicit application of the
showmethod of the
class Show a where show :: a -> String . . .In Pivotal, in an analogous way, when an expression occurs in a document, it is converted into a picture and displayed at that point in the document. The conversion into a picture takes place by the implicit application of the
displaymethod of the
class Show a => Display a where display :: a -> Pic . . . display x = PicText black 12 (show x) -- default method for 'display'For user-defined types, the implementor is free to define an appropriate instance declarations of the
Displayclasses. For example, for an ADT representing positions in the game of chess, the
displaymethod could be defined to display positions in the conventional diagrammatic form.
If, for a particular type, the
display method is not explicitly defined, the default
method of the class is used. This (see above) uses the
show method to convert the value into a string and then the
PicText constructor to convert this string into a 'picture' of the string. Since no '
declarations are made for the standard types (
Int, etc.) defined in the Prelude,
values of these types are thus displayed in textual form in the usual way.
ExampleAs a (rather simple!) example, suppose an end-user has an interest in triangles. A first step would thus be for the user (or a tool-builder) to introduce a representation for triangles. This could be simple datatype with a constructor for holding the lengths of the three sides of the triangle:
data Triangle = Tri Double Double Double deriving ShowWith this type defined, the user is able to construct value of type
Triangleand display their values textually. For example: However, in this context, a textual representation is not a very intuitive form to use.
Defining a pictorial representationSuppose the user would prefer to be able to display values of type
Trianglepictorially. This is easily done: a conversion function, of type:
drawTri :: Triangle -> Pic drawTri (Tri a b c) = Poly red False [ . . . ]can be written to compute the coordinates of the vertices as a function of the lengths of the sides and used to display triangle values:
Defining an instance of the Display classFinally, we can define an instance, for the type
Triangle, for the
Displayclass. This means that the system will then automatically invoke the
drawTrifunction whenever a value of type
Triangleneeds to be displayed. For example: