Mathematica 模块与使用或块 - 指南,使用经验法则? [英] Mathematica Module versus With or Block - Guideline, rule of thumb for usage?
问题描述
Leonid 在他的书的第四章中写道:...模块、块和与.这些结构在 Mathematica Book 和 Mathematica Help 中有详细解释,所以我在这里只说几句...."
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 a few words about them here. ..."
从我读到的(能够找到的)来看,我仍然一无所知.对于打包的函数,我(简单地)使用 Module,因为它可以工作并且我知道它的构造.虽然它可能不是最好的选择.我并不完全清楚(从文档中)何时、何地或为什么使用 With(或 Block).
From what I have read ( been able to find ) I am still in the dark. For packaged functions I ( simply ) use Module, because it works and I know the construct. It may not be the best choice though. It is not entirely clear to me ( from the documentation ) when, where or why to use With ( or Block ).
推荐答案
Block
和 Module
之间更实际的区别可以在这里看到:
A more practical difference between Block
and Module
can be seen here:
Module[{x}, x]
Block[{x}, x]
(*
-> x$1979
x
*)
所以如果你想返回例如x
,你可以使用Block
.例如,
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).
另一个用途是类似于 Block[{$RecursionLimit = 1000},...]
,它临时改变了 $RecursionLimit
(Module
不会起作用,因为它重命名了 $RecursionLimit
).
Another use is something like Block[{$RecursionLimit = 1000},...]
, which temporarily changes $RecursionLimit
(Module
would not have worked as it renames $RecursionLimit
).
还可以使用 Block
来阻止对某事的评估,例如
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}
*)
即,它返回 Sin[0.5]
仅在 Block
完成执行后才计算.这是因为 Block
中的 Sin
只是一个符号,而不是正弦函数.你甚至可以做类似的事情
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]
*)
(使用 Trace
来查看它是如何工作的).所以你也可以使用 Block
在本地重新定义内置函数:
(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
*)
这篇关于Mathematica 模块与使用或块 - 指南,使用经验法则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!