我試圖從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'實例。 –