7stud
7stud

Reputation: 48599

Passing arguments to a function: a two element tuple v. two separate arguments?

In some situations, I find it is clearer if I pass two arguments to a function, e.g. two lists, rather than passing a tuple containing the two lists. Which is considered better style? Any differences in efficiency?

Thanks.

Upvotes: 2

Views: 1342

Answers (1)

Adam Lindberg
Adam Lindberg

Reputation: 16577

It is mostly a matter of taste and a well designed API. If you follow the "don't make me think" philosophy, you might end up using both ways.

Using a tuple in an argument can sometimes be confusing, because it is non-trivial and has to be documented. For example, lists:zip({List1, List2}) would be confusing because sending in the lists separately is more intuitive.

If the two lists belong together and will be passed through several functions before being used, it can be handy to group them together into one tuple so that functions on the way don't have to pass them separately. This makes the tuple almost a lightweight "object" that you can pass around. Functions that understand the "object" can either look into it, or split it up and call deeper functions that operate on the elements separately.

Sometimes the two lists are so related to each other that it just makes more sense to always keep them in a tuple:

aquire(Caller, {[Item|Free], Busy}) -> {Free, [{Caller, Item}|Busy]};
aquire(_Caller, {[], _Busy})        -> {error, no_free_items}.

Upvotes: 4

Related Questions