3
我寫單子的實現自定義類型:如何閱讀編譯器錯誤
data Sum a b =
First a
| Second b
deriving (Eq, Show)
instance Functor (Sum a) where
fmap _ (First x) = First x
fmap f (Second y) = Second (f y)
instance Applicative (Sum a) where
pure = Second
First x <*> _ = First x
_ <*> First x = First x
Second f <*> Second x = Second (f x)
instance Monad (Sum a) where
return = pure
(First a) >>= _ = First a
(Second a) >>= k = Second (k a)
,我知道這是錯誤的。編譯器抱怨:
D:\haskell\chapter18\src\SumMonad.hs:39:24: error:
* Couldn't match type `b' with `Sum a b'
`b' is a rigid type variable bound by
the type signature for:
(>>=) :: forall a1 b. Sum a a1 -> (a1 -> Sum a b) -> Sum a b
at D:\haskell\chapter18\src\SumMonad.hs:38:15
Expected type: Sum a b
Actual type: Sum a (Sum a b)
* In the expression: Second (k a)
In an equation for `>>=': (Second a) >>= k = Second (k a)
In the instance declaration for `Monad (Sum a)'
* Relevant bindings include
k :: a1 -> Sum a b
(bound at D:\haskell\chapter18\src\SumMonad.hs:39:20)
(>>=) :: Sum a a1 -> (a1 -> Sum a b) -> Sum a b
(bound at D:\haskell\chapter18\src\SumMonad.hs:38:5)
Failed, modules loaded: none.
如何讀取編譯器錯誤?