Search a list: Difference between revisions

Added Io entry.
(→‎{{header|Perl 6}}: add solution using search hash)
(Added Io entry.)
Line 1,394:
main(list_1 = [])
runerr(500,"Washington") from line 7 in haystack.icn</pre>
 
=={{header|Io}}==
 
List has a <code>indexOf</code> method which does not raise an exception on lookup failure but returns <code>nil</code> therefore I extend List with a <code>firstIndex</code> method that does raise an exception. I also create a <code>lastIndex</code> extension that finds the last index of a matching object by iterating in reverse over the list. Note that all these methods find any object not just strings.
 
<lang Io>NotFound := Exception clone
List firstIndex := method(obj,
indexOf(obj) ifNil(NotFound raise)
)
List lastIndex := method(obj,
reverseForeach(i,v,
if(v == obj, return i)
)
NotFound raise
)
 
haystack := list("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")
list("Washington","Bush") foreach(needle,
try(
write("firstIndex(\"",needle,"\"): ")
writeln(haystack firstIndex(needle))
)catch(NotFound,
writeln(needle," is not in haystack")
)pass
try(
write("lastIndex(\"",needle,"\"): ")
writeln(haystack lastIndex(needle))
)catch(NotFound,
writeln(needle," is not in haystack")
)pass
)</lang>
{{out}}
<pre>firstIndex("Washington"): Washington is not in haystack
lastIndex("Washington"): Washington is not in haystack
firstIndex("Bush"): 4
lastIndex("Bush"): 7</pre>
 
=={{header|J}}==
Anonymous user