[erlang-questions] Charset conversion / stylistic question.

Thomas Lindgren thomasl_erlang@REDACTED
Wed Apr 18 01:13:42 CEST 2007


--- Ulf Wiger <ulf@REDACTED> wrote:

> Hi Tim,
> 
> There is a problem in your map/2 function.
> The call to list_to_binary/1 makes it non-tail
> recursive,
> so the recursion cannot reuse the stack frame.

Actually, plain old map/2 isn't tail recursive
either*. But, as you say, the repeated calls to
list_to_binary can be replaced by a single one after
returning, which potentially saves a lot of binary
copying.

The cost of binary copying alone for this code is
basically O(N^2) for N list elements (unless it's
getting too late for me) so it can get problematic.
Ulf's new code avoids that.

> Also, you will get many unnecessary calls to
> list_to_binary()
> (one per iteration).
> 
> One could instead write like this
> 
> map(F, Bin) ->
>   list_to_binary(map_1(F, Bin))
> 
> map_1(F, <<A:8, Rest/binary>>) ->
> [F(A)|map_1(Rest)];
> map_1(_, <<>>) -> [].

* (A clever implementation could turn map/2 into tail
recursion, but as far as I know none today do.)

Best,
Thomas


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 



More information about the erlang-questions mailing list