Haskell:[IO()]到IO()

nmd*_*mdr 6 haskell io-monad

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)
Run Code Online (Sandbox Code Playgroud)

当然map (ioFn) (generate s cnd incr)导致[IO ()].我不确定如何将其转化为IO () 我需要的东西,foldl但是需要的东西,[IO ()]而不是[a].

Wil*_*sem 10

您正在寻找的功能是:

sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
Run Code Online (Sandbox Code Playgroud)

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

for :: a -> (a -> Bool) -> (a -> a) -> (a -> IO ()) -> IO()
for s cnd incr ioFn = mapM_ ioFn (generate s cnd incr)
Run Code Online (Sandbox Code Playgroud)

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