Search code examples
erlanggeneratorlist-comprehension

Understanding Erlang List Comprehension Generators


Given this function:

pretty_print(Folders, Depth) ->
    
        {CurrrentFolder, ListSubfolders} = Folders,
        SignTemp = lists:duplicate(Depth, "-"),
        case Depth of
            0 -> Sign = SignTemp;
            _ -> Sign = "|" ++ SignTemp
        end,
    
        io:format("~s~s~n", [Sign, CurrrentFolder]),
        
        [pretty_print(Subfolder, Depth+1)|| Subfolder <- ListSubfolders].

What happens to a recursive function in Erlang when in a list comprehension the generator is null or empty?

So when the variable is empty, the function won't call itself?

Won't it produce an error on that line? There is nothing to control that an error does not occur in this line?

  {CurrrentFolder, ListSubfolders} = Folders,

For example in this piece of code, the behaviour of another variable through Depth is controlled:

case Depth of
    0 -> Sign = SignTemp;
    _ -> Sign = "|" ++ SignTemp
end,

There is something that I do not quite understand here.

What happens to the function when it reaches the last folder of a directory?


Solution

  • ¿What happens to a recursive function in Elrang when in a list comprehesion the generator is null or empty?

    When a generator in a list comprehension is empty, then the comprehension is empty. Doesn't matter if it's recursive or not.

    So when the variable is empty, the function won't call itself?

    Yes.

    There is nothing to control that an error does not occur in this line?

    No, it simply assumes the caller will give an argument which matches it (and that ListSubfolders is a list each element of which also matches it). It would be more idiomatic to match directly in the head:

    pretty_print({CurrrentFolder, ListSubfolders}, Depth) ->    
        SignTemp = lists:duplicate(Depth, "-"),
        ... %% the rest is the same