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

前端 未结 4 1226
旧时难觅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:45

    A more practical difference between Block and Module can be seen here:

    Module[{x}, x]
    Block[{x}, x]
    (*
    -> x$1979
       x
    *)
    

    So if you wish to return eg x, you can use Block. For instance,

    Plot[D[Sin[x], x], {x, 0, 10}]
    

    does not work; to make it work, one could use

    Plot[Block[{x}, D[Sin[x], x]], {x, 0, 10}]
    

    (of course this is not ideal, it is simply an example).

    Another use is something like Block[{$RecursionLimit = 1000},...], which temporarily changes $RecursionLimit (Module would not have worked as it renames $RecursionLimit).

    One can also use Block to block evaluation of something, eg

    Block[{Sin}, Sin[.5]] // Trace
    (*
    -> {Block[{Sin},Sin[0.5]],Sin[0.5],0.479426}
    *)
    

    ie, it returns Sin[0.5] which is only evaluated after the Block has finished executing. This is because Sin inside the Block is just a symbol, rather than the sine function. You could even do something like

    Block[{Sin = Cos[#/4] &}, Sin[Pi]]
    (*
    -> 1/Sqrt[2]
    *)
    

    (use Trace to see how it works). So you can use Block to locally redefine built-in functions, too:

    Block[{Plus = Times}, 3 + 2]
    (*
    -> 6
    *)
    

提交回复
热议问题