With

With[{x=x0,y=y0,},expr]

specifies that all occurrences of the symbols x, y, in expr should be replaced by x0, y0, .

Details

  • With allows you to define local constants.
  • With replaces symbols in expr only when they do not occur as local variables inside scoping constructs.
  • You can use With[{vars},body/;cond] as the righthand side of a transformation rule with a condition attached.
  • With has attribute HoldAll.
  • With constructs can be nested in any way, with inner variables being renamed if necessary.
  • With is a scoping construct that implements readonly lexical variables.

Examples

open allclose all

Basic Examples  (3)

Evaluate an expression with x locally set to 7:

Locally set both x and y:

With works even without evaluation:

Scope  (3)

Use With to insert values into held expressions:

The variable names can be the same:

Use a constant for a value that is needed more than once:

Applications  (1)

With allows inserting values into unevaluated expressions:

Properties & Relations  (4)

Module introduces local variables to which values can be assigned:

With is faster than Module:

Block localizes values only; it does not substitute values. Module creates new symbols:

With allows substitution inside an unevaluated expression, preserving nested scopes:

Ordinary substitution does not preserve scoping:

Possible Issues  (1)

With is a scoping construct; variables are renamed in nested scopes:

Build the function from its elements to avoid the renaming:

Neat Examples  (2)

Find a zero of an arbitrary function using Newton's method:

Find a fixed point:

A version of With where the initializer is within the scope of the local variable:

Here the f inside the function definition is not inside its own scope:

Introduced in 1991
 (2.0)