[erlang-questions] Tail Call Optimization and Parameter Ordering

David Mercer dmercer@REDACTED
Tue Nov 6 01:18:47 CET 2007


James Hague in "A deeper look at tail recursion in Erlang"
(http://prog21.dadgum.com/1.html) makes an interesting point about
optimizing tail recursion by keeping parameters in the same order.  This, I
think, answers a question I have had in my mind about ordering parameters in
functions in a module: is it better to put the main object at the beginning
of the parameter list or the end?

 

For example, suppose we have a module "widget" that implements some sort of
widget--whatever that is--with a couple of member functions that act on a
widget, say "change" and "query".  Is it better to implement these functions
with the widget object being the first parameter or the last?  That is,
which is better:

 

change(Widget, Arg1, Arg2) -> .

query(Widget, Arg1) -> .

 

or:

 

change(Arg1, Arg2, Widget) -> .

query(Arg1, Widget) -> .

 

Based on Hague's insight, I would say the former, with the object up front,
is better.  Why?  Because functions that are used by these functions (and
functions that use them) are likely to copy the pattern (in fact, they
should), and the Widget argument can therefore fall through in the same
position.  For example, if change/3 has to call a couple of private
functions in the module in order to perform the "change," it is likely these
functions will have different arity.  If we are in the habit of putting the
object at the end of the parameter list, then its position will have
changed.  If, on the other hand, the object is at the beginning of the
parameter list, it will always be in the same position and will cause less
stack manipulation.  Granted, this optimization only occurs in the case of
tail calls, but surely this is a good habit to be in for that case when the
tail call optimization can be used.

 

Discuss.

 

Cheers,

 

David

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20071105/ea6dab84/attachment.htm>


More information about the erlang-questions mailing list