gatoatigrado
gatoatigrado

Reputation: 16850

Haskell default superclass instances

I want to take some of the boilerplate out of Num declarations for a few custom classes (call them Monomial and Polynomial). Instead of writing

instance Num (Monomial) where
    f - g = f + (negate g)
    abs _ = undefined

Is there a way to get around this? I came across default superclass instances and something called "the strathclyde haskell enhancement" which if implemented might let me write something like,

class SimpleNum a => Num a where
    (+) :: a -> a -> a -- standard ring stuff
    (*) :: a -> a -> a
    one :: a
    zero :: a
    instance Num (SimpleNum a) where
        f - g = f + (negate g)
        abs _ = undefined

What's the usual / simple way of dealing with this?

Upvotes: 3

Views: 842

Answers (1)

SamB
SamB

Reputation: 9224

The usual ways of dealing this is to do at least one or more of the following:

  1. Grumble a lot.

  2. Write helper functions like this:

simpleMinus f g = f + (negate g)
  1. Use tools like Template Haskell and Derive.

  2. Attempt to implement extensions like the one you mention. (This unfortunately not as easy as you might think.)

Upvotes: 2

Related Questions