[erlang-questions] Erlang math libraries

Jay Anderson horndude77@REDACTED
Fri May 18 04:30:13 CEST 2007

I decided it would be a good exercise for me to put together matrix and vector
modules. I have a question about tail recursion in erlang. I was making the
transpose function. This was my first impulse:

t(M) -> t(M, []).
t([[]|_], NewM) -> lists:reverse(NewM);
t(M, NewM) -> t([T || [_|T] <- M], [ [H || [H|_] <- M] |NewM]).

I don't particularly like the reverse at the end, but I'd rather do that and
keep it tail recursive. Then I was looking at lists.erl in stdlib and this is
the implementation of lists:map:

map(F, [H|T]) ->
    [F(H)|map(F, T)];
map(F, []) when is_function(F, 1) -> [].

This seems like it wouldn't be tail recursive. So does the erlang compiler
optimize this somehow?

Would the following be preferable for transpose?

t([[]|_]) -> [];
t(M) -> [ [H || [H|_] <- M] | t([T || [_|T] <- M]) ].


More information about the erlang-questions mailing list