[erlang-questions] Is this code tail recursive ?

Hynek Vychodil hynek@REDACTED
Thu Feb 10 13:07:56 CET 2011


On Mon, Feb 7, 2011 at 4:21 PM, Robert Virding
<robert.virding@REDACTED> wrote:
> Yes, it is tail-recursive in gather_files/1/2. Though it will probably not return what you want as the first clause of gather_files/2:
>
> gather_files([], [Acc]) -> Acc;
>
> will only succeed if there is ONE element (file) in the accumulator in which case it will return the file, otherwise it will crash. Did you intend
>
> gather_files([], Acc) -> Acc; ?
>
> Robert
>

No, it works well if it is called gether_files([{path,Dir}]) because
in this case it will have only one element in Acc due

    directory ->
        gather_files(Files, [gather_directory_files(F) | Acc ]);

I would rewrite it as

....
gather_files([],Acc) -> Acc;
...
    directory ->
        gather_files(Files, gather_directory_files(F, Acc));
...
gather_directory_files(D, Tail) ->
   filelib:fold_files( D, ".*", true, fun(X,Acc) ->
                                      [X|Acc]
                             end,
                     Tail).


> ----- "Mihai Balea" <mihai@REDACTED> wrote:
>
>> On Feb 6, 2011, at 6:08 PM, Radu Brumariu wrote:
>>
>> > gather_files([]) -> [];
>> > gather_files(F) ->
>> >    gather_files(F,[]).
>> > gather_files([],[Acc]) -> Acc;
>> > gather_files([{path,F}|Files],Acc) ->
>> >    io:format("Processing path ~p~n",[F]),
>> >    {ok, T} = file:read_file_info(F),
>> >    case T#file_info.type
>> >    of
>> >     regular ->
>> >         gather_files(Files, [F | Acc]);
>> >     directory ->
>> >         gather_files(Files, [gather_directory_files(F) | Acc ]);
>> >     _ ->
>> >         gather_files(Files, Acc)
>> >    end.
>> >
>> > gather_directory_files(D) ->
>> >    filelib:fold_files( D, ".*", true, fun(X,Acc) ->
>> >                                     [X|Acc]
>> >                            end,
>> >                    []).
>> >
>>
>> Looks tail recursive to me, although looking at the way you build up
>> your result, it might not be what you expect :)
>> Not sure what you expect though, so I cannot comment on that.
>>
>> Hope this helps,
>> Mihai
>> ________________________________________________________________
>> erlang-questions (at) erlang.org mailing list.
>> See http://www.erlang.org/faq.html
>> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
> --
> Robert Virding, Erlang Solutions Ltd.
>
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
>



-- 
--Hynek (Pichi) Vychodil

Analyze your data in minutes. Share your insights instantly. Thrill
your boss.  Be a data hero!
Try GoodData now for free: www.gooddata.com


More information about the erlang-questions mailing list