Sequential With
From Daniel Lichtblau's comment there is a new undocumented syntax for With introduced sometime after version 10.1 that allows:
With[{a = 0}, {a = a + 1}, {a = a + 1}, a]
2
Delayed With, Block, and Module
These scoping constructs support the use of := in definitions which allows one to handle unevaluated expressions.
With[{x := 2 + 2}, Trace[x]]
Block[{x := 2 + 2}, Trace[x]]
Module[{x := 2 + 2}, Trace[x]]
{2 + 2, 4}
{x, 2 + 2, 4}
{x$6064, 2 + 2, 4}
###Examples:
I find this most useful in
Withsince it inserts definitions into held expressions.
I commonly use this for in-place modification ofDownValues:a[1] = Pi; a[2] = E; With[{dv := DownValues[a]}, dv = dv /. {1 -> 3};] a[3] (* out= π *)Kuba finds it very useful for writing readable controllers definitions.
E.g.
asso = <|"nested" -> <|"key" -> <|
"spec" -> <|"a" -> 1, "b" -> 0|>
|>|>|>;
With[{
a := asso["nested", "key", "spec", "a"],
b := asso["nested", "key", "spec", "b"]
},
DynamicModule[{},
Column@{
Slider@Dynamic[a],
Slider[Dynamic[b, {Automatic, (a = b^2) &}]],
Dynamic@asso
}
]
]
The earliest Stack Exchange usage of this that I can find is a post by Szabolcsa post by Szabolcs.
I implemented a similar syntax in my listWith function which is itself an extension of With.