Search a list: Difference between revisions

Add Ecstasy example
m (code cleanup)
(Add Ecstasy example)
 
(22 intermediate revisions by 18 users not shown)
Line 22:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V haystack = [‘Zig’, ‘Zag’, ‘Wally’, ‘Ronald’, ‘Bush’, ‘Krusty’, ‘Charlie’, ‘Bush’, ‘Bozo’]
 
L(needle) (‘Washington’, ‘Bush’)
Line 28:
print(haystack.index(needle)‘ ’needle)
X.catch ValueError
print(needle‘ is not in haystack’)</langsyntaxhighlight>
 
{{out}}
Line 37:
 
=={{header|ACL2}}==
<langsyntaxhighlight lang="lisp">(defun index-of-r (e xs i)
(cond ((endp xs) nil)
((equal e (first xs)) i)
Line 43:
 
(defun index-of (e xs)
(index-of-r e xs 0))</langsyntaxhighlight>
 
=={{header|Acornsoft Lisp}}==
 
Acornsoft Lisp does not have strings, so symbols would be used instead. That also allows us to use <code>eq</code> as the test.
 
<syntaxhighlight lang="lisp">
(defun first-index (word words (i . 0))
(loop
(until (null words)
(error word '! is! missing))
(until (eq word (car words))
i)
(setq words (cdr words))
(setq i (add1 i))))
 
(defun last-index (word words (i . 0) (last-i . nil))
(loop
(until (null words)
(cond (last-i) (t (error word '! is! missing))))
(cond ((eq word (car words))
(setq last-i i)))
(setq words (cdr words))
(setq i (add1 i))))
</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
 
INT FUNC Search(PTR ARRAY texts INT count CHAR ARRAY text)
INT i
 
FOR i=0 TO count-1
DO
IF SCompare(texts(i),text)=0 THEN
RETURN (i)
FI
OD
RETURN (-1)
 
PROC Test(PTR ARRAY texts INT count CHAR ARRAY text)
INT index
 
index=Search(texts,count,text)
IF index=-1 THEN
PrintF("""%S"" is not in haystack.%E",text)
ELSE
PrintF("""%S"" is on index %I in haystack.%E",text,index)
FI
RETURN
 
PROC Main()
PTR ARRAY texts(7)
 
texts(0)="Monday"
texts(1)="Tuesday"
texts(2)="Wednesday"
texts(3)="Thursday"
texts(4)="Friday"
texts(5)="Saturday"
texts(6)="Sunday"
 
Test(texts,7,"Monday")
Test(texts,7,"Sunday")
Test(texts,7,"Thursday")
Test(texts,7,"Weekend")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Search_a_list.png Screenshot from Atari 8-bit computer]
<pre>
"Monday" is on index 0 in haystack.
"Sunday" is on index 6 in haystack.
"Thursday" is on index 3 in haystack.
"Weekend" is not in haystack.
</pre>
 
=={{header|ActionScript}}==
===Using the built-in Error class===
<langsyntaxhighlight ActionScriptlang="actionscript">var list:Vector.<String> = Vector.<String>(["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]);
function lowIndex(listToSearch:Vector.<String>, searchString:String):int
{
Line 62 ⟶ 136:
throw new Error("String not found: " + searchString);
return index;
}</langsyntaxhighlight>
 
===Using a custom error===
In StringNotFoundError.as:
<langsyntaxhighlight ActionScriptlang="actionscript">package {
public class StringNotFoundError extends Error {
public function StringNotFoundError(message:String) {
Line 72 ⟶ 146:
}
}
}</langsyntaxhighlight>
In a separate file:
<langsyntaxhighlight ActionScriptlang="actionscript">import StringNotFoundError;
var list:Vector.<String> = Vector.<String>(["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]);
function lowIndex(listToSearch:Vector.<String>, searchString:String):int
Line 91 ⟶ 165:
return index;
}
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 135 ⟶ 209:
Check ("Washington");
Check ("Bush");
end Test_List_Index;</langsyntaxhighlight>
{{out}}
<pre>
Line 143 ⟶ 217:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
search(list l, text s)
{
Line 169 ⟶ 243:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Bush is at 4
Line 181 ⟶ 255:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68"> FORMAT hay stack := $c("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")$;
FILE needle exception; STRING ref needle;
Line 204 ⟶ 278:
end on value error: reset(needle exception)
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 216 ⟶ 290:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68"> []STRING hay stack = ("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
PROC index = ([]STRING hay stack, STRING needle)INT:(
Line 243 ⟶ 317:
FI
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 251 ⟶ 325:
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">haystack: [Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo]
 
loop [Bush Washington] 'needle [
Line 258 ⟶ 332:
if? empty? i -> panic ~"|needle| is not in haystack"
else -> print [i needle]
]</langsyntaxhighlight>
 
{{out}}
Line 266 ⟶ 340:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">haystack = Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo
needle = bush, washington
Loop, Parse, needle, `,
Line 274 ⟶ 348:
Else
MsgBox % A_LoopField . " not in haystack"
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 282 ⟶ 356:
In the following implementation we can reach the strings by numeric index with the array <code>haystack_byorder</code> (so, e.g. <code>haystack_byorder[4]</code> gives Bush), and know the "position" of the needle (if it exists) using it as string index for the array <code>haystack</code>, as example does. ('''Beware''': this method does not work when there are duplicates!)
 
<langsyntaxhighlight lang="awk">#! /usr/bin/awk -f
BEGIN {
# create the array, using the word as index...
Line 302 ⟶ 376:
print "Washington is not here";
}
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QBasic}}
 
<langsyntaxhighlight lang="qbasic">DATA foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt
DATA foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc
DATA spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar
Line 335 ⟶ 409:
EXIT DO
END IF
LOOP</langsyntaxhighlight>
 
{{out}}
Line 358 ⟶ 432:
Word to search for? (Leave blank to exit)
</pre>
 
==={{header|BASIC256}}===
{{trans|Yabasic}}
<syntaxhighlight lang="freebasic">list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
n$ = explode(list$, ",")
t = 0 : j = 0
 
input string "Enter string to search: ", linea$
 
for i = 0 to n$[?]-1
if linea$ = n$[i] then
if not t then print "First index for "; linea$; ": "; i
t = i
j += 1
end if
next
 
if t = 0 then
print "String not found in list"
else
if j > 1 then print "Last index for "; linea$; ": "; t
end if</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> DIM haystack$(27)
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
\ "hotel","india","juliet","kilo","lima","mike","needle", \
\ "november","oscar","papa","quebec","romeo","sierra","tango", \
\ "needle","uniform","victor","whisky","x-ray","yankee","zulu"
needle$ = "needle"
maxindex% = DIM(haystack$(), 1)
FOR index% = 0 TO maxindex%
IF needle$ = haystack$(index%) EXIT FOR
NEXT
IF index% <= maxindex% THEN
PRINT "First found at index "; index%
FOR last% = maxindex% TO 0 STEP -1
IF needle$ = haystack$(last%) EXIT FOR
NEXT
IF last%<>index% PRINT "Last found at index "; last%
ELSE
ERROR 100, "Not found"
ENDIF</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Search.bas"
110 STRING A$(1 TO 55)*8
120 FOR I=1 TO 55
Line 376 ⟶ 496:
240 LOOP
250 DATA foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt,foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc
260 DATA spqr,wombat,shme,foo,bar,baz,bongo,spam,eggs,snork,foo,bar,zot,blarg,wibble,toto,titi,tata,tutu,pippo,pluto,paperino,aap,noot,mies,oogle,foogle,boogle,zork,gork,bork</langsyntaxhighlight>
 
==={{header|FreeBASIC}}===
FreeBASIC doesn't have exceptions so we use a different approach to check if the needle is present or not in the haystack:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
' Works FB 1.05.0 Linux Mint 64
 
Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
index = i '' first occurrence
Return True
End If
Next
index = LBound(s) - 1 '' outside array
Return False
End Function
 
Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
Dim maxIndex As Integer = LBound(s) - 1 '' outside array
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
maxIndex = i
End If
Next
If maxIndex > LBound(s) - 1 Then
index = maxIndex '' last occurrence
Return True
Else
Return False
End If
End Function
 
Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"}
Dim needle(1 To 4) As String = {"Zag", "Krusty", "Washington", "Bush"}
 
Dim As Integer index
Dim As Boolean found
For i As Integer = 1 To 4
found = tryFindString(haystack(), needle(i), index)
If found Then
Print needle(i); " found first at index"; index
Else
Print needle(i); " is not present"
End If
Next
found = tryFindLastString(haystack(), needle(4), index)
If found Then
Print needle(4); " found last at index"; index
Else
Print needle(4); " is not present"
End If
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Zag found first at index 2
Krusty found first at index 6
Washington is not present
Bush found first at index 5
Bush found last at index 8
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=7729d65f8af3f128db6c6992c5f74e98 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Dim sOutput As String = "No needle found!"
Dim siCount As Short
 
For siCount = 0 To sHaystack.Max
If sNeedle = sHaystack[siCount] Then
sOutPut = sNeedle & " found at index " & Str(siCount)
Break
End If
Next
 
Print sOutput
 
End</syntaxhighlight>
Output:
<pre>
Charlie found at index 6
</pre>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
 
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
 
needle$="needle"
'index of first occurrence
for i = 1 to total
if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i
 
'index of last occurrence
for j = total to 1
if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
print "Multiple instances of ";needle$
else
print "Only one instance of ";needle$;" in list."
end if
 
'raise exception
needle$="cauliflower"
for k=1 to total
if word$(haystack$,k)=needle$ then exit for
next
if k>total then
print needle$;" not found in list."
else
print needle$;" found at index ";k
end if</syntaxhighlight>
 
 
==={{header|PowerBASIC}}===
{{works with|PowerBASIC for Windows}}
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
DIM haystack(54) AS STRING
ARRAY ASSIGN haystack() = "foo", "bar", "baz", "quux", "quuux", "quuuux", _
"bazola", "ztesch", "foo", "bar", "thud", "grunt", "foo", _
"bar", "bletch", "foo", "bar", "fum", "fred", "jim", _
"sheila", "barney", "flarp", "zxc", "spqr", ";wombat", "shme", _
"foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", _
"bar", "zot", "blarg", "wibble", "toto", "titi", "tata", _
"tutu", "pippo", "pluto", "paperino", "aap", "noot", "mies", _
"oogle", "foogle", "boogle", "zork", "gork", "bork"
DIM needle AS STRING, found AS LONG, lastFound AS LONG
DO
needle = INPUTBOX$("Word to search for? (Leave blank to exit)")
IF needle <> "" THEN
' collate ucase -> case insensitive
ARRAY SCAN haystack(), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
lastFound = found
MSGBOX "Found """ & needle & """ at index " & TRIM$(STR$(found - 1))
IF found < UBOUND(haystack) THEN
DO
ARRAY SCAN haystack(lastFound), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
MSGBOX "Another occurence of """ & needle & """ at index " & _
TRIM$(STR$(found + lastFound - 1))
lastFound = found + lastFound
ELSE
MSGBOX "No more occurences of """ & needle & """ found"
EXIT DO 'will exit inner DO, not outer
END IF
LOOP
END IF
ELSE
MSGBOX "No occurences of """ & needle & """ found"
END IF
ELSE
EXIT DO
END IF
LOOP
END FUNCTION</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">If OpenConsole() ; Open a simple console to interact with user
NewList Straws.s()
Define Straw$, target$="TBA"
Define found
Restore haystack ; Read in all the straws of the haystack.
Repeat
Read.s Straw$
If Straw$<>""
AddElement(Straws())
Straws()=UCase(Straw$)
Continue
Else
Break
EndIf
ForEver
While target$<>""
Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input()
ResetList(Straws()): found=#False
While NextElement(Straws())
If UCase(target$)=Straws()
found=#True
PrintN(target$+" found as index #"+Str(ListIndex(Straws())))
EndIf
Wend
If Not found
PrintN("Not found.")
EndIf
Wend
EndIf
DataSection
haystack:
Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection</syntaxhighlight>
 
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$ = "Zag Wally Bush Chicken"
 
while word$(needle$,i+1," ") <> ""
i = i + 1
thisNeedle$ = word$(needle$,i," ") + " "
j = instr(haystack$,thisNeedle$)
k1 = 0
k = instr(haystack$,thisNeedle$,j+1)
while k <> 0
k1 = k
k = instr(haystack$,thisNeedle$,k+1)
wend
if j <> 0 then
print thisNeedle$;" located at:";j;
if k1 <> 0 then print " Last position located at:";k1;
print
else
print thisNeedle$;" is not in the list"
end if
wend</syntaxhighlight>
{{out}}
<pre>Zag located at:5
Wally located at:9
Bush located at:22 Last position located at:52
Chicken is not in the list</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
 
dim item$(1)
 
n = token(list$, item$(), ",")
 
line input "Enter string to search: " line$
for i = 1 to n
if line$ = item$(i) then
if not t print "First index for ", line$, ": ", i
t = i
j = j + 1
end if
next
 
if t = 0 then
print "String not found in list"
else
if j > 1 print "Last index for ", line$, ": ", t
end if</syntaxhighlight>
 
=={{header|Batch File}}==
The index of this simple implementation is 1-based. The "haystack" data are borrowed from the [[Search_a_list#BASIC|BASIC]] implementation.
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 419 ⟶ 807:
%==We are done==%
echo.
pause</langsyntaxhighlight>
{{Out}}
<pre>"foo": Found 6 times. First instance:[1] Last instance:[35].
Line 429 ⟶ 817:
Press any key to continue . . .</pre>
 
=={{header|BBC BASICBQN}}==
 
{{works with|BBC BASIC for Windows}}
Generally, <code>⊐</code> (Index Of) is used to find the indices of the right argument array's elements in the left argument. It returns the length of the left argument <code>𝕨</code> if the argument is not present.
<lang bbcbasic> DIM haystack$(27)
 
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
The given <code>IndexOf</code> function is written to satisfy question requirements (throwing exceptions), and it is not recommended for use in production.
\ "hotel","india","juliet","kilo","lima","mike","needle", \
 
\ "november","oscar","papa","quebec","romeo","sierra","tango", \
<syntaxhighlight lang="bqn">list ← ⟨"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"⟩
\ "needle","uniform","victor","whisky","x-ray","yankee","zulu"
 
IndexOf ← {
needle$ = "needle"
("Error: '" ∾𝕩∾ "' Not found in list") ! (≠𝕨)≠ind ← ⊑𝕨⊐⋈𝕩
maxindex% = DIM(haystack$(), 1)
ind
}
FOR index% = 0 TO maxindex%
 
IF needle$ = haystack$(index%) EXIT FOR
•Show list ⊐ "Wally"‿"Hi" # intended
NEXT
•Show list IndexOf "Wally"
IF index% <= maxindex% THEN
list IndexOf "Hi"</syntaxhighlight><syntaxhighlight lang="text">⟨ 2 10 ⟩
PRINT "First found at index "; index%
2
FOR last% = maxindex% TO 0 STEP -1
! "Error: 'Hi' Not found in list"
IF needle$ = haystack$(last%) EXIT FOR
 
NEXT
("Error: '" ∾𝕩∾ "' Not found in list") ! (≠𝕨)≠ind ← ⊑𝕨⊐⋈𝕩
IF last%<>index% PRINT "Last found at index "; last%
^
ELSE
 
ERROR 100, "Not found"
list IndexOf "Hi"
ENDIF</lang>
^^^^^^^</syntaxhighlight>
 
=={{header|Bracmat}}==
For both subtasks, pattern matching is used. The second subtasks proceeds in two steps. First, the first word that occurs twice is found (if it exists). Then, the last occurrence of this word is found using forced backtracking (see the <code>~</code> node) until failure.
<langsyntaxhighlight Bracmatlang="bracmat">( return the largest index to a needle that has multiple
occurrences in the haystack and print the needle
: ?list
Line 477 ⟶ 866:
| out$"No word occurs more than once."
)
);</langsyntaxhighlight>
{{out}}
<pre>The word 'haystack' occurs at 1-based index 14
Line 484 ⟶ 873:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}"Bush"Fi
3</langsyntaxhighlight>
 
If you want all indices:
 
<langsyntaxhighlight lang="burlesque">blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}{"Bush"==}fI
{3 5}</langsyntaxhighlight>
 
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 533 ⟶ 922:
printf("Last index for Zag: %d\n", search_last_needle("Zag", haystack));
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 543 ⟶ 932:
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 557 ⟶ 946:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 564 ⟶ 953:
The following code shows three different ways to solve the task.
 
<langsyntaxhighlight lang="cpp">#include <string>
#include <algorithm>
#include <iterator>
Line 675 ⟶ 1,064:
std::cout << "\n=== Word not occuring at all ===\n";
test("Goofy");
}</langsyntaxhighlight>
 
{{out}} (note that in C++, indices start at 0):
Line 707 ⟶ 1,096:
=== C++11 ===
{{works with|g++ version 4.8.4, clang++ version 3.4| "-std=c++11" }}
<langsyntaxhighlight lang="cpp">/* new c++-11 features
* list class
* initialization strings
Line 820 ⟶ 1,209:
} // main
 
/* end */</langsyntaxhighlight>
{{out}}
<pre>
Line 830 ⟶ 1,219:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared test void searchAListTask() {
value haystack = [
"Zig", "Zag", "Wally", "Ronald", "Bush",
Line 840 ⟶ 1,229:
assertEquals(firstIdx, 4);
assertEquals(lastIdx, 7);
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]]
(let [idx (.indexOf haystack "Zig")]
(if (neg? idx)
(throw (Error. "item not found."))
idx)))</langsyntaxhighlight>
 
Extra credit: Since Clojure vectors implement java.util.List, you can switch .indexOf for .lastIndexOf to find the highest index of your value.
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% 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</syntaxhighlight>
{{out}}
<pre>Ronald: 4
McDonald: not found
Bush: 5
Obama: not found</pre>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">*> This is written to COBOL85, which does not include exceptions.
IDENTIFICATION DIVISION.
PROGRAM-ID. Search-List.
Line 914 ⟶ 1,342:
DISPLAY "Found last of " needle " at " haystack-index "."
END-IF
.</langsyntaxhighlight>
 
{{out}}
Line 924 ⟶ 1,352:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let ((haystack '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)))
(dolist (needle '(Washington Bush))
(let ((index (position needle haystack)))
(if index
(progn (print index) (princ needle))
(progn (print needle) (princ "is not in haystack"))))))</langsyntaxhighlight>
{{out}}
<pre>
Line 936 ⟶ 1,364:
</pre>
The position function solves this task elegantly.
<langsyntaxhighlight lang="lisp">
CL-USER> (defparameter *list* '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo))
*LIST*
Line 944 ⟶ 1,372:
7
CL-USER> (position 'Washington *list*)
NIL</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.algorithm, std.range, std.string;
 
auto firstIndex(R, T)(R hay, T needle) {
Line 964 ⟶ 1,392:
assert(firstIndex(h, "Bush") == 4);
assert(lastIndex(h, "Bush") == 7);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
<langsyntaxhighlight Delphilang="delphi">program Needle;
 
{$APPTYPE CONSOLE}
Line 1,003 ⟶ 1,431:
list.Free;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,012 ⟶ 1,440:
=={{header|DWScript}}==
 
<langsyntaxhighlight Delphilang="delphi">var haystack : array of String = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];
 
function Find(what : String) : Integer;
Line 1,022 ⟶ 1,450:
 
PrintLn(Find("Ronald")); // 3
PrintLn(Find('McDonald')); // exception</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
 
/** meet the 'raise an exception' requirement */
Line 1,037 ⟶ 1,465:
 
println(find("Ronald")) # prints 3
println(find("McDonald")) # will throw</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
haystack$[] = [ "Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Boz" "Zag" ]
#
func getind needle$ .
for i to len haystack$[]
if haystack$[i] = needle$
return i
.
.
return 0
.
# arrays are 1 based
for n$ in [ "Bush" "Washington" ]
h = getind n$
if h = 0
print n$ & " not found"
else
print n$ & " found at " & h
.
.
</syntaxhighlight>
 
=={{header|Ecstasy}}==
The <code>List</code> type has an <code>indexOf()</code> method, and the <code>Array</code> type is a <code>List</code>:
<syntaxhighlight lang="ecstasy">
module test {
@Inject Console console;
 
void run() {
String[] haystack = ["this", "needle", "is", "a", "test"];
if (Int pos := haystack.indexOf("needle")) {
console.print($"Found the needle at {pos=}");
} else {
console.print("No needle in the haystack");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
x$ xec test
Found the needle at pos=1
</pre>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,048 ⟶ 1,523:
var haystack := new string[]{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"};
new string[]{"Washington", "Bush"}.forEach::(needle)
{
var index := haystack.indexOfElement:(needle);
if (index == -1)
Line 1,061 ⟶ 1,536:
}
}
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">haystack = ~w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)
 
Enum.each(~w(Bush Washington), fn needle ->
Line 1,070 ⟶ 1,545:
if index, do: (IO.puts "#{index} #{needle}"),
else: raise "#{needle} is not in haystack\n"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,087 ⟶ 1,562:
Erlang lists can be accessed with the function lists:nth/2, which starts at 1 (first element). As such Erlang can be considered 1-indexed for this problem.
Note that you could set the indexing to 0 by modifying the function call in pos/2.
<langsyntaxhighlight lang="erlang">-module(index).
-export([main/0]).
 
Line 1,101 ⟶ 1,576:
 
print({Needle, undefined}) -> io:format("~s is not in haystack.~n",[Needle]);
print({Needle, Pos}) -> io:format("~s at position ~p.~n",[Needle,Pos]).</langsyntaxhighlight>
 
{{out}}
Line 1,115 ⟶ 1,590:
The procedure can be made into a function to search with other strings, take user input and give output of the searched haystack.
 
<langsyntaxhighlight lang="euphoria">
include std/search.e
include std/console.e
Line 1,162 ⟶ 1,637:
--wait for user to press a key to exit
any_key()
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,194 ⟶ 1,669:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">List.findIndex (fun x -> x = "bar") ["foo"; "bar"; "baz"; "bar"] // -> 1
// A System.Collections.Generic.KeyNotFoundException
// is raised, if the predicate does not evaluate to
// true for any list element.</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: find-index ( seq elt -- i )
'[ _ = ] find drop [ "Not found" throw ] unless* ; inline
 
: find-last-index ( seq elt -- i )
'[ _ = ] find-last drop [ "Not found" throw ] unless* ; inline</langsyntaxhighlight>
 
( scratchpad ) { "a" "b" "c" "d" "c" } "c" find-index .
Line 1,213 ⟶ 1,688:
=={{header|Forth}}==
{{works with|4tH|3.61.5}}
<langsyntaxhighlight lang="forth">include lib/row.4th
 
create haystack
Line 1,223 ⟶ 1,698:
;
 
s" Washington" haystack s" Bush" haystack</langsyntaxhighlight>
 
 
Line 1,230 ⟶ 1,705:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
 
Line 1,259 ⟶ 1,734:
s" Hillary" haystack LastIndexOf . \ => 7
s" Washington" haystack needleIndex . \ => aborted: Not found
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">program main
 
implicit none
Line 1,297 ⟶ 1,772:
end subroutine find_needle
 
end program main</langsyntaxhighlight>
 
=={{header|FreeBASICFutureBasic}}==
<syntaxhighlight lang="futurebasic">
FreeBASIC doesn't have exceptions so we use a different approach to check if the needle is present or not in the haystack:
window 1, @"Search a list"
<lang freebasic>' FB 1.05.0 Win64
' Works FB 1.05.0 Linux Mint 64
 
void local fn MyEnumeratorCallback( array as CFArrayRef, obj as CFTypeRef, index as NSUInteger, stp as ^BOOL, userData as ptr )
Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean
if ( fn StringIsEqual( obj, userData ) )
Dim length As Integer = UBound(s) - LBound(s) + 1
print obj;@" found at index ";index
If length = 0 Then
*stp = YES// stop enumeration
index = LBound(s) - 1 '' outside array
end if
Return False
if ( index == 0 ) then print userData;@" not found"
End If
end fn
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
index = i '' first occurrence
Return True
End If
Next
index = LBound(s) - 1 '' outside array
Return False
End Function
 
void local fn DoIt
Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean
CFArrayRef haystack = @[@"Mike",@"Bravo",@"Tango",@"Uniform",@"Golf",
Dim length As Integer = UBound(s) - LBound(s) + 1
@"Tango",@"Sierra",@"November",@"Zulu",@"Delta",@"Hotel",@"Juliet"]
If length = 0 Then
index = LBound(s) - 1 '' outside array
CFStringRef needle = @"Sierra"
Return False
End If
NSInteger index = fn ArrayIndexOfObject( haystack, needle )
Dim maxIndex As Integer = LBound(s) - 1 '' outside array
if ( index != NSNotFound )
For i As Integer = LBound(s) To UBound(s)
print needle;@" found at index ";index
If s(i) = search Then
else
maxIndex = i
print needle;@" not found"
End If
Nextend if
If maxIndex > LBound(s) - 1 Then
ArrayEnumerateObjectsWithOptions( haystack, NSEnumerationReverse, @fn MyEnumeratorCallback, (ptr)@"Tango" )
index = maxIndex '' last occurrence
end fn
Return True
Else
Return False
End If
End Function
 
fn DoIt
Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"}
Dim needle(1 To 4) As String = {"Zag", "Krusty", "Washington", "Bush"}
 
Dim As Integer index
Dim As Boolean found
For i As Integer = 1 To 4
found = tryFindString(haystack(), needle(i), index)
If found Then
Print needle(i); " found first at index"; index
Else
Print needle(i); " is not present"
End If
Next
found = tryFindLastString(haystack(), needle(4), index)
If found Then
Print needle(4); " found last at index"; index
Else
Print needle(4); " is not present"
End If
Print
Print "Press any key to quit"
Sleep</lang>
 
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
ZagSierra found first at index 26
KrustyTango found first at index 65
Washington is not present
Bush found first at index 5
Bush found last at index 8
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=7729d65f8af3f128db6c6992c5f74e98 Click this link to run this code]'''
<lang gambas>Public Sub Main()
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Dim sOutput As String = "No needle found!"
Dim siCount As Short
 
For siCount = 0 To sHaystack.Max
If sNeedle = sHaystack[siCount] Then
sOutPut = sNeedle & " found at index " & Str(siCount)
Break
End If
Next
 
Print sOutput
 
End</lang>
Output:
<pre>
Charlie found at index 6
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># First position is built-in
haystack := Eratosthenes(10000);;
needle := 8999;;
Line 1,422 ⟶ 1,839:
# 1
LastPosition(a, 0);
# 97</langsyntaxhighlight>
See also [[Sieve of Eratosthenes#GAP|Eratosthenes]] and [[Knuth shuffle#GAP|Shuffle]] functions in RosettaCode.
 
=={{header|Go}}==
Data used by both examples below. (You can give multiple files to go run, like <tt>$ go run data.go example.go</tt>)
<langsyntaxhighlight lang="go">package main
 
var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty",
Line 1,440 ⟶ 1,857:
"zork", "gork", "bork", "sodium", "phosphorous", "californium",
"copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper",
"helium", "sulfur"}</langsyntaxhighlight>
===Linear search===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,507 ⟶ 1,924:
}
return -1
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,519 ⟶ 1,936:
===Map lookup===
More efficient, if you're doing lots of lookups, is to build a map. This example doesn't completely conform to the task but gives the idea that you could store indexes as map values.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,531 ⟶ 1,948:
fmt.Println(n, m[n])
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,540 ⟶ 1,957:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
def needles = ["Washington","Bush","Wally"]
needles.each { needle ->
Line 1,552 ⟶ 1,969:
println "Last index: " + lastindex + " " + needle
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,565 ⟶ 1,982:
=={{header|Haskell}}==
Libraries and data:
<langsyntaxhighlight lang="haskell">import Data.List
 
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
needles = ["Washington","Bush"]</langsyntaxhighlight>
I use 'lambda' notation for readability.
:Find 'just' an index:
<langsyntaxhighlight lang="haskell">*Main> map (\x -> (x,elemIndex x haystack)) needles
[("Washington",Nothing),("Bush",Just 4)]</langsyntaxhighlight>
Want to know if there are there more Bushes hiding in the haystack?
<langsyntaxhighlight lang="haskell">*Main> map (\x -> (x,elemIndices x haystack)) needles
[("Washington",[]),("Bush",[4,7])]</langsyntaxhighlight>
To be complete. Here is the 'point free' version of the task:
<langsyntaxhighlight lang="haskell">*Main> ((,) <*> flip elemIndex haystack) <$> needles
[("Washington",Nothing),("Bush",Just 4)]</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">CHARACTER haystack='Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo.'
CHARACTER needle*10
 
Line 1,598 ⟶ 2,015:
WRITE(ClipBoard) "Last ", needle, "found in position ", last
! Last bush found in position 8
ENDIF</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">
<lang Icon>
link lists
 
Line 1,626 ⟶ 2,043:
every i := p!arglist
return \i
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Taken from the public domain Icon Programming Library's [http://www.cs.arizona.edu/icon/library/src/procs/lists.icn lindex in lists] which generates list indices for x of any type
<langsyntaxhighlight Iconlang="icon">procedure lindex(lst, x) #: generate indices for items matching x
local i
 
Line 1,636 ⟶ 2,053:
if lst[i] === x then suspend i
 
end</langsyntaxhighlight>
 
{{out}}
Line 1,655 ⟶ 2,072:
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.
 
<langsyntaxhighlight Iolang="io">NotFound := Exception clone
List firstIndex := method(obj,
indexOf(obj) ifNil(NotFound raise)
Line 1,680 ⟶ 2,097:
writeln(needle," is not in haystack")
)pass
)</langsyntaxhighlight>
{{out}}
<pre>firstIndex("Washington"): Washington is not in haystack
Line 1,693 ⟶ 2,110:
For example:
 
<langsyntaxhighlight lang="j"> Haystack =: ;:'Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo'
Needles =: ;:'Washington Bush'
Line 1,699 ⟶ 2,116:
9 4
Haystack i: Needles NB. last positions
9 7</langsyntaxhighlight>
 
Note that the arguments to <code>i.</code> can be anything (ie either or both may be scalars, lists, multidimensional arrays, etc). Nonmatches get a result of 1+largest valid index.
Line 1,707 ⟶ 2,124:
<code>e.</code> finds whether items are members of a set, returning a bitmask to select the members:
 
<langsyntaxhighlight lang="j"> Needles e. Haystack
0 1
1 2 3 4 5 6 7 8 9 e. 2 3 5 60
0 1 1 0 1 0 0 0 0</langsyntaxhighlight>
 
<code>I.</code> finds indices, but performs a binary search (which requires that the list being searched is sorted). This can be useful for finding non-exact matches (the index of the next value is returned for non-exact matches).
 
<langsyntaxhighlight lang="j"> 1 2 3 4 5 6 7 8 9 I. 2 3 5 60 6.66
1 2 4 9 6
(;:'eight five four nine one seven six three two') I. ;:'two three five sixty'
8 7 1 7</langsyntaxhighlight>
 
To format output similar to the other examples, one might write:
 
<langsyntaxhighlight lang="j"> Haystack ;:^:_1@(] ,. [ ((<'is not in haystack')"_)`(#@[ I.@:= ])`(8!:0@])} i.) Needles
Washington is not in haystack
Bush 4</langsyntaxhighlight>
 
Or broken up into components and defined as a verb/function for finding the last positions:
<langsyntaxhighlight lang="j"> msg=: (<'is not in haystack')"_ NB. not found message
idxmissing=: #@[ I.@:= ] NB. indices of items not found
fmtdata=: 8!:0@] NB. format atoms as boxed strings
Line 1,733 ⟶ 2,150:
Haystack findLastIndex Needles NB. usage
Washington is not in haystack
Bush 7</langsyntaxhighlight>
 
To elaborate a bit: Array-oriented languages (like J) consume the input and produce the output ''in toto''.
Line 1,751 ⟶ 2,168:
=={{header|Java}}==
for Lists, they have an indexOf() method:
<langsyntaxhighlight lang="java">import java.util.List;
import java.util.Arrays;
 
Line 1,762 ⟶ 2,179:
else
System.out.println(index + " " + needle);
}</langsyntaxhighlight>
 
for arrays, you have to do it manually:
<langsyntaxhighlight lang="java">import java.util.Arrays;
String[] haystack = { "Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"};
Line 1,775 ⟶ 2,192:
else
System.out.println(index + " " + needle);
}</langsyntaxhighlight>
 
{{out}}
Line 1,784 ⟶ 2,201:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var haystack = ['Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo']
var needles = ['Bush', 'Washington']
 
Line 1,799 ⟶ 2,216:
else
throw needles[i] + " does not appear in the haystack"
}</langsyntaxhighlight>
 
The following {{works with|JavaScript|1.6}}:
<langsyntaxhighlight lang="javascript">for each (var needle in needles) {
var idx = haystack.indexOf(needle);
if (idx == -1)
Line 1,819 ⟶ 2,236:
break
}
}</langsyntaxhighlight>
 
 
Or, generalising enough (in ES5) to allow for varying definitions of the type of match we are looking for:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
function findIndex(fnPredicate, list) {
Line 1,870 ⟶ 2,287:
})
}
})();</langsyntaxhighlight>
 
Output:
 
<syntaxhighlight lang="javascript">{
<lang JavaScript>{
"first": [
[
Line 1,895 ⟶ 2,312:
]
]
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,902 ⟶ 2,319:
 
In the following, the output is shown after the "# =>":
<syntaxhighlight lang="jq">
<lang jq>
["a","b","c"] | index("b")
# => 1
Line 1,919 ⟶ 2,336:
 
["a","b","c","b","d"] | indices("b")[-1]
# => 3</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">@show findfirst(["no", "?", "yes", "maybe", "yes"], "yes")
@show indexin(["yes"], ["no", "?", "yes", "maybe", "yes"])
@show findin(["no", "?", "yes", "maybe", "yes"], ["yes"])
@show find(["no", "?", "yes", "maybe", "yes"] .== "yes")</langsyntaxhighlight>
 
{{out}}
Line 1,936 ⟶ 2,353:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> Haystack:("Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo")
Needles:("Washington";"Bush")
{:[y _in x;(y;x _bin y);(y;"Not Found")]}[Haystack]'Needles </langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight Klang="k">(("Washington"
"Not Found")
("Bush"
4))</langsyntaxhighlight>
 
Additional:
Line 1,950 ⟶ 2,367:
Here we use the dyadic verb _sm (string match) instead of _bin (binary search).
 
<langsyntaxhighlight Klang="k"> Haystack2: Haystack,,"Bush"
Needles2:Needles,,"Zag"
{+(x;{:[#&x;,/?(*&x;*|&x);"Not found"]}'+x _sm/:y)}[Needles2;Haystack2]</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight Klang="k">(("Washington"
"Not found")
("Bush"
4 9)
("Zag"
1))</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6 (search_list.kt)
 
fun main(args: Array<String>) {
Line 1,976 ⟶ 2,393:
index = haystack.indexOf(needle)
if (index == -1) throw Exception("$needle does not occur in the list")
}</langsyntaxhighlight>
 
{{out}}
Line 1,990 ⟶ 2,407:
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: haystack(*) ['rosetta 'code 'search 'a 'list 'lang5 'code] find-index ;
: find-index
2dup eq length iota swap select swap drop
Line 1,998 ⟶ 2,415:
: ==>search apply ;
 
['hello 'code] 'haystack ==>search .</langsyntaxhighlight>
{{out}}
<pre>[ hello is not in haystack
Line 2,007 ⟶ 2,424:
Lasso arrays have a findindex method which returns all matching indexes. [http://lassoguide.com/operations/containers.html?#array]
 
<langsyntaxhighlight Lassolang="lasso">local(haystack) = array('Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo')
 
#haystack->findindex('Bush')->first // 5
Line 2,015 ⟶ 2,432:
handle_error => {^ error_msg ^}
fail_if(not #haystack->findindex('Washington')->first,'Washington is not in haystack.')
^}</langsyntaxhighlight>
 
{{out}}
Line 2,022 ⟶ 2,439:
8
Washington is not in haystack.</pre>
 
=={{header|Liberty BASIC}}==
<lang lb>haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
 
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
 
needle$="needle"
'index of first occurrence
for i = 1 to total
if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i
 
'index of last occurrence
for j = total to 1
if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
print "Multiple instances of ";needle$
else
print "Only one instance of ";needle$;" in list."
end if
 
'raise exception
needle$="cauliflower"
for k=1 to total
if word$(haystack$,k)=needle$ then exit for
next
if k>total then
print needle$;" not found in list."
else
print needle$;" found at index ";k
end if</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">haystack = ["apples", "oranges", "bananas", "oranges"]
needle = "oranges"
 
Line 2,073 ⟶ 2,451:
end if
 
-- "needle found at index 2"</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">+ haystack : ARRAY[STRING];
haystack := "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo".split;
"Washington Bush".split.foreach { needle : STRING;
Line 2,088 ⟶ 2,466:
" is not in haystack\n".print;
};
};</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to indexof :item :list
if empty? :list [(throw "NOTFOUND 0)]
if equal? :item first :list [output 1]
Line 2,103 ⟶ 2,481:
 
showindex "dog [My dog has fleas] ; dog found at position 2 in My dog has fleas
showindex "cat [My dog has fleas] ; cat not found in My dog has fleas</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">list = {"mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads"} --contents of my desk
 
item = io.read()
Line 2,112 ⟶ 2,490:
for i,v in ipairs(list)
if v == item then print(i) end
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 2,118 ⟶ 2,496:
Normally we use Exist(inventoryA, "key") and if it is true then we get the value as Eval(inventoryA) without using second search, by temporary use of an index. We can read that index by making a variable to bind a property of COM object (the object under the inventory).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Flush ' empty stack
Line 2,155 ⟶ 2,533:
}
CheckIt
</syntaxhighlight>
</lang>
 
Extra-Extra: Find all occurrences displaying the indexes for each one.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckThis {
Inventory Queue Haystack= "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt"
Line 2,185 ⟶ 2,563:
}
CheckThis
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]:
occurences := ListTools:-SearchAll(needle,haystack):
try
Line 2,197 ⟶ 2,575:
catch :
print("Erros: Needle not found in the haystack"):
end try:</langsyntaxhighlight>
{{Out|Examples}}
needle := "Washington":
Line 2,205 ⟶ 2,583:
The last occurence is at index 8</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This examples shows you the first appearance, the last appearance, and all appearances (as a list):
<langsyntaxhighlight Mathematicalang="mathematica">haystack = {"Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"};
needle = "Zag";
first = Position[haystack,needle,1][[1,1]]
last = Position[haystack,needle,1][[-1,1]]
all = Position[haystack,needle,1][[All,1]]</langsyntaxhighlight>
gives back:
<syntaxhighlight lang="mathematica">2
<lang Mathematica>2
7
{2,7}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Collections of strings are stored in cell arrays in MATLAB. The solution bellow will only work for a cell array of this construction:<langsyntaxhighlight MATLABlang="matlab">stringCollection = {'string1','string2',...,'stringN'}</langsyntaxhighlight> It will not work for any other construction, for example:<langsyntaxhighlight MATLABlang="matlab">stringCollection = {{'string1'},{'string2'},{...},{'stringN'}}</langsyntaxhighlight>
 
searchCollection.m:
<langsyntaxhighlight MATLABlang="matlab">function index = searchCollection(list,searchItem,firstLast)
%firstLast is a string containing either 'first' or 'last'. The 'first'
Line 2,233 ⟶ 2,611:
assert(~isempty(index),['The string ''' searchItem ''' does not exist in this collection of strings.']);
 
end</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> list = {'a','b','c','d','e','c','f','c'};
>> searchCollection(list,'c','first')
 
Line 2,251 ⟶ 2,629:
>> searchCollection(list,'g','last')
??? Error using ==> searchCollection at 11
The string 'g' does not exist in this collection of strings.</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">haystack: ["Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"];
needle: "Zag";
 
Line 2,262 ⟶ 2,640:
if emptyp(opt) then return(idx),
opt: first(opt),
if opt='f then first(idx) else if opt='l then last(idx) else throw('unknownmode));</langsyntaxhighlight>
 
{{out|Usage}}
Line 2,279 ⟶ 2,657:
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">haystack=#("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")
 
for needle in #("Washington","Bush") do
Line 2,293 ⟶ 2,671:
format "% %\n" index needle
)
)</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="maxscript">Washington is not in haystack
5 Bush</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">$haystack = list()
append $haystack "Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie"
append $haystack "Bush" "Bozo"
Line 2,317 ⟶ 2,695:
println $needle + " is not in haystack"
end
end for</langsyntaxhighlight>
{{out}}
<pre>Washington is not in haystack
Line 2,323 ⟶ 2,701:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,428 ⟶ 2,806:
end needle
return</langsyntaxhighlight>
{{out}}
<pre>
Line 2,451 ⟶ 2,829:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
 
for needle in ["Bush", "Washington"]:
Line 2,458 ⟶ 2,836:
echo f, " ", needle
else:
raise newException(ValueError, needle & " not in haystack")</langsyntaxhighlight>
 
{{out}}
<pre>4 Bush
[...]/search_a_list.nim(8) search_a_list
Error: unhandled exception: Washington not in haystack [ValueError]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use Collection;
 
class Test {
Line 2,476 ⟶ 2,859:
};
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
{{works with|Objective-C|2.0+}}
<langsyntaxhighlight lang="objc">NSArray *haystack = @[@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo"];
for (id needle in @[@"Washington",@"Bush"]) {
int index = [haystack indexOfObject:needle];
Line 2,487 ⟶ 2,870:
else
NSLog(@"%i %@", index, needle);
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># let find_index pred lst =
let rec loop n = function
[] -> raise Not_found
Line 2,512 ⟶ 2,895:
Washington is not in haystack
4 Bush
- : unit = ()</langsyntaxhighlight>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
import "core:slice"
import "core:fmt"
 
main :: proc() {
hay_stack := []string{"Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"}
 
// Odin does not support exceptions.
// For conditions requiring special processing during the execution of a program it is
// encouraged to make that explicit through return values:
 
index, found := slice.linear_search(hay_stack, "Bush")
if found do fmt.printf("First occurence of 'Bush' at %d\n", index)
 
index, found = slice.linear_search(hay_stack, "Rob")
if found do fmt.printf("First occurence of 'Rob' at %d\n", index)
}
 
// Output:
// First occurence of 'Bush' at 4</syntaxhighlight>
 
=={{header|Oforth}}==
Line 2,518 ⟶ 2,925:
indexOf returns null if an object is not into a collection, not an exception.
 
<langsyntaxhighlight Oforthlang="oforth">: needleIndex(needle, haystack)
haystack indexOf(needle) dup ifNull: [ drop ExRuntime throw("Not found", needle) ] ;
 
Line 2,525 ⟶ 2,932:
needleIndex("Bush", Haystack) println
Haystack lastIndexOf("Bush") println
needleIndex("Washington", Haystack) println</langsyntaxhighlight>
 
{{out}}
Line 2,538 ⟶ 2,945:
For ordered collections, this will always be the first item.
For unordered collections, the index returned is undetermined.
<langsyntaxhighlight ooRexxlang="oorexx">-- ordered collections always return the first hit
a = .array~of(1,2,3,4,4,5)
say a~index(4)
Line 2,556 ⟶ 2,963:
d["foo"] = 4
d["bar"] = 4
say d~index(4)</langsyntaxhighlight>
 
=={{header|Oz}}==
Line 2,562 ⟶ 2,969:
(the operation is quite inefficient, after all).
A possible implementation:
<langsyntaxhighlight lang="oz">declare
%% Lazy list of indices of Y in Xs.
fun {Indices Y Xs}
Line 2,585 ⟶ 2,992:
{Show {List.last {Indices "Bush" Haystack}}}
 
{Show {Index "Washington" Haystack}} %% throws</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<langsyntaxhighlight lang="parigp">find(v,n)={
my(i=setsearch(v,n));
if(i,
Line 2,597 ⟶ 3,004:
);
i
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,603 ⟶ 3,010:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util qw(first);
 
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
Line 2,615 ⟶ 3,022:
print "$needle is not in haystack\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,623 ⟶ 3,030:
 
You could install a non-standard module List::MoreUtils:
<langsyntaxhighlight lang="perl">use List::MoreUtils qw(first_index);
 
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
Line 2,635 ⟶ 3,042:
print "$needle is not in haystack\n";
}
}</langsyntaxhighlight>
 
Alternatively, if you need to do this a lot, you could create a hash table mapping values to indices in the haystack:
<langsyntaxhighlight lang="perl">my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
 
my %haystack_indices;
Line 2,650 ⟶ 3,057:
print "$needle is not in haystack\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,658 ⟶ 3,065:
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>constant s = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"}
<!--<syntaxhighlight lang="phix">-->
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Zig"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Zag"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Wally"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Ronald"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bush"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Krusty"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Charlie"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bush"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Boz"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Zag"</span><span style="color: #0000FF;">}</span>
integer r = find("Zag",s) ?r -- 2 (first)
r = find("Zag",s,r+1) ?r -- 10 (next)
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Zag"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span> <span style="color: #000080;font-style:italic;">-- 2 (first)</span>
r = find("Zag",s,r+1) ?r -- 0 (no more)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Zag"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span> <span style="color: #000080;font-style:italic;">-- 10 (next)</span>
r = rfind("Zag",s) ?r -- 10 (last)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Zag"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span> <span style="color: #000080;font-style:italic;">-- 0 (no more)</span>
r = find("Zog",s) ?r -- 0 (none)</lang>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rfind</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Zag"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span> <span style="color: #000080;font-style:italic;">-- 10 (last)</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Zog"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span> <span style="color: #000080;font-style:italic;">-- 0 (none)</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">"mouse" "hat" "cup" "deodorant" "television"
"soap" "methamphetamine" "severed cat heads" "cup"
pstack
Line 2,692 ⟶ 3,102:
endif
endif
drop</langsyntaxhighlight>
 
Other solution with syntactic sugar for list construction.
 
<langsyntaxhighlight Phixmontilang="phixmonti">include Utilitys.pmt
 
0 var acum
Line 2,717 ⟶ 3,127:
search
endwhile
</syntaxhighlight>
</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$haystack = array("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
 
foreach (array("Washington","Bush") as $needle) {
Line 2,728 ⟶ 3,138:
else
echo "$i $needle\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,734 ⟶ 3,144:
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.
<syntaxhighlight 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.</syntaxhighlight>
 
{{out}}
<pre>First 'Bush' = 5
Last 'Bush' = 9
All 'Bush' = [5,7,9]
error(search_list(Waldo),not_found)
Waldo = _3590</pre>
 
 
=={{header|PicoLisp}}==
Note that in PicoLisp all indexes are one-based
(the first element has the position '1')
<langsyntaxhighlight PicoLisplang="picolisp">(de lastIndex (Item Lst)
(- (length Lst) (index Item (reverse Lst)) -1) )
 
Line 2,747 ⟶ 3,204:
(findNeedle index 'Washington Lst)
(findNeedle index 'Bush Lst)
(findNeedle lastIndex 'Bush Lst) )</langsyntaxhighlight>
{{out}}
<pre>Washington not found
Line 2,754 ⟶ 3,211:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">search: procedure () returns (fixed binary);
declare haystack (0:9) character (200) varying static initial
('apple', 'banana', 'celery', 'dumpling', 'egg', 'flour',
Line 2,774 ⟶ 3,231:
signal condition(missing_needle);
return (lbound(haystack,1)-1);
end search;</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Make an example haystack.
Line 2,814 ⟶ 3,271:
Put the bale's next into the bale.
Bump the count.
Repeat.</langsyntaxhighlight>
{{out}}
<pre>
The index of "b" is 2
</pre>
 
=={{header|PowerBASIC}}==
{{works with|PowerBASIC for Windows}}
 
<lang powerbasic>FUNCTION PBMAIN () AS LONG
DIM haystack(54) AS STRING
ARRAY ASSIGN haystack() = "foo", "bar", "baz", "quux", "quuux", "quuuux", _
"bazola", "ztesch", "foo", "bar", "thud", "grunt", "foo", _
"bar", "bletch", "foo", "bar", "fum", "fred", "jim", _
"sheila", "barney", "flarp", "zxc", "spqr", ";wombat", "shme", _
"foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", _
"bar", "zot", "blarg", "wibble", "toto", "titi", "tata", _
"tutu", "pippo", "pluto", "paperino", "aap", "noot", "mies", _
"oogle", "foogle", "boogle", "zork", "gork", "bork"
DIM needle AS STRING, found AS LONG, lastFound AS LONG
DO
needle = INPUTBOX$("Word to search for? (Leave blank to exit)")
IF needle <> "" THEN
' collate ucase -> case insensitive
ARRAY SCAN haystack(), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
lastFound = found
MSGBOX "Found """ & needle & """ at index " & TRIM$(STR$(found - 1))
IF found < UBOUND(haystack) THEN
DO
ARRAY SCAN haystack(lastFound), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
MSGBOX "Another occurence of """ & needle & """ at index " & _
TRIM$(STR$(found + lastFound - 1))
lastFound = found + lastFound
ELSE
MSGBOX "No more occurences of """ & needle & """ found"
EXIT DO 'will exit inner DO, not outer
END IF
LOOP
END IF
ELSE
MSGBOX "No occurences of """ & needle & """ found"
END IF
ELSE
EXIT DO
END IF
LOOP
END FUNCTION</lang>
 
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function index($haystack,$needle) {
$index = $haystack.IndexOf($needle)
Line 2,879 ⟶ 3,292:
index $haystack "house"
index $haystack "paragraph"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,888 ⟶ 3,301:
===PowerShell Extra credit===
The -Verbose switch is available to any advanced function.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Find-Needle
{
Line 2,946 ⟶ 3,359:
 
$haystack = @("word", "phrase", "preface", "title", "house", "line", "chapter", "page", "book", "house")
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Find-Needle "house" $haystack
</syntaxhighlight>
</lang>
{{Out}}
<pre>
4
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Find-Needle "house" $haystack -Verbose
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,962 ⟶ 3,375:
4
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Find-Needle "house" $haystack -LastIndex -Verbose
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,970 ⟶ 3,383:
9
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Find-Needle "title" $haystack -LastIndex -Verbose
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,978 ⟶ 3,391:
3
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Find-Needle "something" $haystack -Verbose
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,989 ⟶ 3,402:
=={{header|Prolog}}==
Works with SWI-Prolog
<langsyntaxhighlight Prologlang="prolog">search_a_list(N1, N2) :-
L = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"],
 
Line 3,012 ⟶ 3,425:
my_write(Name) :-
writef(' %s', [Name]).
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,023 ⟶ 3,436:
true.
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole() ; Open a simple console to interact with user
NewList Straws.s()
Define Straw$, target$="TBA"
Define found
Restore haystack ; Read in all the straws of the haystack.
Repeat
Read.s Straw$
If Straw$<>""
AddElement(Straws())
Straws()=UCase(Straw$)
Continue
Else
Break
EndIf
ForEver
While target$<>""
Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input()
ResetList(Straws()): found=#False
While NextElement(Straws())
If UCase(target$)=Straws()
found=#True
PrintN(target$+" found as index #"+Str(ListIndex(Straws())))
EndIf
Wend
If Not found
PrintN("Not found.")
EndIf
Wend
EndIf
DataSection
haystack:
Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection</lang>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
 
for needle in ("Washington","Bush"):
Line 3,069 ⟶ 3,444:
print haystack.index(needle), needle
except ValueError, value_error:
print needle,"is not in haystack"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,079 ⟶ 3,454:
The following shows the default information given
when the exception is not captured in the program:
<langsyntaxhighlight lang="python">>>> haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
>>> haystack.index('Bush')
4
Line 3,087 ⟶ 3,462:
haystack.index('Washington')
ValueError: list.index(x): x not in list
>>></langsyntaxhighlight>
 
There is no built-in method for returning the highest index of a repeated string in a Python list, tuple or array, (although strings have [http://docs.python.org/library/stdtypes.html?highlight=rindex#str.rindex rindex]).
Instead we need to look for the index in the reversed list and adjust the result.
<langsyntaxhighlight lang="python">>>> def hi_index(needle, haystack):
return len(haystack)-1 - haystack[::-1].index(needle)
 
Line 3,102 ⟶ 3,477:
assert hi == haystack.index(n), "index == hi_index if needle occurs only once"
 
>>></langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">find.needle <- function(haystack, needle="needle", return.last.index.too=FALSE)
{
indices <- which(haystack %in% needle)
if(length(indices)==0) stop("no needles in the haystack")
if(return.last.index.too) range(indices) else min(indices)
}</langsyntaxhighlight>
Example usage:
<langsyntaxhighlight Rlang="r">haystack1 <- c("where", "is", "the", "needle", "I", "wonder")
haystack2 <- c("no", "sewing", "equipment", "in", "here")
haystack3 <- c("oodles", "of", "needles", "needles", "needles", "in", "here")
Line 3,119 ⟶ 3,494:
find.needle(haystack2) # error
find.needle(haystack3) # 3
find.needle(haystack3, needle="needles", ret=TRUE) # 3 5</langsyntaxhighlight>
 
=={{header|Racket}}==
The function index returns the index of the the element x in the sequence xs.
If the element is not found, then #f is returned.
<langsyntaxhighlight lang="racket">(define (index xs y)
(for/first ([(x i) (in-indexed xs)]
#:when (equal? x y))
i))</langsyntaxhighlight>
 
If the last index of an element is needed, for/last is used:
<langsyntaxhighlight lang="racket">(define (index-last xs y)
(for/last ([(x i) (in-indexed xs)]
#:when (equal? x y))
i))</langsyntaxhighlight>
 
Both index and index-last can handle any sequence such as lists, vectors, sets etc.
Let us test with a linked list:
<langsyntaxhighlight lang="racket">(define haystack '("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))
 
(for/list ([needle '("Bender" "Bush")])
Line 3,143 ⟶ 3,518:
 
(for/list ([needle '("Bender" "Bush")])
(index-last haystack needle))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,154 ⟶ 3,529:
 
{{works with|Rakudo Star|2016.07}}
<syntaxhighlight lang="raku" perl6line>my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
for <Washington Bush> -> $needle {
say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }";
}</langsyntaxhighlight>
 
{{out}}
Line 3,169 ⟶ 3,544:
Or, including the "extra credit" task:
{{works with|Rakudo Star|2016.07}}
<syntaxhighlight lang="raku" perl6line>my Str @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
 
for <Washingston Bush> -> $needle {
Line 3,181 ⟶ 3,556:
say "$needle -- not in haystack";
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,195 ⟶ 3,570:
<br>
If you plan to do many searches on the same large list, you might want to build a search hash first for efficient look-up:
<syntaxhighlight lang="raku" perl6line>my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
 
my %index;
Line 3,202 ⟶ 3,577:
for <Washington Bush> -> $needle {
say "$needle -- { %index{$needle} // 'not in haystack' }";
}</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "List Indexing"
URL: http://rosettacode.org/wiki/Index_in_a_list
Line 3,242 ⟶ 3,617:
reform [needle "=>" locate/largest haystack needle]
]
]</langsyntaxhighlight>
 
{{out}}
Line 3,261 ⟶ 3,636:
<br><br>The haystack items may have any character, including blanks.
<br>A ''null'' value isn't allowed in this method of representing values.
<langsyntaxhighlight lang="rexx">/*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.= /*initialize the haystack collection. */
hay.1 = 'sodium'
Line 3,289 ⟶ 3,664:
if found then return j /*return the haystack index number. */
else say needle "wasn't found in the haystack!"
return 0 /*indicates the needle wasn't found. */</langsyntaxhighlight>
 
===version 2===
Line 3,297 ⟶ 3,672:
this counter may be any sufficiently high number.
<br><br>The array may be out of order (but not recommended!).
<langsyntaxhighlight lang="rexx">/*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.0 = 1000 /*safely indicate highest item number. */
hay.200 = 'Binilnilium'
Line 3,330 ⟶ 3,705:
if found then return j /*return the haystack index number. */
else say needle "wasn't found in the haystack!"
return 0 /*indicates the needle wasn't found. */</langsyntaxhighlight>
 
===version 3===
Line 3,345 ⟶ 3,720:
<br>variable names. Therefore, there shouldn't be any REXX variable names (in this
<br>program) that have a leading underscore &nbsp; ('''_''').
<langsyntaxhighlight lang="rexx">/*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.=0 /*initialize the haystack collection. */
hay._sodium = 1
Line 3,373 ⟶ 3,748:
if found then return j /*return the haystack index number. */
else say needle "wasn't found in the haystack!"
return 0 /*indicates the needle wasn't found. */</langsyntaxhighlight>
 
===version 4===
This method uses a simple string (so haystack items can't have embedded blanks or tabs in them).
<br>Code was added to uppercase both the &nbsp; '''haystack''' &nbsp; and the &nbsp; '''needle''' &nbsp; to make the search &nbsp; ''case insensitive''.
<langsyntaxhighlight lang="rexx">/*REXX program searches a collection of strings (an array of periodic table elements).*/
/*───────────────names of the first 200 elements of the periodic table.─────────────*/
_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium'
Line 3,414 ⟶ 3,789:
else say needle "wasn't found in the haystack!"
return 0 /*indicates the needle wasn't found. */
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
haystack = ["alpha","bravo","charlie","delta","echo","foxtrot","golf",
"hotel","india","juliet","kilo","lima","mike","needle",
Line 3,436 ⟶ 3,811:
if !=index see " last found at index " + last + nl
else see "not found" + nl ok
</syntaxhighlight>
</lang>
Output:
<pre>
first found at index : 14
last found at index : 22
</pre>
 
=={{header|RPL}}==
{{works with|HP|48G}}
{ "Zig" "Zag" "Zig" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo" } '<span style="color:green">HAYSTACK</span>' STO
≪ → up
≪ <span style="color:green">HAYSTACK</span>
'''IF''' up NOT '''THEN''' REVLIST '''END'''
'''IF''' SWAP POS '''THEN'''
LASTARG
'''ELSE '''
"LOOKHAY Error:
Needle not found" DOERR
'''END'''
≫ ≫ '<span style="color:blue">LOOKHAY</span>' STO
 
"Bush" 1 <span style="color:blue">LOOKHAY</span>
"Bush" 0 <span style="color:blue">LOOKHAY</span>
{{out}}
<pre>
2: 6
1: 2
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)
 
%w(Bush Washington).each do |needle|
Line 3,452 ⟶ 3,850:
raise "#{needle} is not in haystack\n"
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,462 ⟶ 3,860:
 
'''Extra credit'''
<langsyntaxhighlight lang="ruby">haystack.each do |item|
last = haystack.rindex(item)
if last > haystack.index(item)
Line 3,469 ⟶ 3,867:
end
end
#=> Bush last appears at index 7</langsyntaxhighlight>
or
<langsyntaxhighlight lang="ruby">multi_item = haystack.each_index.group_by{|idx| haystack[idx]}.select{|key, val| val.length > 1}
# multi_item is => {"Bush"=>[4, 7]}
multi_item.each do |key, val|
puts "#{key} appears at index #{val}"
end
#=> Bush appears at index [4, 7]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<lang runbasic>haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$ = "Zag Wally Bush Chicken"
 
while word$(needle$,i+1," ") <> ""
i = i + 1
thisNeedle$ = word$(needle$,i," ") + " "
j = instr(haystack$,thisNeedle$)
k1 = 0
k = instr(haystack$,thisNeedle$,j+1)
while k <> 0
k1 = k
k = instr(haystack$,thisNeedle$,k+1)
wend
if j <> 0 then
print thisNeedle$;" located at:";j;
if k1 <> 0 then print " Last position located at:";k1;
print
else
print thisNeedle$;" is not in the list"
end if
wend</lang>
{{out}}
<pre>Zag located at:5
Wally located at:9
Bush located at:22 Last position located at:52
Chicken is not in the list</pre>
 
=={{header|Rust}}==
 
Rust encourages to encode possible errors in function's return type. For example, <code>position</code> returns <code>Option<usize></code>, which can be <code>None</code> or <code>Some(x)</code>.
 
<langsyntaxhighlight lang="rust">fn main() {
let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag"];
Line 3,518 ⟶ 3,887:
println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob"));
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,529 ⟶ 3,898:
===Version that panics===
 
<langsyntaxhighlight lang="rust">fn main() {
let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag"];
Line 3,537 ⟶ 3,906:
println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob").unwrap());
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,548 ⟶ 3,917:
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">variable haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo","Ronald"];
define find(needle)
Line 3,563 ⟶ 3,932:
($1, $2) = find("Ronald"); % returns 3, 9
($1, $2) = find("McDonald"); % throws ApplicationError, labelled "an exception"
</syntaxhighlight>
</lang>
 
=={{header|Sather}}==
{{trans|C_sharp}}
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
haystack :ARRAY{STR} := |"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"|;
Line 3,581 ⟶ 3,950:
end;
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 3,593 ⟶ 3,962:
not using those or similar methods might be written like this:
 
<langsyntaxhighlight lang="scala">def findNeedles(needle: String, haystack: Seq[String]) = haystack.zipWithIndex.filter(_._1 == needle).map(_._2)
def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head
def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last</langsyntaxhighlight>
 
It does raise an exception if there's no needle.
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define haystack
'("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))
 
Line 3,615 ⟶ 3,984:
(if tail
(- (length tail) 1)
(throw 'needle-missing)))))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,625 ⟶ 3,994:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
put ("apple", "banana", "cranberry" ,"durian", "eggplant", "grape", "banana", "appl", "blackberry") into fruitList
 
Line 3,643 ⟶ 4,012:
end if
end findInList
</syntaxhighlight>
</lang>
Note: Sensetalk indexes from 1
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
 
%w(Bush Washington).each { |needle|
Line 3,656 ⟶ 4,025:
die "#{needle} is not in haystack";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,663 ⟶ 4,032:
</pre>
Extra credit:
<langsyntaxhighlight lang="ruby">var haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
say haystack.last_index{|item| item == "Bush"};</langsyntaxhighlight>
{{out}}
<pre>
Line 3,671 ⟶ 4,040:
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">define: #haystack -> ('Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' splitWith: $,).
{'Washington'. 'Bush'} do: [| :needle |
(haystack indexOf: needle)
Line 3,679 ⟶ 4,048:
lastIndex: (haystack lastIndexOf: word).
lastIndex isNotNil /\ (lastIndex > firstIndex) ifTrue:
[inform: 'last occurrence of ' ; word ; ' is at index ' ; lastIndex]]].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}{{works with|Smalltalk/X}}
Notice: Smalltalk indexes start at 1.
<langsyntaxhighlight lang="smalltalk">| haystack |
haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
{ 'Washington' . 'Bush' } do: [:word |
Line 3,698 ⟶ 4,067:
('last occurence of %1 is at index %2' % { word . l }) displayNl ]
]
].</langsyntaxhighlight>
the above example did not raise an exception; the following does (a handler has been added to proceed for more search words):
{{works with|Smalltalk/X}}
Notice: the code below uses the ST/X embedded-expression-string extension.
<langsyntaxhighlight lang="smalltalk">| haystack |
haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
[
Line 3,723 ⟶ 4,092:
'but I don''t care and proceed...' printCR.
ex proceed.
]</langsyntaxhighlight>
{{out}}
<pre>not found exception raised for: Washington
Line 3,732 ⟶ 4,101:
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun find_index (pred, lst) = let
fun loop (n, []) = NONE
| loop (n, x::xs) = if pred x then SOME n
Line 3,746 ⟶ 4,115:
SOME i => print (Int.toString i ^ " " ^ needle ^ "\n")
| NONE => print (needle ^ " is not in haystack\n"))
["Washington", "Bush"];</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<langsyntaxhighlight lang="swift">let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
for needle in ["Washington","Bush"] {
if let index = haystack.indexOf(needle) {
Line 3,757 ⟶ 4,126:
print("\(needle) is not in haystack")
}
}</langsyntaxhighlight>
{{works with|Swift|1.x}}
<langsyntaxhighlight lang="swift">let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
for needle in ["Washington","Bush"] {
if let index = find(haystack, needle) {
Line 3,766 ⟶ 4,135:
println("\(needle) is not in haystack")
}
}</langsyntaxhighlight>
 
The second task:
{{works with|Swift|2.x+}}
 
<langsyntaxhighlight lang="swift">
// the second part can be done several ways, but extending any Array of Comparable objects is the most generic approach
extension Array where Element : Comparable {
Line 3,794 ⟶ 4,163:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo}
foreach needle {Bush Washington} {
if {[set idx [lsearch -exact $haystack $needle]] == -1} {
Line 3,804 ⟶ 4,173:
puts "$needle appears at index $idx in the haystack"
}
}</langsyntaxhighlight>
'''Extra credit:'''
<langsyntaxhighlight lang="tcl">set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo}
foreach needle {Bush Washington} {
set indices [lsearch -all -exact $haystack $needle]
Line 3,814 ⟶ 4,183:
puts "$needle appears first at index [lindex $indices 0] and last at [lindex $indices end]"
}
}</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
Line 3,822 ⟶ 4,191:
Find multiple needles in a haystack:
 
<langsyntaxhighlight TorqueScriptlang="torquescript">function findIn(%haystack,%needles)
{
%hc = getWordCount(%haystack);
Line 3,856 ⟶ 4,225:
return %string;
}</langsyntaxhighlight>
 
How to use it:
 
<langsyntaxhighlight TorqueScriptlang="torquescript">echo(findIn("Hello world, you are quite sunny today.","quite hello somethingelse"));</langsyntaxhighlight>
 
returns:
 
<langsyntaxhighlight TorqueScriptlang="torquescript">=> "quite_4 hello_0 somethingelse_-1"</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
SET haystack="Zig'Zag'Wally'Ronald'Bush'Krusty'Charlie'Bush'Bozo"
PRINT "haystack=",haystack
Line 3,882 ⟶ 4,251:
ENDIF
RELEASE S_TABLE needle
ENDLOOP</langsyntaxhighlight>
 
{{out}}
Line 3,898 ⟶ 4,267:
{{works with|pdksh}}
{{works with|Z Shell}}
<langsyntaxhighlight lang="sh">if [ $1 ];then
haystack="Zip Zag Wally Ronald Bush Krusty Charlie Bush Bozo"
 
Line 3,912 ⟶ 4,281:
echo "The greatest index for $1 is: $greatest_index";fi
else echo $1 is absent from haystatck.;fi
else echo Must provide string to find in haystack.;fi</langsyntaxhighlight>
 
{{out}}
Line 3,925 ⟶ 4,294:
If it's not present, an exception is thrown with a diagnostic message of 'missing'.
The search is expressed by <code>~|</code>, the built-in distributing filter operator.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
indices = ||<'missing'>!% ~&nSihzXB+ ~&lrmPE~|^|/~& num</langsyntaxhighlight>
The explanation is somewhat longer than the program.
* The <code>^|</code> operator takes a right operand consisting of a pair of functions <math>(f,g)</math>, and returns a function that takes a pair <math>(x,y)</math> to the result <math>(f(x),g(y))</math>.
Line 3,952 ⟶ 4,321:
 
Test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nW
 
test = indices/'bar' <'foo','bar','baz','bar'></langsyntaxhighlight>
{{out}}
<pre>(1,3)</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Function IsInArray(stringToBeFound As Variant, arr As Variant, _
Optional start As Integer = 1, Optional reverse As Boolean = False) As Long
'Adapted from https://stackoverflow.com/questions/12414168/use-of-custom-data-types-in-vba
Line 3,990 ⟶ 4,359:
End If
Next i
End Sub</langsyntaxhighlight>{{out}}<pre>Washington not found in haystack.
Bush is at position 5. And last position is 8.</pre>
 
=={{header|VBScript}}==
Shamelessly derived from the BASIC version.
<syntaxhighlight lang="vb">
<lang vb>
data = "foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt," &_
"foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc," &_
Line 4,024 ⟶ 4,393:
End If
Loop
</syntaxhighlight>
</lang>
{{out}}
<pre>F:\VBScript>cscript /nologo search_a_list.vbs
Line 4,046 ⟶ 4,415:
 
F:\VBScript></pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Rust">
const (
haystacks = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"]
needles = ["Bush", "washington", "Wally"]
)
 
fn main() {
mut list, mut index, mut count, mut missing := "", "", "", ""
for nee in needles {
for idx, hay in haystacks {
if nee == hay {
count = "${haystacks.str().count(nee)}"
if list.contains(nee) {
index += ", ${idx}"
list = "Found: ${nee}; Index: ${index}; Count: ${count}\n"
}
else {
index = "${idx}"
list += "Found: ${nee}; Index: ${index}; Count: ${count}\n"
}
}
}
if nee !in haystacks && !missing.contains(nee) {missing += "Missing: ${nee}\n"}
}
list += missing
println(list.all_before_last('\n'))
}
</syntaxhighlight>
 
{{out}}
<pre>
Found: Bush; Index: 4, 7; Count: 2
Found: Wally; Index: 2; Count: 1
Missing: washington
</pre>
 
=={{header|Wart}}==
Wart uses the function <code>pos</code> to search a list for an element.
Here's how it's implemented:
<langsyntaxhighlight lang="python">def (pos x (seq | (head ... tail)) n)
default n :to 0
if seq
if (head = x)
n
(pos x tail n+1)</langsyntaxhighlight>
 
{{out|Usage}}
Line 4,065 ⟶ 4,471:
=={{header|Wren}}==
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "./seq" for Lst
 
var find = Fn.new { |haystack, needle|
Line 4,086 ⟶ 4,492:
System.print("The needle is %(needle).")
find.call(haystack, needle)
}</langsyntaxhighlight>
 
{{out}}
Line 4,114 ⟶ 4,520:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">\Based on C example:
include c:\cxpl\stdlib; \provides StrCmp routine, etc.
int Haystack; \('int' is used instead of 'char' for 2D array)
Line 4,138 ⟶ 4,544:
Text(0, "First index for Zag: "); IntOut(0, Search("Zag", true)); CrLf(0);
Text(0, "Last index for Zag: "); IntOut(0, Search("Zag", false)); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,147 ⟶ 4,553:
Last index for Zag: 9
</pre>
 
=={{header|Yabasic}}==
<lang Yabasic>list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
 
dim item$(1)
 
n = token(list$, item$(), ",")
 
line input "Enter string to search: " line$
for i = 1 to n
if line$ = item$(i) then
if not t print "First index for ", line$, ": ", i
t = i
j = j + 1
end if
next
 
if t = 0 then
print "String not found in list"
else
if j > 1 print "Last index for ", line$, ": ", t
end if</lang>
 
=={{header|Yorick}}==
<langsyntaxhighlight lang="yorick">haystack = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"];
needles = ["Bush", "Washington"];
for(i = 1; i <= numberof(needles); i++) {
Line 4,180 ⟶ 4,564:
if(numberof(w) > 1)
write, format="Needle %s appears last at index %d\n", needles(i), w(0);
}</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">L("Krusty","Charlie","Bozo","Bozo").index("Charlie") //--> 1
L("Krusty","Charlie","Bozo","Bozo").index("fred") //--> throws index error</langsyntaxhighlight>
Find last needle:
<langsyntaxhighlight lang="zkl">haystack:=L("Krusty","Charlie","Bozo","Bozo");
haystack.filterNs('==("Bozo"))[-1]; // -->3, indexError if not found
haystack.len() - 1 - haystack.reverse().index("Bozo"); // or this</langsyntaxhighlight>
Use a bit bucket of ASCIIZ strings
<langsyntaxhighlight lang="zkl">haystack:=Data(0,String,"Krusty","Charlie","Bozo","Bozo");
if((n:=haystack.findString("Charlie")) != Void) n else throw(Exception.IndexError);
//-->7</langsyntaxhighlight>
162

edits