RosettaCodeData/Task/Search-a-list/CLU/search-a-list.clu
2023-07-01 13:44:08 -04:00

32 lines
1.1 KiB
Text

% 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