[erlang-questions] Mapping over 2+ lists/variables?

Richard A. O'Keefe ok@REDACTED
Thu Jul 24 03:33:23 CEST 2008

On 24 Jul 2008, at 4:24 am, Circular Function wrote:
> 38> lists:map(fun(X,Y) -> X+Y end,[1,2],[3,4]).
> ** exception error: undefined function lists:map/3
> 39>

So write your own:

	map(F, [A|As], [B|Bs]) -> [F(A,B) | map(F, As, Bs)];
	map(_, [],     []    ) -> [].

I mean, it's less typing to FIX the problem than to complain
about it!

> isnt there general map-function that map is derived from that I can  
> use?

No.  The code for map is just

	map(F, [A|As]) -> [F(A) | map(F, As)];
	map(_, []    ) -> [].

Erlang is open source, and if you have it, you also have all the
source code, including <ERLHOME>/lib/stdlib/src/lists.erl,
so you can easily see for yourself how this and other functions

> what about listcomprehensions?
> 44> [X+Y || X,Y <- lists:seq(1,10),lists:seq(1,10)].
> * 1: variable 'X' is unbound

Indeed it is.  Like Haskell (yah boo chiz) Erlang list
comprehensions do not permit "parallel" iteration, only
"nested" iteration.  This is one of the things I like
about Clean.  Hmm.  List comprehension uses '||', I've
just thought of a use for '&&'...

The Haskell approach would be

	[x + y | (x,y) <- zip [1..10] [1..10]]

or better still,
	zipWith (+) [1..10] [1..10]

The Erlang equivalent of using zip here is, well,
using zip:

	[X + Y | {X,Y} <- lists:zip(lists:seq(1,10),

Personally I loathe this.  Some Haskell compilers
(notably GHC and I think YHC) are smart enough to do
'deforestation' and NOT really build a list of pairs.
The Erlang compiler is not.  (For one thing, 'zip'
is part of the Haskell 'standard prelude'; it really
counts as part of the language.  'zip' is not in the
erlang: module, and not even in any module in the
kernel application.  It's in the lists module, which
is in the stdlib application.  So the compiler is not
going to make any assumptions at all about what it does.)
I would prefer to see
	[X +  Y || X <- lists:seq(1,10)
                 && Y <- lists:seq(1,10)]

Sadly, that's not legal now.

If stupidity were a crime, who'd 'scape hanging?

More information about the erlang-questions mailing list