我试图从this paper第一章,它是这样实现的例子时:得到一个错误“应用型的无实例”声明一个单子
data Tree a = Fork (Tree a) (Tree a) | Leaf a | Nil deriving (Show)
instance Monad Tree where
return a = Leaf a
Nil >>= f = Nil
Leaf a >>= f = f a
Fork u v >>= f = Fork (u >>= f) (v >>= f)
tree1 = Fork
(Fork (Leaf 2) Nil)
(Fork (Leaf 2) (Leaf 3))
tree2 = Fork (Leaf 2) (Leaf 3)
f 2 = Fork Nil (Leaf "Two")
f 3 = Fork (Leaf "Three") (Leaf "String")
tree3 = tree2 >>= f
当我在GHC运行它,我得到这个错误:
monads.hs:3:10:
No instance for (Applicative Tree)
arising from the superclasses of an instance declaration
In the instance declaration for ‘Monad Tree’
Failed, modules loaded: none.
我尝试添加这开始
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
但我得到这个错误:
monads.hs:7:10:
Ambiguous occurrence ‘Monad’
It could refer to either ‘Main.Monad’, defined at monads.hs:1:1
or ‘Prelude.Monad’,
imported from ‘Prelude’ at monads.hs:1:1
(and originally defined in ‘GHC.Base’)
什么是最正确的修复?
您不能定义一个类('Monad '或别的东西)两次...... –
自那篇论文以来,'Monad'获得了'Applicative'的依赖。不过,你应该能够使用'ap'和'return'来实现它。 –
要真正明确地说明问题,您遇到的问题是此代码在较早版本的Haskell中工作,但在GHC的最新版本中不再使用。最近的版本不允许你定义一个'Monad'实例,除非有问题的类型也有'Functor'和'Applicative'实例。 –