Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: [IO ()] to IO ()

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 [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)

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

like image 757
coder_bro Avatar asked Oct 24 '18 12:10

coder_bro


1 Answers

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 ().

like image 143
Willem Van Onsem Avatar answered Sep 29 '22 04:09

Willem Van Onsem