我正在尝试定义以下类&实例
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 :(得分: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 = (++)