简体   繁体   中英

How can I run multiple Haskell IO actions and store the results?

I'm a Haskell beginner, so sorry in advance for the newbie question. I only have a very superficial understanding of monads.

I'm using the function insert from the module Persistent. (I've been following the tutorial here .) It inserts something in a database, and returns the ID. I can use it like this:

resultId <- insert myItem

That works fine for a single item. I can print out the resultId like this:

liftIO $ print resultId

But what if my myItem is actually a list of arbitrary length? I want to map insert over this list, which I can seem to do with:

resultIds <- mapM_ insert myItemList

but then if I try to print out the values:

liftIO $ print resultIds

I just get () . What am I doing wrong?

You are quite close: you need mapM :: Monad m => (a -> mb) -> ta -> m (tb) instead of mapM_ :: (Foldable t, Monad m) => (a -> mb) -> ta -> m ()

Like the name and the signature already suggest, both functions take a monadic function and a traversable (let us for now assume that that is a list) of a s, and it applies the monadic function to all elements and returns a monadic function that contains a traversable (list) of the results.

So if you write:

    resultIds <-  insert myItemList

The difference between mapM and mapM_ is that in the case of mapM_ (like the signature already suggests), you are not interested in the outcome, and thus it is not calculated. A reason for this could possibly be that the list is very long (and generated by-need ), and thus the list of identifiers would never fit in memory.

then resultIds will contain a list of identifiers.

The explanation about the mapM (and mapM_ ) function is a bit an oversimplification, but I think that it is usually better to first get more comfortable about monads, than getting details about monadic functions completely right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM