【问题标题】:Haskell: [IO ()] to IO ()Haskell: [IO()] 到 IO()
【发布时间】:2019-03-28 20:50:16
【问题描述】:

Haskell wiki 有以下问题:

https://en.wikibooks.org/wiki/Haskell/Higher-order_functions for :: a -> (a -> Bool) -> (a -> a) -> (a -> IO ()) -> IO () for i p f job = -- ???

我想出了以下实现:

generate :: a -> (a->Bool) -> (a->a) -> [a]
generate s cnd incr = if (cnd s) then [] else [s] ++ generate (incr s) cnd incr

-- collapse :: [IO ()] -> IO ()
-- collapse (x:xs) = x ++ collapse xs
-- does not work ^^^^^^


for::a->(a->Bool)->(a->a)->(a->IO())->IO()
for s cnd incr ioFn = map (ioFn) (generate s cnd incr)

当然map (ioFn) (generate s cnd incr) 会产生[IO ()]。我不确定如何将其转换为IO () 我需要foldl 之类的东西,但可以使用[IO ()] 而不是[a]

【问题讨论】:

  • 你可以使用sequence_
  • generate s cnd incr = takeWhile cnd (iterate incr s)
  • [IO ()][a] 的更具体实例(其中aIO ()),因此您可以将其传递给foldl。你也可以问hoogle这样的问题:hoogle.haskell.org/…
  • 除了sequence_,您可以直接使用例如将其写为折叠foldr (*>) (pure ())(或foldr (>>) (return ()))。这或多或少是sequence/sequence_/sequenceA 所做的:使用应用程序/单子序列(*>/>>)将操作连接起来,“基本情况”是一个什么都不做的操作( pure ()/return ())。

标签: haskell io-monad


【解决方案1】:

你要找的功能是:

<b>@987654321@</b>

但实际上我们可以直接替换map,这样我们就不需要额外的函数了。你可以在这里使用mapM_ :: Monad m =&gt; (a -&gt; m b) -&gt; [a] -&gt; m () 而不是map,所以:

for :: a -> (a -> Bool) -> (a -> a) -> (a -> IO ()) -> IO()
for s cnd incr ioFn = mapM_ ioFn (generate s cnd incr)

因此,这将对generate s cnd incr的所有元素应用函数ioFun,并最终返回单元()

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 2012-03-28
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多