简体   繁体   English

我如何在Haskell中将monad任意数目加在一起?

[英]How do I monad an arbitrary number of Monads together in Haskell?

Let's say I have 假设我有

x :: Monad a => [a]
x = [item1, item2, item3, ...]

And I want to do for these: 我想为这些做:

y f = f <$> item1 <*> item2 <*> item3 <*> item4 <*> ...

Previously I've tried this for doing it with ZipLists: 以前,我曾尝试使用ZipLists做到这一点:

zipf' x (y:z) = getZipList $ foldl (<*>) (x <$> y) z

But it unfortunately returned this: 但不幸的是,它返回了:

<interactive>:94:36: error:
• Occurs check: cannot construct the infinite type: a1 ~ a -> a1
  Expected type: ZipList a1 -> ZipList a -> ZipList a1
    Actual type: ZipList (a -> a1) -> ZipList a -> ZipList a1
• In the first argument of ‘foldl’, namely ‘(<*>)’
  In the second argument of ‘($)’, namely ‘foldl (<*>) (x <$> y) z’
  In the expression: getZipList $ foldl (<*>) (x <$> y) z
• Relevant bindings include
    z :: [ZipList a] (bound at <interactive>:94:12)
    y :: ZipList a (bound at <interactive>:94:10)
    x :: a -> a1 (bound at <interactive>:94:7)
    zipf' :: (a -> a1) -> [ZipList a] -> [a1]
      (bound at <interactive>:94:1)

The type 方式

x :: Monad a => [a]

is impossible: you cannot have such a thing, because Monad needs a type parameter. 不可能:您不可能有这样的事情,因为Monad需要类型参数。 You probably mean 你可能是说

x :: Monad m => [m a]

After that, the next problem is: what is the type of y ? 之后,下一个问题是: y的类型是什么? It takes a function f , and that f somehow accepts any number of arguments? 它需要一个函数f ,并且f以某种方式接受任意数量的参数? That doesn't sound right, which is why GHC is complaining about the infinite type: f 's type must contain as a subterm the type of f itself. 听起来不对,这就是GHC抱怨无限类型的原因: f的类型必须包含f本身的类型作为子项。

Perhaps you mean something more like foldM ? 也许您的意思更像foldM Whether or not foldM is what you need after all, your search will be easier once you nail down the correct types of the functions you're after. foldM是否是您所需要的,一旦您确定要使用的正确类型的函数,搜索就会更加容易。

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

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