2014-11-18 2 views
1

Я пытаюсь определить следующий класс & экземплярConstraint ошибка с определением экземпляра

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

instance Adder Num where 
    plus x y = x + y 

Но я получаю эту ошибку

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. 

Позже я хотел бы также определить

instance Adder String where 
    plus x y = x + y 
+0

Я обновил свой ответ с раствором для 'String'. –

ответ

2

Если вы хотите, чтобы любой тип, являющийся экземпляром Num, был экземпляр Adder, вы можете добиться того, что, как:

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

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

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

добавить String экземпляр, вам нужно еще одно расширение языка

{-# 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 = (++) 
Смежные вопросы