Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion of internal functions in Erlang

Playing with Erlang, I've got a process-looping function like:

process_loop(...A long list of parameters here...) ->
    receive
        ...Message processing logic involving the function parameters...
    end,
    process_loop(...Same long list of parameters...)
end.

It looks quite ugly, so I tried a refactoring like that:

process_loop(...A long list of parameters...) ->
    Loop = fun() ->
        receive
            ...Message processing logic...
        end,
        Loop()
    end,
    Loop()
end.

But it turned out to be incorrect, as Loop variable is unbound inside the Loop function. So, I've arranged a workaround:

process_loop(...A long list of parameters...) ->
    Loop = fun(Next) ->
        receive
            ...Message processing logic...
        end,
        Next(Next)
    end,
    Loop(Loop)
end.

I have two questions:

  1. Is there a way to achieve the idea of snippet #2, but without such "Next(Next)" workarounds?

  2. Do snippets #1 and #3 differ significantly in terms of performance, or they're equivalent?

like image 985
Vanya Avatar asked Dec 31 '25 22:12

Vanya


2 Answers

  1. No. Unfortunately anonymous function are just that. Anonymous, unless you give them a name.

  2. Snippet #3 is a little bit more expensive. Given that you do pattern matching on messages in the body, I wouldn't worry about it. Optimise for readability in this case. The difference is a very small constant factor.

like image 143
Daniel Luna Avatar answered Jan 05 '26 04:01

Daniel Luna


  1. You might use tuples/records as named parameters instead of passing lots of parameters. You can just reuse the single parameter that the function is going to take.

  2. I guess (but I' not sure) that this syntax isn't supported by proper tail-recursion. If you refactor to use a single parameter I think that you will be again on the right track.

like image 24
Papipo Avatar answered Jan 05 '26 06:01

Papipo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!