Leonid wrote in chapter iv of his book : "... Module, Block and With. These constructs are explained in detail in Mathematica Book and Mathematica Help, so I will say just
Andrew has already provided a very comprehensive answer. I would just summarize by noting that Module
is for defining local variables that can be redefined within the scope of a function definition, while With
is for defining local constants, which can't be. You also can't define a local constant based on the definition of another local constant you have set up in the same With
statement, or have multiple symbols on the LHS of a definition. That is, the following does not work.
With[{{a,b}= OptionValue /@ {opt1,opt2} }, ...]
I tend to set up complicated function definitions with Module
enclosing a With
. I set up all the local constants I can first inside the With
, e.g. the Length
of the data passed to the function, if I need that, then other local variables as needed. The reason is that With
is a little faster of you genuinely do have constants not variables.