Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang using for() vs lists:foreach

Tags:

erlang

The following sample code is from Joe Armstrong's Programming Erlang book:

max(N) ->
  Max = erlang:system_info(process_list),
  io:format("Maximum allowed processes:~p~n",[Max]),
  statistics(runtime),
  statistics(wall_clock),
  L = for(1, N, fun() -> spawn(fun() -> wait() end) end),
  {_, Time1} = statistics(runtime),
  {_, Time2} = statistics(wall_clock),
  lists:foreach(fun(Pid) -> Pid ! die end, L),
  U1 = Time1 * 1000 / N,
  U2 = Time2 * 1000 / N,
  io:format("Process spawn time=~p (~p) microseconds~n",
    [U1, U2]).

My question is dealing with Erlang fundamentals. It looks like Joe used for() to spawn processes, followed by a lists:foreach to die them. Is there a reason to use one over the other? Why not use for() again to iterate over the the spawned process list and send them a die message? Is there an efficiency optimization here that I'm missing?

like image 629
randombits Avatar asked Jul 11 '11 21:07

randombits


People also ask

How do I check if a list is empty in Erlang?

This is the function that is called: set_viewer_values(Value, ViewerSet) -> if ViewerSet /= empty_set -> lists:map(fun(ViewerPid) -> ViewerPid ! {self(), set_value, Value} end, ViewerSet) end.

Is Erlang a list?

The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.

Does Erlang have different types?

Erlang is a dynamically typed language. Still, it comes with a notation for declaring sets of Erlang terms to form a particular type. This effectively forms specific subtypes of the set of all Erlang terms.


1 Answers

lists:foreach saves you the trouble of determining the length of the list ahead of time, and of specifying it as an argument. The for invocation needs to know how long to make the list, so it's necessary. for() is usually used as a last resort when there's nothing more appropriate.

like image 114
nmichaels Avatar answered Jan 01 '23 09:01

nmichaels