实例定义的约束错误

时间:2014-11-18 10:00:24

标签: haskell

我正在尝试定义以下类&实例

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

1 个答案:

答案 0 :(得分: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 = (++)