Next: , Previous: Accumulations, Up: Gathering Clauses

2.3.3 Finders

A finder is a clause whose value is an expression that meets some condition.

— Clause: finding expr such-that test &optionally into var on-failure failure-value

If test (which is an expression) ever evaluates to non-nil, the loop is terminated, the epilogue code is run and the value of expr is returned. Otherwise, nil (or failure-value, if provided) is returned. If var is provided, it will have either the non-nil value of expr or failure-value when the epilogue code is run.

As a special case, if the test expression is a sharp-quoted function, then it is applied to expr instead of being simply evaluated. E.g. (finding x such-that #'evenp) is equivalent to (finding x such-that (evenp x)).

On-failure is a misnomer. Because it is always evaluated, it behaves more like the default third argument to the gethash function. As a result, on-failure (error "Not found") makes no sense. Instead, the clauses leave or thereis can be used in conjunction with finally as follows:

       (iter (for x in '(1 2 3))
             (if (evenp x) (leave x))
             (finally (error "not found")))

This clause may appear multiple times when all defaults are identical. It can also be used together with either always/never or thereis if their defaults match. More specifically, on-failure nil is compatible with thereis, while on-failure t is compatible with always and never clauses.

       (iter (for i in '(7 -4 2 -3))
             (if (plusp i)
       	   (finding i such-that (evenp i))
                 (finding (- i) such-that (oddp i))))

— Clause: finding expr maximizing m-expr &optional into var
— Clause: finding expr minimizing m-expr &optional into var

Computes the extremum (maximum or minimum) value of m-expr over all iterations, and returns the value of expr corresponding to the extremum. expr is evaluated inside the loop at the time the new extremum is established. If m-expr is never evaluated (due to, for example, being embedded in a conditional clause), then the returned value depends on the type, if any, of expr (or var, if one is supplied). If there is no type, the returned value will be \nil; if the type is numeric, the returned value will be zero.

For these two clauses, var may be a list of two symbols; in that case, the first is used to record expr and the second, m-expr.

As with finding... such-that, if m-expr is a sharp-quoted function, then it is called on expr instead of being evaluated.