I have a list of batches(sublists) of ids and I want to iterate over this list and spawn a worker process for each id in the batch of ids. Each of these workers will query some service, get the result and send it back to the caller. In simple words I want to map a list of id
s to a list of data which I get by virtue of those id
s. I managed to achieve this but in, what I believe is, an unidiomatic way:
lists:map(fun(Ids) ->
Pids = [spawn_link(fun() ->
Result = [...] % Here goes a side-effect operation (http request)
Self ! {received_data, process(Result)}
end) || Id <- Ids],
[receive {received_data, Data} -> Data end || _Pid <- Pids],
end, JobChunks)))
In this case as you see I misuse map
function as it's designed to be side-effect free. But i don't see another option. There is foreach()
but it is used only to run side-effects and just returns ok
whereas in my case I want to preserve shape of a list too. In Haskell there is a handy type-class Traversable
with traverse
function which exactly does this: runs fmap
and in the same time allows you to perform action (effect) on each item. Is there something similar in Erlang? (like smap
perhaps?).