Mathematica Module versus With or Block - Guideline, rule of thumb for usage?

前端 未结 4 1232
旧时难觅i
旧时难觅i 2021-01-29 22:45

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

4条回答
  •  滥情空心
    2021-01-29 23:50

    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.

提交回复
热议问题