[Haskell-cafe] Random thoughts about typeclasses

Casey McCann syntaxglitch at gmail.com
Mon May 16 15:45:01 CEST 2011

On Mon, May 16, 2011 at 8:10 AM, Robert Clausecker <fuzxxl at gmail.com> wrote:
> I found out, that GHC implements typeclasses as an extra argument, a
> record that stores all functions of the typeclass. So I was wondering,
> is there a way (apart from using newtype) to pass a custom record as the
> typeclass record, to modify the behavior of the typeclass? I thought
> about something like this:

Would GHC's implicit parameter extension possibly suit your purposes
here? Your example would translate as:

    {-# LANGUAGE ImplicitParams #-}

    type ShowClass a = a -> String

    f :: (?showC :: ShowClass a) => [a] -> String
    f x = x >>= ?showC

    g :: [Int] -> String
    g = let ?showC = show in f

    g2 :: [Int] -> String
    g2 = let ?showC = (return . toEnum) in f


    > g [72, 97, 115, 107, 101, 108, 108]
    > g2 [72, 97, 115, 107, 101, 108, 108]

Clearly this doesn't allow you retrofit such functionality onto
existing code using existing type classes, but I'd be wary of doing
that anyway--type class instances are not something that code will
expect to have changing out from under it. Otherwise, this seems to be
exactly what the implicit parameters extension is designed for,
judging from the way the GHC user's guide describes it.

- C.

More information about the Haskell-Cafe mailing list