[英]How do I monad an arbitrary number of Monads together in Haskell?
假设我有
x :: Monad a => [a]
x = [item1, item2, item3, ...]
我想为这些做:
y f = f <$> item1 <*> item2 <*> item3 <*> item4 <*> ...
以前,我曾尝试使用ZipLists做到这一点:
zipf' x (y:z) = getZipList $ foldl (<*>) (x <$> y) z
但不幸的是,它返回了:
<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)
方式
x :: Monad a => [a]
不可能:您不可能有这样的事情,因为Monad需要类型参数。 你可能是说
x :: Monad m => [m a]
之后,下一个问题是: y
的类型是什么? 它需要一个函数f
,并且f
以某种方式接受任意数量的参数? 听起来不对,这就是GHC抱怨无限类型的原因: f
的类型必须包含f
本身的类型作为子项。
也许您的意思更像foldM
? foldM
是否是您所需要的,一旦您确定要使用的正确类型的函数,搜索就会更加容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.