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

前端 未结 4 1224
旧时难觅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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 23:34

    As you mentioned there are many things to consider and a detailed discussion is possible. But here are some rules of thumb that I apply the majority of the time:

    Module[{x}, ...] is the safest and may be needed if either

    1. There are existing definitions for x that you want to avoid breaking during the evaluation of the Module, or

    2. There is existing code that relies on x being undefined (for example code like Integrate[..., x]).

    Module is also the only choice for creating and returning a new symbol. In particular, Module is sometimes needed in advanced Dynamic programming for this reason.

    If you are confident there aren't important existing definitions for x or any code relying on it being undefined, then Block[{x}, ...] is often faster. (Note that, in a project entirely coded by you, being confident of these conditions is a reasonable "encapsulation" standard that you may wish to enforce anyway, and so Block is often a sound choice in these situations.)

    With[{x = ...}, expr] is the only scoping construct that injects the value of x inside Hold[...]. This is useful and important. With can be either faster or slower than Block depending on expr and the particular evaluation path that is taken. With is less flexible, however, since you can't change the definition of x inside expr.

提交回复
热议问题