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

 
link lists
 
procedure main()              
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]  # the haystack
every needle := !["Bush","Washington"] do {                                         # the needles
 
   if i := lindex(haystack,needle) then {                                           # first occurrence 
      write("needle=",needle, " is at position ",i," in haystack.")                
 
      if i <:= last(lindex,[haystack,needle]) then                                  # last occurrence 
         write("needle=",needle, " is at last position ",i," in haystack.")         
      }
   else {
      write("needle=",needle, " is not in haystack.")
      runerr(500,needle)        # throw an error
      }
   }
 
end
 
procedure last(p,arglist)               #: return the last generation of p(arglist) or fail
local i
every i := p!arglist
return \i
end