Haskell: [IO()] 到 IO()

Haskell: [IO ()] to IO ()

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

您要查找的函数是:

<b><a href="https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:sequence_" rel="noreferrer">sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()</a></b>

但实际上我们可以只替换map,这样我们就不需要额外的功能了。这里可以用mapM_ :: Monad m => (a -> m b) -> [a] -> m ()代替map,所以:

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

这将在 generate s cnd incr 的所有元素上应用函数 ioFun,最终 return 单元 ()