Search a list: Difference between revisions

Line 2,856:
4 Bush
</pre>
 
=={{header|Picat}}==
Picat has built-in functions <code>find_first_of/2</code> and <code>find_last_of/2</code>. They return -1 if the needle is not found, so here they are wrapped in functions that throws exceptions in this case.
 
And Picat is 1-based.
<lang Picat>import util.
 
go =>
Haystack=["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Bush", "Charlie", "Bush", "Boz", "Zag"],
 
println("First 'Bush'"=search_list(Haystack,"Bush")),
println("Last 'Bush'"=search_list_last(Haystack,"Bush")),
 
println("All 'Bush'"=search_list_all(Haystack,"Bush")),
 
catch(WaldoIx=search_list(Haystack,"Waldo"),E,println(E)),
println("Waldo"=WaldoIx),
 
nl.
 
% Wrapping find_first_of/2 and find_last_of/2 with exceptions
search_list(Haystack,Needle) = Ix =>
Ix = find_first_of(Haystack,Needle),
if Ix < 0 then
throw $error(search_list(Needle),not_found)
end.
 
search_list_last(Haystack,Needle) = Ix =>
Ix = find_last_of(Haystack,Needle),
if Ix < 0 then
throw $error(search_list_last(Needle),not_found)
end.
 
% Find all indices
search_list_all(Haystack,Needle) = Ixs =>
Ixs = [Ix : {W,Ix} in zip(Haystack,1..Haystack.len), W == Needle],
if Ixs == [] then
throw $error(search_list_all(Needle),not_found)
end.</lang>
 
{{out}}
<pre>First 'Bush' = 5
Last 'Bush' = 9
All 'Bush' = [5,7,9]
error(search_list(Waldo),not_found)
Waldo = _3590</pre>
 
 
=={{header|PicoLisp}}==
495

edits