【发布时间】:2023-03-08 20:48:01
【问题描述】:
我想在 Haskell 中实现我的列表。
但我不能这样做。 <*>的实现导致
data List a = a :+ (List a) | Empty deriving Show
infixr 9 :+
instance Functor List where
fmap _ Empty = Empty
fmap f (a :+ xs) = f a :+ fmap f xs
instance Applicative List where
pure x = x :+ Empty
Empty <*> _ = Empty
(f :+ fs) <*> xs = fmap f xs :+ (fs <*> xs) -- Error
main :: IO ()
main = do
print $ 1 :+ 2 :+ 3 :+ Empty
print $ fmap (^2) (1 :+ 2 :+ 3 :+ Empty)
print $ ((+1) :+ (*2) :+ (^2) :+ Empty) <*> (1 :+ 2 :+ 3 :+ Empty)
错误是
无法将预期类型“b”与实际类型“列表 b”匹配 ‘b’ 是一个被 ... 绑定的刚性类型变量。
【问题讨论】:
-
您正在尝试使用
:+构造函数来连接两个列表。 -
谢谢!我现在明白了。