[Haskell-cafe] How far can you take overloading with type classes?

Alexis King lexi.lambda at gmail.com
Wed Jun 13 04:37:11 UTC 2018


Sure, it can certainly be done:

  class CombineLines a b where
    (++) :: a -> b -> Lines

  instance CombineLines Line Line where { ... }
  instance CombineLines Line Lines where { ... }
  instance CombineLines Lines Line where { ... }
  instance CombineLines Lines Lines where { ... }

Of course, whether or not such a class is an especially useful thing is
another matter entirely. Other encodings might be more helpful in
practice. Perhaps something like this is closer to what you really want:

  class ToLines a where
    toLines :: a -> Lines

  instance ToLines Line where
    toLines = lineToLines
  instance ToLines Lines where
    toLines = id

  (++) :: (ToLines a, ToLines b) => a -> b -> Lines
  x ++ y = toLines x `addLines` toLines y

Or perhaps none of these are really all that helpful in practice, and
the overloading isn’t really worth it.


> On Jun 12, 2018, at 22:58, Hilco Wijbenga <hilco.wijbenga at gmail.com> wrote:
> 
> Hi all,
> 
> Given definitions of Line and Lines is it possible to define a type
> class (or maybe multiple type classes) that would allow for the
> following:
> 
> (++) :: Line -> Line -> Lines
> (++) :: Line -> Lines -> Lines
> (++) :: Lines -> Line -> Lines
> (++) :: Lines -> Lines -> Lines
> 
> I.e. is there a way to overload (++) such that it supports each of
> these 4 combinations? (Let's ignore that (++) already exists for the
> moment.)
> 
> Cheers,
> Hilco



More information about the Haskell-Cafe mailing list