11.5.6 Search of arrays with find-key

In Dylan, we can access multidimensional arrays as though they are linearized one-dimensional vectors by using the element generic function. Dylan provides a find-key generic function that uses element to find the index (or key) that corresponds to a desired value in a collection. Here, we rewrite find-larger-than to use find-key:

define method find-larger-than 
    (array :: <array>, value :: <integer>)
 => (result :: type-union(singleton(#f), <integer>))
  let index 
    = find-key(array, method (array-element) array-element > value end);
  index & array[index];
end method find-larger-than;

The find-key generic function searches an array, calling the function that we provided on each element. If our function ever returns true, find-key returns the linearized index of the array element containing the value. For a two-dimensional array, the linearized index is the index that would be the appropriate key of a one-dimensional array that we could construct by placing the rows of the two-dimensional array one after the other. Rows in a two-dimensional array are numbered with the first subscript, and the column within those rows is numbered by the second subscript.

If our function never returns true for any element, find-key returns false. In this example & is truly used as a control structure. If index is false, then & will return false without executing the array access. If index is true, then the array access occurs, and that is the value of the & expression, and thus the value returned from the method.