A better way to map a function that requires IO over a list

前端 未结 4 1468
感动是毒
感动是毒 2021-01-20 03:40

So lately I have a list of strings, and need to independently go over each one and perform some IO function.

So basically what I have is this:

4条回答
  •  伪装坚强ぢ
    2021-01-20 04:14

    sepp2k and solrize are right to recommend mapM_. But, in the spirit of teaching you to fish instead of giving you a fish, here's something you can try in the future:

    1. Try to come up with the type signature of the operation that you need. For example, in your case, you want something of type (String -> IO ()) -> [String] -> IO ().
    2. Go to the Hoogle search engine for Haskell libraries and search for that type.
    3. That one has no results, so try modifying the type a bit to make it more generic. Replace String with a to get (a -> IO ()) -> [a] -> IO (), and search for that.

    Now the third result of the second search is mapM_ :: Monad m => (a -> m b) -> [a] -> m (), which is exactly what you want. (The first answer, closeFdWith :: (Fd -> IO ()) -> Fd -> IO () is not a relevant result; the second, traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () is relevant but a bit more complicated to understand and use.)

提交回复
热议问题