Using vtx[] instead of vtx
The reason to use 1. is readability. There is no difference in function or performance.
Simply because of established convention, most people when they see f[vtx]
, they assume that vtx
is "a variable", i.e. if it is evaluated twice, it will give the same result both times. vtx[]
looks like "a function call", so people will expect that a second evaluation may give a different result (as it is the case here).
Technically speaking, Mathematica has neither functions nor variables (it is a term rewriting system), but it is still useful to think of code in these terms.
Besides the reasons mentioned by @Szabolcs, there's a second advantage of the first method: It is easier to control when evaluation happens.
- With
vtx := …
, evaluation happens as soon as the symbol appears (as long as you're not using stuff withHold
attributes/Unevaluated
) - With
vtx[] := …
, you can pass aroundvtx
without having to worry about evaluation. Only when you add the square brackets is the code actually evaluated.
Example
To see why this can be useful, consider the following example: We want to create a function drawTrees
that creates small plots of 5 randomly sample trees, where we can specify how to sample them.
With vtx[] := …
, this would look like this:
drawTrees[gen_]:= Table[
Graph[gen[], ImageSize->100],
5
]
vtx[] := Table[i <-> RandomInteger[{0, i - 1}], {i, 1, 20}];
vtx2[] := Flatten@Table[{i <-> i - 1, i <-> f[i]}, {i, 20}];
drawTrees[vtx]
drawTrees[vtx2]
With vtx := …
, we need to use a HoldFirst
attribute:
drawTrees[gen_]:= Table[
Graph[gen, ImageSize->100],
5
]
Attributes[drawTrees] = {HoldFirst};
vtx := Table[i <-> RandomInteger[{0, i - 1}], {i, 1, 20}];
vtx2 := Flatten@Table[{i <-> i - 1, i <-> f[i]}, {i, 20}];
drawTrees[vtx]
(* same as above *)
drawTrees[vtx2]
(* same as above *)
Of course, the fix is simple in this case. But if you need to pass around the generator a lot and store it somewhere, it will become even more messy with the vtx := …
approach.