[英]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.