我创建了自己的数据类型,并尝试实现仿函数方法如下:
data Hieu a = Hieu [a] deriving (Show, Read, Eq)
instance Functor Hieu where
fmap f (Hieu [x]) = Hieu (f [x])
这是一段非常简单的代码,但它失败了。你能解释一下为什么吗?
感谢您的所有回复。现在我明白了我只将仿函数应用于一种情况。我试图重写如下,不使用地图
data Hieu a = Hieu [a] deriving (Show, Read, Eq)
consHieu :: a -> (Hieu a) -> (Hieu a)
consHieu x (Hieu xs) = Hieu (x:xs)
instance Functor Hieu where
fmap f (Hieu (x:xs)) = consHieu (f x) (fmap f (Hieu xs))
fmap f (Hieu []) = Hieu []
感谢您的所有回复。现在我明白了我只将仿函数应用于一种情况。我试图重写如下,不使用地图
data Hieu a = Hieu [a] deriving (Show, Read, Eq)
consHieu :: a -> (Hieu a) -> (Hieu a)
consHieu x (Hieu xs) = Hieu (x:xs)
实例 Functor Hieu 在哪里
fmap f (Hieu (x:xs)) = consHieu (f x) (fmap f (Hieu xs))
fmap f (Hieu []) = Hieu []