[Haskell-cafe] [ANN] ttc- - Textual Type Classes

Travis Cardwell travis.cardwell at extrema.is
Thu Jun 3 07:43:55 UTC 2021

On Thu, Jun 3, 2021 at 2:57 PM Henning Thielemann wrote:
> That is, your class is intended for text representation for program users
> (instead of programmers)?

Yes, that is correct.  While Show instances should produce valid Haskell
code and Read instances should parse that code to create the original
value, forming an isomorphism, the Render and Parse type classes can be
used by the developer to define instances as required for each
particular application.  The Render and Parse type classes in Data.TTC
have no instances, allowing developers to write their own instances for
Int for example, but some default instances can optionally be imported
from Data.TTC.Instances when they are appropriate.

> I think a notable difference between Show (which is for programmers) and a
> human readable text formatter should be a control of formatting details.
> Currently 'printf' is the way to format human readable text and you can
> control formatting of numbers e.g. by "%d", "%3d", "%03d" etc. It's not
> type safe but better than Show.

Indeed.  Due to the nature of type classes, each concrete type can have
a single instance.  I usually define Render and Parse instances that use
the canonical representation, and I provide separate functions for
customized formatting based on options.  Functions that only need the
canonical representation can rely on the Render instance, while
functions that need to be more flexible can accept a render/formatting
function, to which TTC.render can be passed when the canonical
representation is sufficient.

I worry that my explanation is not clear, so here is a minimal example,
using a type Quantity that is assumed to have a Render instance.

    -- This function relies on the Render instance of Quantity.
    formatQuantityList :: [Quantity] -> Text

    -- This function allows you to customize how a Quantity is rendered.
    -- TTC.render can be passed as the first argument when appropriate.
    formatQuantityList' :: (Quantity -> Text) -> [Quantity] -> Text

The common way to get around the one-instance-per-type limitation is to
use newtypes.  I generally do not use this strategy with TTC to
provide different ways to format text, however.

Best regards,


More information about the Haskell-Cafe mailing list