optimization of list comprehensions

Richard A. O'Keefe ok@REDACTED
Mon Mar 6 22:43:21 CET 2006


Serge Aleynikov <serge@REDACTED> wrote:
	If we can represent:
	
	lists:map(fun(I) -> I end,
	  lists:filter(fun(N) -> N > 10 end,
	    lists:seq(1, 20)).
	
	like this:
	
	[I || I <- lists:seq(1, 20), I > 10].
	
	Why not have a similar concise representation for the following case?
	
	lists:foldl(fun(I, Acc) -> Acc+I end, 0,
	  lists:filter(fun(N) -> N > 10 end,
	    lists:seq(1, 20)).
	
Well, we can improve that:

	lists:foldl(fun(I, Acc) -> Acc+I end, 0,
	  [I || I <- lists:seq(1, 20), I > 10])

and indeed we can improve it to

	lists:sum([I || I <- lists:seq(1, 20), I > 10])

which is pretty hard to improve on, no?  The Haskell version is
more concise:

	sum [x | x <- [1..20], x > 10]

but that's because Haskell has .. notation and doesn't use parentheses
or commas nearly as much as Erlang does.




More information about the erlang-questions mailing list