[英]How do I apply a series of monadic actions to the same argument in Haskell?
Haskell,有沒有辦法簡化下面的代碼,去掉“hello world”的重復? 換句話說,將f
、 g
和h
應用於hello world
?
fn = do
a <- f "hello world"
b <- g "hello world"
c <- h "hello world"
return (a, b, c)
如果f
、 g
和h
具有相同的類型,您可以簡單地遍歷它們:
[a,b,c] <- forM [f,g,h] ($"hello world")
如果它們有不同的類型,你可以使用函數形成一個 monad 的事實,特別是可以作為一個 monad 轉換器堆疊在你當前的 monad 之上:
import Control.Monad.Trans.Reader
fn = (`runReaderT`"hello world") $ do
a <- ReaderT f
b <- ReaderT g
c <- ReaderT h
return (a, b, c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.