键盘快捷键

使用 跳转章节

使用 S/ 在本书内搜索

使用 ? 显示帮助页面

使用 Esc 隐藏帮助页面

Block

Executes a sequence of expressions in an isolated, temporary scope and returns the value of the final expression.

Block is the standard way to group multiple operations into a single expression without affecting the surrounding environment. Any variables created or modified with Let inside a Block are local to that block’s scope.

Parameters

Block[expr1, expr2, ...]

The function accepts a variable number of arguments.

  • expr1, expr2, ...: A sequence of expressions to be evaluated in order.

    A trailing comma after the final expression is permitted and will be ignored.

Return Value

Returns the value of the last expression evaluated within the block. If no arguments are provided, it returns Unit[].

Errors

An error will be propagated if any of the expressions within the Block fail during evaluation.

Examples

Basic Scoping

The primary use of Block is to create a local scope for variables.

Let[x, 2];
Print[x]; (* => 2 *)

Block[
  (* x is shadowed here;
    this is a new, local variable *)
  Let[x, 10],
  Print[x] (* => 10 *)
];

(* The outer x is unaffected *)
Print[x]; (* => 2 *)

Return Value

Block evaluates all its arguments and returns the result of the last one.

Let[result, Block[
  Let[a, 5],
  Let[b, 3],
  (* This is the final expression,
    its result is returned *)
  Add[a, b]
]];
Print[result]; (* => 8 *)

(* A trailing comma is allowed *)
Block[1, 2, 3,]; (* 3 *)

Block vs. List

It is important to distinguish Block from the evaluation of expressions within a List literal. Block isolates its environment, while a List does not.

In contrast to Block, evaluating expressions within a List literal affects the current environment. Any state modifications, such as variable assignments with Let, will persist.

Let[a, 0];

(* The expressions inside the list are evaluated in the current scope.
  Let returns Unit[] (represented as ()),
  so the list contains two unit values. *)
Print[{ Let[b, 10], Let[a, Add[b, b]] }]; (* => {(), ()} *)

(* The variables a and b were created/modified in the outer scope. *)
Print[{ a, b }]; (* => {20, 10} *)