我如何在 Haskell 中将任意数量的 Monad 组合在一起?
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
是否是您所需要的,一旦您确定了您所追求的函数的正确类型,您的搜索就会变得更加容易。
假设我有
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
是否是您所需要的,一旦您确定了您所追求的函数的正确类型,您的搜索就会变得更加容易。