/* Search a list (Rosetta code) in Picat. http://rosettacode.org/wiki/Search_a_list """ Task 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. """ This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. main => go. /* The built-in find_first_of/2 and find_last_of/2 returns -1 if the needle is not found, so they are here wrapped into functions which throws exceptions. */ 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. 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.