Block
Block[{x,y,…},expr]
specifies that expr is to be evaluated with local values for the symbols x, y, ….
Block[{x=x0,…},expr]
defines initial local values for x, ….
Details
- Block allows you to set up an environment in which the values of variables can temporarily be changed.
- When you execute a block, values assigned to x, y, … are cleared. When the execution of the block is finished, the original values of these symbols are restored.
- Block affects only the values of symbols, not their names.
- Initial values specified for x, y, … are evaluated before x, y, … are cleared.
- You can use Block[{vars},body/;cond] as the right‐hand side of a transformation rule with a condition attached.
- Block has attribute HoldAll.
- Block implements dynamic scoping of variables.
- Block is automatically used to localize values of iterators in iteration constructs such as Do, Sum, and Table.
Background & Context
- Block is a scoping construct that localizes symbols by separating the values they assume inside the block from values they might assume outside. Block implements dynamic scoping of variables, meaning the name of the local symbol stays the same. When the local symbol has a value, this value is used; otherwise, the value in the enclosing function is used (and so forth). Block localizes values only and does not substitute them.
- In contrast, Module does lexical scoping, meaning a new, unique copy of the variable is created in each invocation that is used nowhere else in any enclosing function or subsequent call to the Module.
- Block is typically faster than Module, so use of Block may result in faster evaluation when functions with scoped variables are called many times. Block is automatically used to localize values of iterators in constructs such as Do, Sum, Product, and Table. Block may be nested.
- With is another scoping construct that allows definition of local constants. It implements read‐only lexical variables and replaces symbols only when they do not occur as local variables inside scoping constructs. Like Block, With is faster than Module. While ordinary substitution does not preserve scoping, With allows substitution inside an unevaluated expression, thus preserving nested scopes.
- Multiple expressions inside (or outside) a Block construct are grouped together using CompoundExpression.
Examples
open allclose allBasic Examples (1)
Scope (2)
Applications (2)
Perform a deeply recursive calculation:
The default setting of $RecursionLimit is too low for this calculation:
Text
Wolfram Research (1988), Block, Wolfram Language function, https://reference.wolfram.com/language/ref/Block.html.
CMS
Wolfram Language. 1988. "Block." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/Block.html.
APA
Wolfram Language. (1988). Block. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Block.html