chickadee » srfi-197 » nest

(nest [<placeholder>] <step> ... <initial-value>)procedure

nest is similar to chain, but sequences its steps in the opposite order. Unlike chain, nest literally nests expressions; as a result, it does not provide the same strict evaluation order guarantees as chain.

<placeholder> is a literal symbol; this is the placeholder symbol. If <placeholder> is not present, the placeholder symbol is _. The syntax of <step> is (<datum> ... <_> <datum> ...), where <_> is the placeholder symbol. <initial-value> is expression.

(nest (a b _) (c d _) e) ; => (a b (c d e))

A nest expression is evaluated by lexically replacing the <_> in the last <step> with <initial-value>, then replacing the <_> in the next-to-last <step> with that replacement, and so on until the <_> in the first <step> has been replaced. It is an error if the resulting final replacement is not an expression, which is then evaluated and its values are returned.

Because it produces an actual nested form, nest can build expressions that chain cannot. For example, nest can build a quoted data structure:

(nest '_ (1 2 _) (3 _ 5) (_) 4) ; => '(1 2 (3 (4) 5))

nest can also safely include special forms like if, let, lambda, or parameterize in a pipeline.

A custom placeholder can be used to safely nest nest expressions.

(nest (nest _2 '_2 (1 2 3 _2) _ 6)
      (_ 5 _2)
      4)
; => '(1 2 3 (4 5 6))