I was reading some code, in particular, recipe 4.13 on unification pattern-matching in Sal Mangano's Mathematica Cookbook, and there were many instances of Modules with no variables in them, such as
Lookup[x_] := Module[{}, x /. $bindings]
i didn't understand the point. Why not just write
Lookup[x_] := x /. $bindings
? Sal uses such modules frequently, so I'm supposing there is some deep reason I'm missing, hence the question here.
Answer
For a single code statement, this is probably an overkill. If you have two or more of them, you have to group them in any case. CompoundExpression
is one obvious choice, such as
f[x_]:=
(
Print[x];
x^2
)
Instead, you could also do
f[x_]:=
Module[{},
Print[x];
x^2
]
which is what I personally often prefer. Apart from some stylistic preferences, this may make sense if you anticipate that your function will grow in the future, and some local variables will be introduced.
EDIT
There is a more important point, which was escaping me for a while but which I had on the back of my mind. I will quote Paul Graham here (ANSI Common Lisp, 1996, p.19):
When we are writing code without side effects, there is no point in defining functions with bodies of more than one expression. The value of the last expression is returned as the value of the function, but the values of any preceding expressions are thrown away.
So, what Module
really signals (since it is better recognizable than CompundExpression
) is a piece of code where side effects are present or expected. And, at least for me, having an easy way to locate such parts in code when I look at it is important, since I try to minimize their presence and, generally, they tend to produce more bugs and problems than side-effects-free code. But, even when they are really necessary, it is good to isolate and clearly mark them, so that you can see which parts of your code are and are not side-effects free.
Comments
Post a Comment