[erlang-questions] Code generation (was NOOB)

Jay Nelson <>
Wed Sep 6 04:32:28 CEST 2006

Robert Virding wrote:
> Jay Nelson wrote:
>>> foo(X) ->
>>>    A = [do_something(E) || E <- X],    % <1>
>>>    [do_other(E) || E <- X],            % <2>
>>>    ok.
> You must clarify what you mean is the exact difference between <1> and 
> <2>? Is it the explicit assignment to A? Or that the return value is 
> never used?
I incorrectly used the example for two cases: asking Bjorn about 
compiler optimizations and demonstrating use cases for list 
comprehensions.  Ideally  the compiler should not generate a list in 
either case, since it knows in both cases the result is never used.

The case of <1> is possibly a programmer error, so I would expect a 
warning of an unused variable (sorry, let's not open that discussion 
again) since the code indicates to a human reader to expect A to be used 

In the case of <2> the intent is clear mainly to the human, but 
incidentally to the compiler, that the result is not intended to be used 
and cannot be used.  The statement clearly exists only for side effects.
> Actually, the only difference between <1> and <2> is that <1> calls 
> do_something on each element of X, while <2> calls do_other.
When I was talking about the difference between the two, I should have 
used a different example wherein A was actually referenced later.  
Change the above return value to {ok, A} for the sake of this discussion. 
> P.S. I think you should use code which builds a list when you want to 
> build a list, not for side-effects! But then again I am a purist.
I agree and am fairly pedantic about such things, but I find the foreach 
statement verbose and hard to read.  I am proposing that the clarity and 
succinctness of list comprehensions wins out.  I would throw out the 
foreach statement from the lists module and always use list 
comprehensions.  Simplicitly and brevity of a single statement with two 
clear uses, versus two separate statements.

The fact that list comprehensions always construct a list is an artifact 
of their genesis.  I agree their syntax intentionally suggests you are 
creating a list, but I still prefer the readability even only for side 
effects.  Using them and reading them clicks my mind into erlang mode.

Just my opinion, though.  I understand the other side is a reasonable 


More information about the erlang-questions mailing list