[Haskell-cafe] casting

Misha Aizatulin avatar at hot.ee
Mon Oct 9 09:13:34 EDT 2006

Thomas Conway wrote:
> I'm having some difficulty with typeclasses.
> What I'm trying to do should be obvious, but it's still giving me
> trouble. I want to take a packaged item, and strengthen the
> constraints on its type. Rather than being just any type that is an
> instance of A, I want to do a runtime check and do something different
> if it is a type that is also an instance of B (which implies that it
> is an instance of A also).

  It is not possible to check at run time, whether an instance of some
class is available for a given value. If a constraint is not mentioned
at compile time, the dictionary for that constraint will not be included
at run time, so there will be nowhere to get it from (unlike in Java,
where every object "carries" along all the dictionaries that it implements).

  Having said that there is a hack/technique that I am using myself -
maybe it will help you. It simulates something similar to what Java
does. I rewrote your program to use it - result attached here.
  The idea is to have an existential box for each class so that this box
carries the dictionary at run time. We call such a box an "interface"
and provide for our values a runtime list of interfaces that they
implement. This list is available as a function of the Interfaced class.

  You might also look at the paper "Scrap your boilerplate with class:
extensible generic functions" by Ralf Lämmel and Simon Peyton-Jones.
Among other things they describe existential boxes that can be
parametrized with the context that they carry.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: Interface.hs
Type: text/x-haskell
Size: 518 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20061009/1b6a2013/Interface.bin
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Cast.hs
Type: text/x-haskell
Size: 950 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20061009/1b6a2013/Cast.bin

More information about the Haskell-Cafe mailing list