简体   繁体   English

如果应用就足够了,为什么序列需要monad?

[英]Why sequence requires monad if applicative would suffice?

The signature of sequence is 序列的签名是

sequence :: Monad m => t (m a) -> m (t a)

But we can implement it as 但我们可以实现它

sequence = traverse id

requiring m to be just Applicative . 要求m只是Applicative If monads are applicatives then why bother having this constraint on type level? 如果monad是applicatives那么为什么在类型级别上有这个约束呢?

There are many functions in Haskell that are equivalent but distinct because Applicative (resp. Functor ) didn't use to be a superclass of Monad . Haskell中有许多函数是等价但不同的,因为ApplicativeFunctor )并没有用作Monad的超类。 For example: 例如:

  • return vs. pure returnpure

  • ap vs. <*> ap vs. <*>

  • liftM vs. liftA vs. fmap liftM vs. liftA vs. fmap

  • liftM2 , liftM3 , &c. liftM2liftM3 ,&c。 vs. liftA2 , liftA3 , &c. liftA2liftA3 ,&c。

  • mapM / forM vs. traverse / for mapM / forMtraverse / for

  • mapM_ / forM_ vs. traverse_ / for_ mapM_ / forM_traverse_ / for_

  • sequence vs. sequenceA sequencesequenceA

  • mzero & mplus (from MonadPlus ) vs. empty & <|> (from Alternative ) mzeromplus (来自MonadPlus )与empty &&( <|>来自Alternative

The old functions with their original Monad signatures are still present, but in new code, since the Applicative–Monad Proposal (AMP) was implemented, you can always use the Applicative versions because they're slightly more general—that is, you can always replace return with pure , but not vice versa. 具有原始Monad签名的旧功能仍然存在,但在新代码中,自应用Monad Proposal(AMP)实施以来,您可以始终使用Applicative版本,因为它们稍微更通用 - 也就是说,您可以随时使用用pure代替return ,但反之则不然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM