Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).

Raise an exception if the needle is missing.

If there is more than one occurrence then return the smallest index to the needle.

Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.

See also
 Search a list of records

% Search an indexable, ordered collection.
% The collection needs to provide `indexes' and `fetch';
% the element type needs to provide `equal'.
search = proc [T, U: type] (haystack: T, needle: U) 
         returns (int) signals (not_found)
         where T has indexes: itertype (T) yields (int),
                     fetch: proctype (T,int) returns (U) signals (bounds),
               U has equal: proctype (U,U) returns (bool)
    for i: int in T$indexes(haystack) do
        if needle = haystack[i] then return (i) end
    end 
    signal not_found
end search
 
start_up = proc ()
    as = array[string]
    str_search = search[as,string]
 
    po: stream := stream$primary_output()
    haystack: as := as$ 
        ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
    needles: as := as$
        ["Ronald","McDonald","Bush","Obama"]
 
    for needle: string in as$elements(needles) do
        stream$puts(po, needle || ": ")
        stream$putl(po, int$unparse(str_search(haystack,needle)))
        except when not_found:
            stream$putl(po, "not found")
        end
    end
end start_up