为什么Tuple没有Monad实例? [英] Why does Tuple not have a Monad instance?
问题描述
我注意到的一件事是Tuple
没有Monad
实例.
One thing I noticed was that Tuple
does not have a Monad
instance.
元组确实具有一个Applicative
实例:
Tuple does however have an Applicative
instance:
instance Monoid a => Applicative ((,) a)
已经非常严格地限制了我们使Monad
实例成为什么样子.
Which already extremely heavily restricts what we can make the Monad
instance be.
让我们看看我们将获得的连接类型签名:
Lets look at the type signature we would get for join:
instance Monoid a => Monad ((,) a)
join :: Monad m => m (m a) -> m a
join :: Monoid a => (a, (a, b)) -> (a, b)
我们还可以查看Monad法则:
We can also look at the Monad laws:
join $ f <$> pure x == f x
join $ f <$> (mempty, x) == f x
join (mempty, f x) == f x
join (mempty, (a, b)) == (a, b)
join $ pure <$> x = x
join $ pure <$> (a, b) = (a, b)
join (a, (mempty, b)) = (a, b)
至此,我们知道以任何一种方式组合mempty
和x
都会导致x
.我们唯一有关x
的类型信息是它是Monoid
.因此,基本上仅有的两种实现是:
At this point we know that combining mempty
and x
in either way results in x
. And the only type information we have about x
is that it is a Monoid
. So basically the only two implementations are:
join (a, (b, x)) = (a <> b, x)
和:
join (a, (b, x)) = (b <> a, x)
其中第二个使ap
和<*>
不同.
所以现在我们知道((,) a)
唯一有效的Monad
实例是:
So now we know that the only valid Monad
instance for ((,) a)
is:
instance Monoid a => Monad ((,) a) where
(a, c) >>= f = let (b, c') = f c in (a <> b, c')
那为什么现在不是这种情况呢?
So why is that not currently the case?
推荐答案
这个问题的答案似乎是我只需要使用ghc-8.0.1
,它确实为Tuple
提供了一个Monad
实例.感谢@Michael指出了这一点.
Well it seems like the answer to this question is that I just have to use ghc-8.0.1
, which does give Tuple
a Monad
instance. Credit to @Michael for pointing this out.
这篇关于为什么Tuple没有Monad实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!