数据类型MyList到Class Semigroup和Class Monoid的实例声明

时间:2018-06-10 17:07:09

标签: haskell

MyList a就像列表一样我已经定义了一些函数来创建concat',相当于(++)。我想为MyList a

制作一个实例声明
instance Semigroup [a] where
    -- (<>) :: [a] -> [a] -> [a]
    (<>) = (++)
instance Monoid [a] where
    -- mempty :: [a]
    mempty = []

我有GHCi版本8.2.2。

data MyList a = Leer | Element a (MyList a) deriving (Show,Eq)

last' :: Eq a => MyList a -> a
last' Leer = undefined
last' (Element x(xs))
    | xs == Leer = x
    | otherwise = last' xs
w :: MyList a -> a -> MyList a
w Leer x = Element x (Leer)
w xs x = Element x (xs)
concat' :: Eq a => MyList a -> MyList a -> MyList a
concat' x Leer = x
concat' (Element x (xs)) ys
    | xs == Leer = (Element x (ys))
    | otherwise = concat' (Element x (deletelst xs)) (w ys (last' xs))

length' :: MyList a -> Int
length' Leer = 0
length' (Element x (xs)) = 1 + length' (xs)
take' :: Int -> MyList a -> MyList a
take' _ Leer = Leer
take' 0 _ = Leer
take' z (Element x (xs)) = Element x (take' (z-1) xs)

deletelst :: MyList a-> MyList a
deletelst Leer = Leer
deletelst xs = (take' ((length' xs) - 1) xs) 

instance Semigroup (MyList a) where
    (<>) = concat'
instance Monoid (MyList a) where
    mempty = Leer
    mappend = (<>)

当我尝试编译程序时,会弹出此错误消息:

FH.hs:115:12: error:
    * No instance for (Eq a) arising from a use of concat'
    Possible fix: add (Eq a) to the context of the instance declaration
    * In the expression: concat'
    In an equation for `<>': (<>) = concat'
    In the instance declaration for `Semigroup (MyList a)'

1 个答案:

答案 0 :(得分:3)

错误消息告诉您 问题所在:

* In the expression: concat'
In an equation for `<>': (<>) = concat'
In the instance declaration for `Semigroup (MyList a)'

就在这里:

instance Semigroup (MyList a) where
    (<>) = concat'

它还告诉你问题是什么

* No instance for (Eq a) arising from a use of concat'
Possible fix: add (Eq a) to the context of the instance declaration

确实,您使用concat'来定义(<>),但您对concat'的定义需要Eq a的实例,该实例不作为实例声明的上下文存在Semigroup (MyList a) - 换句话说,您定义的是instance Semigroup (MyList a),而不是instance Eq a => Semigroup (MyList a)。您可以添加该上下文,但有一个更原则的解决方案:通过使用模式匹配从Eq a(以及concat')的定义中删除(不必要的)last'约束:

concat' :: MyList a -> MyList a -> MyList a
concat' x Leer              = x
concat' (Element x Leer) ys = Element x ys
concat' (Element x xs) ys   = concat' (Element x (deletelst xs)) (w ys (last' xs))

last' :: MyList a -> a
last' Leer             = undefined
last' (Element x Leer) = x
last' (Element x xs)   = last' xs