Mapping IO in Haskell

Is there a traditional way to map a function using IO? In particular, I would like to map a function that returns a random value. Using a regular map will lead to the conclusion of type ([IO b]), but to unpack the values โ€‹โ€‹in the list from IO I need something like (IO [b]). So I wrote ...

mapIO :: (a -> IO b) -> [a] -> [b] -> IO [b] mapIO f [] acc = do return acc mapIO f (x:xs) acc = do new <- fx mapIO f xs (new:acc) 

... which works great. But there seems to be a solution for this built in to Haskell. For example, a usage example:

 getPercent :: Int -> IO Bool getPercent x = do y <- getStdRandom (randomR (1,100)) return $ y < x mapIO (\f -> getPercent 50) [0..10] [] 
+7
io random haskell
source share
2 answers

Standard way: through

 Control.Monad.mapM :: (Monad m) => (a -> mb) -> [a] -> m [b] 

which is implemented in terms of sequence:

 sequence :: (Monad m) => [ma] -> m [a] 
+22
source share

To add an answer to the don, take a look at the mapM_ function, which does exactly what mapM does, but discards all the results, so you get only side effects.

This is useful if you want calculations to be performed (e.g., IO calculations), but not interested in the result (e.g., file cancellation).

Also see forM and forM_ .

+9
source share

All Articles