Jan 21, 2008
Img_5845-srgb_small Jared Haworth 2 posts

Topic: Programming Erlang / Understanding mylists:map/2

I guess it’s a side effect of coming from Ruby, where I’m accustomed to having to flatten and compact my arrays all the time; putting [1|[2,3,4,5]] into the Eshell gave me back [1,2,3,4,5], in harmony with your examples above.

I think the fact that the functions above return all their output in a list is probably what threw me off track, it looked like the return would be coming back as a series of nested lists.

Thanks!

 
Jan 19, 2008
Img_5845-srgb_small Jared Haworth 2 posts

Topic: Programming Erlang / Understanding mylists:map/2

Hi everyone,

So, I’ve finally found some time to get back into the Erlang book, and I was looking over some code as a bit of a refresher.

I’m kind of confused by the output of the mylists:map/2 function (and by extension, the output of the standard lists:map/2).


map(_, [])     -> [];
map(F, [H|T])  -> [F(H)|map(F, T)].

The output of the second clause builds a new list with H being the result of F(H) and the tail is a recursive call to map(F, T).

When I try to map this out on paper, using input such as L = [1, 2, 3, 4, 5], and fun(X) -> 2*X end as the fun being passed in as the first parameter, why isn’t the output [2, [4, [6, [8, [10]]]]] ?

Is it something particular to the internals of Erlang, or my own misunderstanding of recursive functions?

Thanks!

2 posts