[Haskell-cafe] Double-dispatch
wren ng thornton
wren at freegeek.org
Tue Mar 6 06:28:10 CET 2012
On 3/5/12 4:24 PM, Clark Gaebel wrote:
> Well look at that.
>
> Thanks!
>
> On Mon, Mar 5, 2012 at 4:07 PM, Felipe Almeida Lessa
> <felipe.lessa at gmail.com> wrote:
>> {-# LANGUAGE MultiParamTypeClasses #-}
>>
>> class Intersectable a b where
>> intersectsWith :: a -> b -> Bool
Assuming that intersectsWith is something like unification, equality, or
similar operations:
Do note that this can lead to needing quadratically many instances,
about half of which will be redundant if intersectsWith is supposed to
be symmetric.
Often times we know that the vast majority of these quadratically many
instances should be vacuous (i.e., always return False), and it'd be
nice to avoid writing them out. This can be achieved via
-XOverlappingInstances where you give a default instance:
instance Intersectable a b where intersectsWith _ _ = False
and then override it for more specific choices of a and b. Beware that
if you want to have other polymorphic instances you may be forced to use
-XIncoherentInstances, or else resolve the incoherence by filling out
the lattice of instances.
The other notable complication is if you want your collection of types
to have more than just a set structure (e.g., if you want some kind of
subtyping hierarchy). It's doable, but things get complicated quickly.
Other than those caveats, have at it! The ability to do this sort of
thing is part of what makes Haskell great. Few languages have
multiple-dispatch this powerful.
--
Live well,
~wren
More information about the Haskell-Cafe
mailing list