简体   繁体   English

如何将一系列单子动作应用于 Haskell 中的同一个参数?

[英]How do I apply a series of monadic actions to the same argument in Haskell?

In Haskell, is there a way to simplify the following code to remove the repeating of "hello world"? Haskell,有没有办法简化下面的代码,去掉“hello world”的重复? In other words, applying f , g , and h to hello world ?换句话说,将fgh应用于hello world

fn = do
  a <- f "hello world"
  b <- g "hello world"
  c <- h "hello world"
  return (a, b, c)

If f , g and h have the same type, you can simply loop over them:如果fgh具有相同的类型,您可以简单地遍历它们:

  [a,b,c] <- forM [f,g,h] ($"hello world")

If they have different types, you can use the fact that functions form a monad, and in particular can be stacked as a monad transformer on top of your current monad:如果它们有不同的类型,你可以使用函数形成一个 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.

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