robkuz
robkuz

Reputation: 9934

Constraint Error with instance definition

I am trying to define the following class & instance

class Adder a where  
    plus :: a -> a -> a  

instance Adder Num where  
    plus x y = x + y

But I am getting this error

Expecting one more argument to ‘Num’
The first argument of ‘Adder’ should have kind ‘*’,
  but ‘Num’ has kind ‘* -> Constraint’
In the instance declaration for ‘Adder Num’
Failed, modules loaded: none.

Later I would like to also define

instance Adder String where  
    plus x y = x + y

Upvotes: 1

Views: 182

Answers (1)

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

If you want any type that is an instance of Num to be an instance of Adder, you can achieve that like:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}

class Adder a where
    plus :: a -> a -> a

instance Num a => Adder a where   
    plus = (+)

to add a String instance, you need one more language extension

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE OverlappingInstances #-}

class Adder a where
    plus :: a -> a -> a

instance Num a => Adder a where    
    plus = (+)

instance Adder String where
    plus = (++)

Upvotes: 2

Related Questions