Tail Recursion in Erlang

I'm really trying to understand tail recursion in Erlang.

I have the following eunit test:

db_write_many_test() ->
    Db = db:new(),
    Db1 = db:write(francesco, london, Db),
    Db2 = db:write(lelle, stockholm, Db1),
    ?assertEqual([{lelle, stockholm},{francesco, london}], Db2).

And here is my implementation:

-module(db) .
-include_lib("eunit/include/eunit.hrl").
-export([new/0,write/3]).

new() ->
    [].

write(Key, Value, Database) ->
    Record = {Key, Value},
    [Record|append(Database)].

append([H|T]) ->
    [H|append(T)];  
append([])  ->
    [].

I use tail recursively, and if not, how to do it?

Thanks in advance

+2
source share
1 answer

Your implementation is not tail recursion, because append must hold the head of the list when calculating the tail. In order for a function to be tail recursive, the return value must not rely on a value other than that returned from the function call.

you can rewrite it like this:

append(Acc, []) -> %% termination;
    Acc;
append(Acc, [H|T]) ->
    Acc2 = Acc ++ dosomethingto(H); %% maybe you meant this to be your write function?
    append(Acc2, T); %% tail rercursive

, . , append , .

, . , , , , .

+2

Source: https://habr.com/ru/post/1741612/


All Articles