本文介绍了提取嵌套的monadic结果:m(m a) - >嘛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数

  parseArgs :: [String]  - > StdGen  - > IO()

它选择要运行的函数。主要看起来像

  main = parseArgs< $> getArgs< *> getStdGen>> = id 

我有这个问题, parseArgs< $> getArgs< *> getStdGen 类型为 IO(IO()),我使用(>> = id) / code>,其类型 Monad m => m(m b) - > m b 。有没有一种方法可以避免在只有一行代码的情况下需要提取值? 解决方案

最简单的方法将与加入

  main = join $ parseArgs< $ > getArgs< *> getStdGen 

就个人而言,我更喜欢表单

  main = join $ liftM2 parseArgs getArgs getStdGen 

其中

  join:Monad m => m(m a) - > m a 
liftM2 :: Monad m => (a - > b - > r) - > m a - > m b - > mr

或者只是使用一个do

 main = do 
args< - getArgs
gen< - getStdGen
parseArgs args gen
pre>

I have a function

parseArgs :: [String] -> StdGen -> IO ()

which selects the function to run. The main looks like

main = parseArgs <$> getArgs <*> getStdGen >>= id

The problem I have, parseArgs <$> getArgs <*> getStdGen is of type IO (IO ()), which I extract using (>>= id) which is of type Monad m => m (m b) -> m b. Is there a way to avoid requiring the "extraction" of the value while having just a single line function?

解决方案

The easiest way would be with join:

main = join $ parseArgs <$> getArgs <*> getStdGen

Personally, I would prefer the form

main = join $ liftM2 parseArgs getArgs getStdGen

where

join   :: Monad m => m (m a) -> m a
liftM2 :: Monad m => (a -> b -> r) -> m a -> m b -> m r

Or just use a do

main = do
    args <- getArgs
    gen  <- getStdGen
    parseArgs args gen

这篇关于提取嵌套的monadic结果:m(m a) - &gt;嘛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 16:02
查看更多