How to resolve the algorithm Search a list step by step in the CLU programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Search a list step by step in the CLU programming language
Table of Contents
Problem Statement
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. Return the largest index to a needle that has multiple occurrences in the haystack.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Search a list step by step in the CLU programming language
Source code in the clu programming language
% 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
You may also check:How to resolve the algorithm Higher-order functions step by step in the Nim programming language
You may also check:How to resolve the algorithm Anagrams step by step in the REXX programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the F# programming language
You may also check:How to resolve the algorithm Approximate equality step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Filter step by step in the Wren programming language