[erlang-questions] Representation of a map in bytecode?

ok ok@REDACTED
Wed Sep 19 00:48:29 CEST 2007


On 18 Sep 2007, at 7:47 pm, Hugh Perkins wrote:

> On 9/18/07, David King <dking@REDACTED> wrote:
>>> The evaluation order [of lists:map/1] is implementation dependent.
>>
>
> Ok so, in theory, so we dont care about side-effects in a  
> parallelized map?

Whyever would you say THAT?  No, the conclusion is that if you care
about side effects, you don't use lists:map/1, you use your own code
and *document* what order things must be done.

And if you map a function with side effects down a list, you had
*better* care about the order, even if only to prove that in this
case the order does not matter.

> Ermmm..... random question, if lists:map is implementation dependent,
> I guess this means that, in standard erlang, the test results on one
> architecture are not portable to other architectures?  Is this a good
> thing?

Common Lisp and Scheme say exactly the same thing: the order in which
user functions are applied in the supplied list processing functions is
not defined.  Common Lisp has a fairly large section saying what such
a user-supplied function must not do.

Here are two possible implementations of map:

	map(F, [H|T]) ->
	    H1 = F(H),
             T1 = map(F, T),
             [H1|T1];
	map(F, []) when is_function(F, 1) ->
	    [].

is just the existing lists:map/2 written in a funny way, while

	map(F, [H|T]) ->
	    T1 = map(F, T),
             H1 = F(H),
             [H1|T1];
	map(F, []) when is_function(F, 1) ->
	    [].

For pure functions F (that is, for the application map/2 was designed  
for)
you get the same result either way.  If now you write

	map(F, [H|T]) ->
	    [F(H) | map(F, T)];
	map(F, []) when is_function(F, 1) ->
	    [].

the version you get depends on what the compiler does with [E1 | E2].
Which was defined in one Erlang specification to be left to right, but
it is the kind of thing people can change their minds about.

Anyone who cares about the order of operations really should be using
the sequencing operator (,) to make it absolutely explicit and
unmistakable.

I would be a bit wary about list comprehensions too...  Do you know what
the compiler does with them?  Are you sure it will still be doing the
same thing in 10 years?  (I can think of a fairly obvious strategy
which, for equally obvious plausible reasons, might evaluate parts of a
comprehension left to right and other parts right to left.)




More information about the erlang-questions mailing list