- A+

Haskell wiki has the following question:

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

I was able to come up with the following implementation:

`generate :: a -> (a->Bool) -> (a->a) -> [a] generate s cnd incr = if (cnd s) then [] else 展开 ++ 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) `

Ofcourse `map (ioFn) (generate s cnd incr)`

results in `[IO ()]`

. I am not sure how this can be transformed to `IO ()`

I need something like `foldl`

but the one that works with `[IO ()]`

instead of `[a]`

.

The function you are looking for is:

**sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()**

But we can actually just replace `map`

, such that we do not need an extra function. You can use ** mapM_ :: Monad m => (a -> m b) -> [a] -> m ()** here instead of

`map`

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

This thus will apply the function `ioFun`

on all elements of `generate s cnd incr`

, and eventually return the unit `()`

.