[Haskell-cafe] Parallel numeric class hierarchy

adam vogt vogt.adam at gmail.com
Sat Feb 28 21:11:54 UTC 2015

On Sat, Feb 28, 2015 at 12:28 PM, Clinton Mead <clintonmead at gmail.com> wrote:
> Let's say for arguments sake I want to make a new finer grained numeric
> class hierarchy. But, I also want to have the following occur:
> (1) Existing modules which have defined data types which have Num instances
> can be used with functions in my new hierarchy
> (2) New data types defined in the new hierarchy automatically get Num
> instances if appropriate so they can be used in existing modules.
> I know this is somewhat of a vague question but roughly how would I go about
> this?

You could use overlapping & undecidable instances to get (1) and (2):

class Plus a where
  plus :: a -> a -> a

class NewNum a -- no methods

-- a type using the "new" hierarchy
data X = X Int
instance Plus X where
  X a `plus` X b = X (a+b)
instance NewNum X

instance Num a => Plus a where
  plus = (Prelude.+)

instance (Plus a, Minus a, ... , NewNum a) => Num a where
  (+) = plus

Having an extra constraint NewNum stops "() + ()" from being an
infinite loop where we can make an instance Num () if we have an
instance Plus () which exists if we have Num () ...

The usual objection to overlapping instances (that adding an import
can change the result of the program), is probably less of a problem
here than usual because + and plus have a chance of still doing the
same thing when somebody defines "instance Num X" separately.


More information about the Haskell-Cafe mailing list