Erlang/OTP Forums

Author Message

<  Erlang  ~  a stdlib function for collecting results from N func calls?

matpalm
Posted: Sat Feb 23, 2008 2:40 am Reply with quote
Joined: 23 Feb 2008 Posts: 5
hi!

i'm not sure if 'collect' is the right term but i often find myself wanting to collect a list of N function results.

eg. consider the snippet of code below, in particular my 'collect' function implemented with a fold.

is there a stdlib function for this style of operation?

maybe it's just that i'm not approaching the problem in the erlang way...

cheers,
mat

Code:

-module(test).
-export([main/0,job/2]).

main() ->
    NumberChildren = 10,
   
    Children = collect(
      fun() ->
         Self = self(),
         spawn(test,job,[Self,randomVector(10)])           
      end, NumberChildren),   
   
    io:format("~w\n",[Children]),

   Results = collect(
      fun() ->
         receive
            Result -> Result
         end
      end, NumberChildren),
    io:format("~w\n",[Results]).

randomVector(N) ->
    collect(fun() -> random:uniform(10) end, N).
               
collect(Fun, N) ->
   lists:foldl(
      fun(_,List) -> [Fun()|List] end,
      [], lists:seq(1,N)
   ).
   
job(Supervisor, Data) ->
    Sum = lists:sum(Data),
    io:format("~w : sum of ~w is ~w\n",[self(), Data, Sum]),
    Supervisor ! Sum.


Last edited by matpalm on Sat Feb 23, 2008 3:00 am; edited 1 time in total
View user's profile Send private message
bluefly
Posted: Sat Feb 23, 2008 8:37 am Reply with quote
User Joined: 06 Jan 2008 Posts: 10
Have you tried rpc:parallel_eval and rpc:pmap?
View user's profile Send private message
matpalm
Posted: Sat Feb 23, 2008 10:29 pm Reply with quote
Joined: 23 Feb 2008 Posts: 5
thanks for that bluefly.
from poking around http://www.erlang.org/doc/ hadn't seen any of the rpc stuff.
now have http://erlang.org/doc/man/rpc.html bookmarked.
cheers!
View user's profile Send private message

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum