The ability to display non-textual results (such as graphics and animations) inline in playgrounds is one of Haskell for Mac's distinguishing features. This ability used to be reserved for values of a few built-in types. In Version 1.3.1, we have made it user-extensible, by way of instances of the type class
IDE.HaskellForMac.Playground, which we introduced newly, provides this class.
Presentable class determines the set of types whose values can be displayed in playgrounds — just like
Show determines the set of types that can be converted to
String with the
show function. The first instance of
Presentable above makes every type in
Show also a member of
Presentable. As this instance is marked as
OVERLAPPABLE, we do retain the option to subsequently provide more specific instances for any of those types in
Show. (The most specific instance always takes precedence.) In other words, the string representation of a type's values is the default representation in the playground, but we can always override this with a more sophisticated representation.
Out of the box, the system already provides instances for SpriteKit types (including entire SpriteKit scenes),
JuicyPixels images types, and the most commonly used HTML & SVG representations. Let's look at extending this in a simple example.
The chapter More about Algebraic Data Types of the Learning Haskell tutorial provides a function, called
renderTree, to draw a tree diagram for simple binary trees. Previously, we could call
renderTree and then convert the diagram with
drawPicture into a basic image type that the playground finally displayed. We had to do this at every place where we wanted to render a tree. Now, we simply define a class instance, once.
Presentation type produced by the
present method is opaque, user instances will typically convert values of user-defined types into values of one of the types that are already
Presentable — just as in this example. You can download the whole project, to see how it works in detail: PresentableTrees.hsproj.