# Simple list transform

Erik Johansson happi@REDACTED
Fri May 18 00:21:34 CEST 2001

```
> Gidday,
>
> Its the simpliest things that give me trouble in Erlang. I am trying to
work
> out how I can transform the list [0,1,2,3,4] into the list
> [{0,Y},{1,Y},{2,Y},{3,Y},{4,Y}].
>
> I've looked at map, but the function only takes one argument (an array
> element) and I can't see a way to wedge another one in. I think I'm
correct
> in assuming that unless I pass a variable as an argument to a fun it
doesn't
> have it in its scope , so I can't do this:
>
> Y = "really cool id",
> IdList = [0,1,2,3,4] ,
> map(fun(Num) -> {Num, Y} end,IdList).

But you can, as long as Y is bound in the scope where the fun is created.
(You want to use lists:map though):

-module(m).
-export([t/0]).

t() ->
Y = "really cool id",
IdList = [0,1,2,3,4] ,
lists:map(fun(Num) -> {Num, Y} end,IdList).

===
Testrun:

Erlang (BEAM) emulator version 5.1 [source] [hipe]

Eshell V5.1  (abort with ^G)
1> c(m).
{ok,m}
2> m:t().
[{0,"really cool id"},
{1,"really cool id"},
{2,"really cool id"},
{3,"really cool id"},
{4,"really cool id"}]
3>

> I know I could do it the traditional way and use two functions to iterate
> the list, slicing off one item at a time and accumulating the result. Is
> there an easier/nicer way?

Well, as you have seen there are. There are other ways like:
-module(m).
-export([y/1,t/0]).
y(N) -> {N,"really cool id"}.
t() ->
IdList = [0,1,2,3,4] ,
lists:map(fun y/1,IdList).

===
testrun:
8> c(m).
{ok,m}
9> m:t().
[{0,"really cool id"},
{1,"really cool id"},
{2,"really cool id"},
{3,"really cool id"},
{4,"really cool id"}]

(I hope I didn't spoil some homework now...
but since you almost had it anyway I guess no harm is done)

/Erik

```