Anaphoric operations

Anaphoric operations provide a mechanism to refer back to themselves. This can be useful when an expression needs to be used later, as in aif, awhen, or aand. Anaphoric functions allow a function to refer back to itself recursively, without creating a named function.

See On Lisp Chapter 14 for a detailed explanation of anaphoric operations.

Anaphoric operations

aif expr body [expr body] ...
Anaphoric if: each expr is evaluated until one is true, and then the corresponding body is executed. Within the body, the anaphoric variable it refers back to the value of expr.
>(aif (> 1 2) (+ it 1) 42 (+ it 2))
44
>(aif nil (+ it 1))
nil
awhen expr [body ...]
Anaphoric when: if the expr is true, the body is executed. Within the body, the variable it refers back to the value of expr.
>(awhen (* 2 3) (+ it 1))
7
aand [arg ...]
Anaphoric and. Returns the last argument if all arguments are true, otherwise returns nil. Inside each argument the anaphoric variable it refers to the value of the previous argument. Like and, lazy evaluation is used, so evaluation stops after encountering a false argument.
>(aand 1 (+ it 2) (* it 10))
30
afn parms [body ...]
Creates an anaphoric function, which can be called recursively with the name self. This allows a recursive function to be created without assigning it a name.
>((afn (x) (if (is x 0) 1 (* 2 (self (- x 1))))) 5)
32
rfn name parms [body ...]
Creates a function with the given name. The name is only inside the scope of the rfn macro. This allows recursive functions to be created without polluting the wider scope.
>((rfn pow2 (x) (if (is x 0) 1 (* 2 (pow2 (- x 1))))) 5)
32
trav obj [function ...]
Recursive traversal. Applies each function in sequence to obj, if obj is not nil. The function can recursively call itself with a new obj with (self obj).
>(trav '(1 2 3 4) (fn (_) (prn _)) (fn (_) (self (cdr _))))
(1 2 3 4)
(2 3 4)
(3 4)
(4)

nil

Copyright 2008 Ken Shirriff.