11.5.5 Search of arrays with for and block

Suppose that you wanted to search a two-dimensional array, and to return the first number greater than a given value.

define method find-larger-than 
    (2d-array :: <array>, value :: <integer>)
 => (result :: type-union(singleton(#f), <integer>))
  let first-dimension = dimension(2d-array, 0);
  let second-dimension = dimension(2d-array, 1);
  block (return)
    for (i from 0 below first-dimension)
      for (j from 0 below second-dimension)
        if (2d-array[i, j] > value)
          return(2d-array[i, j]);
        end if;
      end for;
    end for;
    #f;
  end block;
end method find-larger-than;

In the preceding example, the block statement binds the variable return to a nonlocal exit procedure. If this exit procedure is called while the block is in effect, it will return immediately from the block statement, using any provided arguments as return values. Thus, if an element of 2d-array is greater than value, then this element will be returned immediately from the block, and thus from the method. Array elements can be accessed with the square-bracket syntax, or with the function aref. (For more information about referencing elements of an array, see Section 12.1.3, page 164.) If the entire array is searched, and no element is found that is greater than value, then the for loops exit normally and the block statement returns the last value in the block body, which in this case is false. We use the type-union type-generating function to create a type that permits either false or an integer to be returned from this method.