Search a list: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 22:
{{trans|Python}}
<
L(needle) (‘Washington’, ‘Bush’)
Line 28:
print(haystack.index(needle)‘ ’needle)
X.catch ValueError
print(needle‘ is not in haystack’)</
{{out}}
Line 37:
=={{header|ACL2}}==
<
(cond ((endp xs) nil)
((equal e (first xs)) i)
Line 43:
(defun index-of (e xs)
(index-of-r e xs 0))</
=={{header|Action!}}==
<
INT FUNC Search(PTR ARRAY texts INT count CHAR ARRAY text)
Line 85:
Test(texts,7,"Thursday")
Test(texts,7,"Weekend")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Search_a_list.png Screenshot from Atari 8-bit computer]
Line 97:
=={{header|ActionScript}}==
===Using the built-in Error class===
<
function lowIndex(listToSearch:Vector.<String>, searchString:String):int
{
Line 112:
throw new Error("String not found: " + searchString);
return index;
}</
===Using a custom error===
In StringNotFoundError.as:
<
public class StringNotFoundError extends Error {
public function StringNotFoundError(message:String) {
Line 122:
}
}
}</
In a separate file:
<
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 141:
return index;
}
</syntaxhighlight>
=={{header|Ada}}==
<
with Ada.Text_IO; use Ada.Text_IO;
Line 185:
Check ("Washington");
Check ("Bush");
end Test_List_Index;</
{{out}}
<pre>
Line 193:
=={{header|Aime}}==
<
search(list l, text s)
{
Line 219:
return 0;
}</
{{out}}
<pre>Bush is at 4
Line 231:
{{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}}
<
FILE needle exception; STRING ref needle;
Line 254:
end on value error: reset(needle exception)
OD
)</
{{out}}
<pre>
Line 266:
{{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}}
<
PROC index = ([]STRING hay stack, STRING needle)INT:(
Line 293:
FI
OD
)</
{{out}}
<pre>
Line 301:
=={{header|Arturo}}==
<
loop [Bush Washington] 'needle [
Line 308:
if? empty? i -> panic ~"|needle| is not in haystack"
else -> print [i needle]
]</
{{out}}
Line 316:
=={{header|AutoHotkey}}==
<
needle = bush, washington
Loop, Parse, needle, `,
Line 324:
Else
MsgBox % A_LoopField . " not in haystack"
}</
=={{header|AWK}}==
Line 332:
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!)
<
BEGIN {
# create the array, using the word as index...
Line 352:
print "Washington is not here";
}
}</
=={{header|BASIC}}==
{{works with|QBasic}}
<
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 385:
EXIT DO
END IF
LOOP</
{{out}}
Line 410:
==={{header|IS-BASIC}}===
<
110 STRING A$(1 TO 55)*8
120 FOR I=1 TO 55
Line 426:
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</
=={{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.
<
setlocal enabledelayedexpansion
Line 469:
%==We are done==%
echo.
pause</
{{Out}}
<pre>"foo": Found 6 times. First instance:[1] Last instance:[35].
Line 481:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
\ "hotel","india","juliet","kilo","lima","mike","needle", \
Line 501:
ELSE
ERROR 100, "Not found"
ENDIF</
=={{header|BQN}}==
Line 509:
The given <code>IndexOf</code> function is written to satisfy question requirements (throwing exceptions), and it is not recommended for use in production.
<
IndexOf ← {
Line 518:
•Show list ⊐ "Wally"‿"Hi" # intended
•Show list IndexOf "Wally"
list IndexOf "Hi"</
2
! "Error: 'Hi' Not found in list"
Line 526:
list IndexOf "Hi"
^^^^^^^</
=={{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.
<
occurrences in the haystack and print the needle
: ?list
Line 552:
| out$"No word occurs more than once."
)
);</
{{out}}
<pre>The word 'haystack' occurs at 1-based index 14
Line 559:
=={{header|Burlesque}}==
<
3</
If you want all indices:
<
{3 5}</
=={{header|C}}==
<
#include <string.h>
Line 608:
printf("Last index for Zag: %d\n", search_last_needle("Zag", haystack));
return 0;
}</
{{out}}
Line 618:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
Line 632:
}
}
}</
=={{header|C++}}==
Line 639:
The following code shows three different ways to solve the task.
<
#include <algorithm>
#include <iterator>
Line 750:
std::cout << "\n=== Word not occuring at all ===\n";
test("Goofy");
}</
{{out}} (note that in C++, indices start at 0):
Line 782:
=== C++11 ===
{{works with|g++ version 4.8.4, clang++ version 3.4| "-std=c++11" }}
<
* list class
* initialization strings
Line 895:
} // main
/* end */</
{{out}}
<pre>
Line 905:
=={{header|Ceylon}}==
<
value haystack = [
"Zig", "Zag", "Wally", "Ronald", "Bush",
Line 915:
assertEquals(firstIdx, 4);
assertEquals(lastIdx, 7);
}</
=={{header|Clojure}}==
<
(let [idx (.indexOf haystack "Zig")]
(if (neg? idx)
(throw (Error. "item not found."))
idx)))</
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}}==
<
% The collection needs to provide `indexes' and `fetch';
% the element type needs to provide `equal'.
Line 958:
end
end
end start_up</
{{out}}
<pre>Ronald: 4
Line 966:
=={{header|COBOL}}==
<
IDENTIFICATION DIVISION.
PROGRAM-ID. Search-List.
Line 1,028:
DISPLAY "Found last of " needle " at " haystack-index "."
END-IF
.</
{{out}}
Line 1,038:
=={{header|Common Lisp}}==
<
(dolist (needle '(Washington Bush))
(let ((index (position needle haystack)))
(if index
(progn (print index) (princ needle))
(progn (print needle) (princ "is not in haystack"))))))</
{{out}}
<pre>
Line 1,050:
</pre>
The position function solves this task elegantly.
<
CL-USER> (defparameter *list* '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo))
*LIST*
Line 1,058:
7
CL-USER> (position 'Washington *list*)
NIL</
=={{header|D}}==
<
auto firstIndex(R, T)(R hay, T needle) {
Line 1,078:
assert(firstIndex(h, "Bush") == 4);
assert(lastIndex(h, "Bush") == 7);
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,117:
list.Free;
end;
end.</
{{out}}
<pre>
Line 1,126:
=={{header|DWScript}}==
<
function Find(what : String) : Integer;
Line 1,136:
PrintLn(Find("Ronald")); // 3
PrintLn(Find('McDonald')); // exception</
=={{header|E}}==
<
/** meet the 'raise an exception' requirement */
Line 1,151:
println(find("Ronald")) # prints 3
println(find("McDonald")) # will throw</
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
Line 1,175:
}
}
}</
=={{header|Elixir}}==
<
Enum.each(~w(Bush Washington), fn needle ->
Line 1,184:
if index, do: (IO.puts "#{index} #{needle}"),
else: raise "#{needle} is not in haystack\n"
end)</
{{out}}
Line 1,201:
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.
<
-export([main/0]).
Line 1,215:
print({Needle, undefined}) -> io:format("~s is not in haystack.~n",[Needle]);
print({Needle, Pos}) -> io:format("~s at position ~p.~n",[Needle,Pos]).</
{{out}}
Line 1,229:
The procedure can be made into a function to search with other strings, take user input and give output of the searched haystack.
<
include std/search.e
include std/console.e
Line 1,276:
--wait for user to press a key to exit
any_key()
</syntaxhighlight>
{{out}}
Line 1,308:
=={{header|F_Sharp|F#}}==
<
// A System.Collections.Generic.KeyNotFoundException
// is raised, if the predicate does not evaluate to
// true for any list element.</
=={{header|Factor}}==
<
'[ _ = ] find drop [ "Not found" throw ] unless* ; inline
: find-last-index ( seq elt -- i )
'[ _ = ] find-last drop [ "Not found" throw ] unless* ; inline</
( scratchpad ) { "a" "b" "c" "d" "c" } "c" find-index .
Line 1,327:
=={{header|Forth}}==
{{works with|4tH|3.61.5}}
<
create haystack
Line 1,337:
;
s" Washington" haystack s" Bush" haystack</
Line 1,344:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<
include FMS-SILib.f
Line 1,373:
s" Hillary" haystack LastIndexOf . \ => 7
s" Washington" haystack needleIndex . \ => aborted: Not found
</syntaxhighlight>
=={{header|Fortran}}==
<
implicit none
Line 1,411:
end subroutine find_needle
end program main</
=={{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:
<
' Works FB 1.05.0 Linux Mint 64
Line 1,475:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,488:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=7729d65f8af3f128db6c6992c5f74e98 Click this link to run this code]'''
<
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Line 1,503:
Print sOutput
End</
Output:
<pre>
Line 1,510:
=={{header|GAP}}==
<
haystack := Eratosthenes(10000);;
needle := 8999;;
Line 1,536:
# 1
LastPosition(a, 0);
# 97</
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>)
<
var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty",
Line 1,554:
"zork", "gork", "bork", "sodium", "phosphorous", "californium",
"copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper",
"helium", "sulfur"}</
===Linear search===
<
import "fmt"
Line 1,621:
}
return -1
}</
{{out}}
<pre>
Line 1,633:
===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.
<
import "fmt"
Line 1,645:
fmt.Println(n, m[n])
}
}</
{{out}}
<pre>
Line 1,654:
=={{header|Groovy}}==
<
def needles = ["Washington","Bush","Wally"]
needles.each { needle ->
Line 1,666:
println "Last index: " + lastindex + " " + needle
}
}</
{{out}}
Line 1,679:
=={{header|Haskell}}==
Libraries and data:
<
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
needles = ["Washington","Bush"]</
I use 'lambda' notation for readability.
:Find 'just' an index:
<
[("Washington",Nothing),("Bush",Just 4)]</
Want to know if there are there more Bushes hiding in the haystack?
<
[("Washington",[]),("Bush",[4,7])]</
To be complete. Here is the 'point free' version of the task:
<
[("Washington",Nothing),("Bush",Just 4)]</
=={{header|HicEst}}==
<
CHARACTER needle*10
Line 1,712:
WRITE(ClipBoard) "Last ", needle, "found in position ", last
! Last bush found in position 8
ENDIF</
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">
link lists
Line 1,740:
every i := p!arglist
return \i
end</
{{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
<
local i
Line 1,750:
if lst[i] === x then suspend i
end</
{{out}}
Line 1,769:
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.
<
List firstIndex := method(obj,
indexOf(obj) ifNil(NotFound raise)
Line 1,794:
writeln(needle," is not in haystack")
)pass
)</
{{out}}
<pre>firstIndex("Washington"): Washington is not in haystack
Line 1,807:
For example:
<
Needles =: ;:'Washington Bush'
Line 1,813:
9 4
Haystack i: Needles NB. last positions
9 7</
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,821:
<code>e.</code> finds whether items are members of a set, returning a bitmask to select the members:
<
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</
<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).
<
1 2 4 9 6
(;:'eight five four nine one seven six three two') I. ;:'two three five sixty'
8 7 1 7</
To format output similar to the other examples, one might write:
<
Washington is not in haystack
Bush 4</
Or broken up into components and defined as a verb/function for finding the last positions:
<
idxmissing=: #@[ I.@:= ] NB. indices of items not found
fmtdata=: 8!:0@] NB. format atoms as boxed strings
Line 1,847:
Haystack findLastIndex Needles NB. usage
Washington is not in haystack
Bush 7</
To elaborate a bit: Array-oriented languages (like J) consume the input and produce the output ''in toto''.
Line 1,865:
=={{header|Java}}==
for Lists, they have an indexOf() method:
<
import java.util.Arrays;
Line 1,876:
else
System.out.println(index + " " + needle);
}</
for arrays, you have to do it manually:
<
String[] haystack = { "Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"};
Line 1,889:
else
System.out.println(index + " " + needle);
}</
{{out}}
Line 1,898:
=={{header|JavaScript}}==
<
var needles = ['Bush', 'Washington']
Line 1,913:
else
throw needles[i] + " does not appear in the haystack"
}</
The following {{works with|JavaScript|1.6}}:
<
var idx = haystack.indexOf(needle);
if (idx == -1)
Line 1,933:
break
}
}</
Or, generalising enough (in ES5) to allow for varying definitions of the type of match we are looking for:
<
function findIndex(fnPredicate, list) {
Line 1,984:
})
}
})();</
Output:
<syntaxhighlight lang="javascript">{
"first": [
[
Line 2,009:
]
]
}</
=={{header|jq}}==
Line 2,016:
In the following, the output is shown after the "# =>":
<syntaxhighlight lang="jq">
["a","b","c"] | index("b")
# => 1
Line 2,033:
["a","b","c","b","d"] | indices("b")[-1]
# => 3</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
@show indexin(["yes"], ["no", "?", "yes", "maybe", "yes"])
@show findin(["no", "?", "yes", "maybe", "yes"], ["yes"])
@show find(["no", "?", "yes", "maybe", "yes"] .== "yes")</
{{out}}
Line 2,050:
=={{header|K}}==
<
Needles:("Washington";"Bush")
{:[y _in x;(y;x _bin y);(y;"Not Found")]}[Haystack]'Needles </
{{out}}
<
"Not Found")
("Bush"
4))</
Additional:
Line 2,064:
Here we use the dyadic verb _sm (string match) instead of _bin (binary search).
<
Needles2:Needles,,"Zag"
{+(x;{:[#&x;,/?(*&x;*|&x);"Not found"]}'+x _sm/:y)}[Needles2;Haystack2]</
{{out}}
<
"Not found")
("Bush"
4 9)
("Zag"
1))</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 2,090:
index = haystack.indexOf(needle)
if (index == -1) throw Exception("$needle does not occur in the list")
}</
{{out}}
Line 2,104:
=={{header|Lang5}}==
<
: find-index
2dup eq length iota swap select swap drop
Line 2,112:
: ==>search apply ;
['hello 'code] 'haystack ==>search .</
{{out}}
<pre>[ hello is not in haystack
Line 2,121:
Lasso arrays have a findindex method which returns all matching indexes. [http://lassoguide.com/operations/containers.html?#array]
<
#haystack->findindex('Bush')->first // 5
Line 2,129:
handle_error => {^ error_msg ^}
fail_if(not #haystack->findindex('Washington')->first,'Washington is not in haystack.')
^}</
{{out}}
Line 2,138:
=={{header|Liberty BASIC}}==
<
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
Line 2,174:
else
print needle$;" found at index ";k
end if</
=={{header|Lingo}}==
<
needle = "oranges"
Line 2,187:
end if
-- "needle found at index 2"</
=={{header|Lisaac}}==
<
haystack := "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo".split;
"Washington Bush".split.foreach { needle : STRING;
Line 2,202:
" is not in haystack\n".print;
};
};</
=={{header|Logo}}==
<
if empty? :list [(throw "NOTFOUND 0)]
if equal? :item first :list [output 1]
Line 2,217:
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</
=={{header|Lua}}==
<
item = io.read()
Line 2,226:
for i,v in ipairs(list)
if v == item then print(i) end
end</
=={{header|M2000 Interpreter}}==
Line 2,232:
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">
Module Checkit {
Flush ' empty stack
Line 2,269:
}
CheckIt
</syntaxhighlight>
Extra-Extra: Find all occurrences displaying the indexes for each one.
<syntaxhighlight lang="m2000 interpreter">
Module CheckThis {
Inventory Queue Haystack= "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt"
Line 2,299:
}
CheckThis
</syntaxhighlight>
=={{header|Maple}}==
<
occurences := ListTools:-SearchAll(needle,haystack):
try
Line 2,311:
catch :
print("Erros: Needle not found in the haystack"):
end try:</
{{Out|Examples}}
needle := "Washington":
Line 2,321:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This examples shows you the first appearance, the last appearance, and all appearances (as a list):
<
needle = "Zag";
first = Position[haystack,needle,1][[1,1]]
last = Position[haystack,needle,1][[-1,1]]
all = Position[haystack,needle,1][[All,1]]</
gives back:
<syntaxhighlight lang="mathematica">2
7
{2,7}</
=={{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:<
searchCollection.m:
<
%firstLast is a string containing either 'first' or 'last'. The 'first'
Line 2,347:
assert(~isempty(index),['The string ''' searchItem ''' does not exist in this collection of strings.']);
end</
{{out}}
<
>> searchCollection(list,'c','first')
Line 2,365:
>> searchCollection(list,'g','last')
??? Error using ==> searchCollection at 11
The string 'g' does not exist in this collection of strings.</
=={{header|Maxima}}==
<
needle: "Zag";
Line 2,376:
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));</
{{out|Usage}}
Line 2,393:
=={{header|MAXScript}}==
<
for needle in #("Washington","Bush") do
Line 2,407:
format "% %\n" index needle
)
)</
{{out}}
<
5 Bush</
=={{header|Nanoquery}}==
{{trans|Python}}
<
append $haystack "Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie"
append $haystack "Bush" "Bozo"
Line 2,431:
println $needle + " is not in haystack"
end
end for</
{{out}}
<pre>Washington is not in haystack
Line 2,437:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 2,542:
end needle
return</
{{out}}
<pre>
Line 2,565:
=={{header|Nim}}==
<
for needle in ["Bush", "Washington"]:
Line 2,572:
echo f, " ", needle
else:
raise newException(ValueError, needle & " not in haystack")</
{{out}}
Line 2,580:
=={{header|Objeck}}==
<
class Test {
Line 2,595:
};
}
}</
=={{header|Objective-C}}==
{{works with|Objective-C|2.0+}}
<
for (id needle in @[@"Washington",@"Bush"]) {
int index = [haystack indexOfObject:needle];
Line 2,606:
else
NSLog(@"%i %@", index, needle);
}</
=={{header|OCaml}}==
<
let rec loop n = function
[] -> raise Not_found
Line 2,631:
Washington is not in haystack
4 Bush
- : unit = ()</
=={{header|Oforth}}==
Line 2,637:
indexOf returns null if an object is not into a collection, not an exception.
<
haystack indexOf(needle) dup ifNull: [ drop ExRuntime throw("Not found", needle) ] ;
Line 2,644:
needleIndex("Bush", Haystack) println
Haystack lastIndexOf("Bush") println
needleIndex("Washington", Haystack) println</
{{out}}
Line 2,657:
For ordered collections, this will always be the first item.
For unordered collections, the index returned is undetermined.
<
a = .array~of(1,2,3,4,4,5)
say a~index(4)
Line 2,675:
d["foo"] = 4
d["bar"] = 4
say d~index(4)</
=={{header|Oz}}==
Line 2,681:
(the operation is quite inefficient, after all).
A possible implementation:
<
%% Lazy list of indices of Y in Xs.
fun {Indices Y Xs}
Line 2,704:
{Show {List.last {Indices "Bush" Haystack}}}
{Show {Index "Washington" Haystack}} %% throws</
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<
my(i=setsearch(v,n));
if(i,
Line 2,716:
);
i
};</
=={{header|Pascal}}==
Line 2,722:
=={{header|Perl}}==
<
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
Line 2,734:
print "$needle is not in haystack\n";
}
}</
{{out}}
<pre>
Line 2,742:
You could install a non-standard module List::MoreUtils:
<
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
Line 2,754:
print "$needle is not in haystack\n";
}
}</
Alternatively, if you need to do this a lot, you could create a hash table mapping values to indices in the haystack:
<
my %haystack_indices;
Line 2,769:
print "$needle is not in haystack\n";
}
}</
{{out}}
<pre>
Line 2,778:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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>
Line 2,786:
<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>
<!--</
=={{header|Phixmonti}}==
<
"soap" "methamphetamine" "severed cat heads" "cup"
pstack
Line 2,814:
endif
endif
drop</
Other solution with syntactic sugar for list construction.
<
0 var acum
Line 2,839:
search
endwhile
</syntaxhighlight>
=={{header|PHP}}==
<
foreach (array("Washington","Bush") as $needle) {
Line 2,850:
else
echo "$i $needle\n";
}</
{{out}}
<pre>
Line 2,861:
And Picat is 1-based.
<
go =>
Line 2,894:
if Ixs == [] then
throw $error(search_list_all(Needle),not_found)
end.</
{{out}}
Line 2,907:
Note that in PicoLisp all indexes are one-based
(the first element has the position '1')
<
(- (length Lst) (index Item (reverse Lst)) -1) )
Line 2,916:
(findNeedle index 'Washington Lst)
(findNeedle index 'Bush Lst)
(findNeedle lastIndex 'Bush Lst) )</
{{out}}
<pre>Washington not found
Line 2,923:
=={{header|PL/I}}==
<
declare haystack (0:9) character (200) varying static initial
('apple', 'banana', 'celery', 'dumpling', 'egg', 'flour',
Line 2,943:
signal condition(missing_needle);
return (lbound(haystack,1)-1);
end search;</
=={{header|Plain English}}==
<
Start up.
Make an example haystack.
Line 2,983:
Put the bale's next into the bale.
Bump the count.
Repeat.</
{{out}}
<pre>
Line 2,992:
{{works with|PowerBASIC for Windows}}
<
DIM haystack(54) AS STRING
ARRAY ASSIGN haystack() = "foo", "bar", "baz", "quux", "quuux", "quuuux", _
Line 3,031:
END IF
LOOP
END FUNCTION</
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
function index($haystack,$needle) {
$index = $haystack.IndexOf($needle)
Line 3,048:
index $haystack "house"
index $haystack "paragraph"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 3,057:
===PowerShell Extra credit===
The -Verbose switch is available to any advanced function.
<syntaxhighlight lang="powershell">
function Find-Needle
{
Line 3,115:
$haystack = @("word", "phrase", "preface", "title", "house", "line", "chapter", "page", "book", "house")
</syntaxhighlight>
<syntaxhighlight lang="powershell">
Find-Needle "house" $haystack
</syntaxhighlight>
{{Out}}
<pre>
4
</pre>
<syntaxhighlight lang="powershell">
Find-Needle "house" $haystack -Verbose
</syntaxhighlight>
{{Out}}
<pre>
Line 3,131:
4
</pre>
<syntaxhighlight lang="powershell">
Find-Needle "house" $haystack -LastIndex -Verbose
</syntaxhighlight>
{{Out}}
<pre>
Line 3,139:
9
</pre>
<syntaxhighlight lang="powershell">
Find-Needle "title" $haystack -LastIndex -Verbose
</syntaxhighlight>
{{Out}}
<pre>
Line 3,147:
3
</pre>
<syntaxhighlight lang="powershell">
Find-Needle "something" $haystack -Verbose
</syntaxhighlight>
{{Out}}
<pre>
Line 3,158:
=={{header|Prolog}}==
Works with SWI-Prolog
<
L = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"],
Line 3,181:
my_write(Name) :-
writef(' %s', [Name]).
</syntaxhighlight>
{{out}}
Line 3,194:
=={{header|PureBasic}}==
<
NewList Straws.s()
Define Straw$, target$="TBA"
Line 3,229:
haystack:
Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection</
=={{header|Python}}==
<
for needle in ("Washington","Bush"):
Line 3,238:
print haystack.index(needle), needle
except ValueError, value_error:
print needle,"is not in haystack"</
{{out}}
<pre>
Line 3,248:
The following shows the default information given
when the exception is not captured in the program:
<
>>> haystack.index('Bush')
4
Line 3,256:
haystack.index('Washington')
ValueError: list.index(x): x not in list
>>></
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.
<
return len(haystack)-1 - haystack[::-1].index(needle)
Line 3,271:
assert hi == haystack.index(n), "index == hi_index if needle occurs only once"
>>></
=={{header|R}}==
<
{
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)
}</
Example usage:
<
haystack2 <- c("no", "sewing", "equipment", "in", "here")
haystack3 <- c("oodles", "of", "needles", "needles", "needles", "in", "here")
Line 3,288:
find.needle(haystack2) # error
find.needle(haystack3) # 3
find.needle(haystack3, needle="needles", ret=TRUE) # 3 5</
=={{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.
<
(for/first ([(x i) (in-indexed xs)]
#:when (equal? x y))
i))</
If the last index of an element is needed, for/last is used:
<
(for/last ([(x i) (in-indexed xs)]
#:when (equal? x y))
i))</
Both index and index-last can handle any sequence such as lists, vectors, sets etc.
Let us test with a linked list:
<
(for/list ([needle '("Bender" "Bush")])
Line 3,312:
(for/list ([needle '("Bender" "Bush")])
(index-last haystack needle))</
{{out}}
<pre>
Line 3,323:
{{works with|Rakudo Star|2016.07}}
<syntaxhighlight lang="raku"
for <Washington Bush> -> $needle {
say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }";
}</
{{out}}
Line 3,338:
Or, including the "extra credit" task:
{{works with|Rakudo Star|2016.07}}
<syntaxhighlight lang="raku"
for <Washingston Bush> -> $needle {
Line 3,350:
say "$needle -- not in haystack";
}
}</
{{out}}
Line 3,364:
<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"
my %index;
Line 3,371:
for <Washington Bush> -> $needle {
say "$needle -- { %index{$needle} // 'not in haystack' }";
}</
=={{header|REBOL}}==
<
Title: "List Indexing"
URL: http://rosettacode.org/wiki/Index_in_a_list
Line 3,411:
reform [needle "=>" locate/largest haystack needle]
]
]</
{{out}}
Line 3,430:
<br><br>The haystack items may have any character, including blanks.
<br>A ''null'' value isn't allowed in this method of representing values.
<
hay.= /*initialize the haystack collection. */
hay.1 = 'sodium'
Line 3,458:
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. */</
===version 2===
Line 3,466:
this counter may be any sufficiently high number.
<br><br>The array may be out of order (but not recommended!).
<
hay.0 = 1000 /*safely indicate highest item number. */
hay.200 = 'Binilnilium'
Line 3,499:
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. */</
===version 3===
Line 3,514:
<br>variable names. Therefore, there shouldn't be any REXX variable names (in this
<br>program) that have a leading underscore ('''_''').
<
hay.=0 /*initialize the haystack collection. */
hay._sodium = 1
Line 3,542:
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. */</
===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 '''haystack''' and the '''needle''' to make the search ''case insensitive''.
<
/*───────────────names of the first 200 elements of the periodic table.─────────────*/
_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium'
Line 3,583:
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. */</
=={{header|Ring}}==
<
haystack = ["alpha","bravo","charlie","delta","echo","foxtrot","golf",
"hotel","india","juliet","kilo","lima","mike","needle",
Line 3,605:
if !=index see " last found at index " + last + nl
else see "not found" + nl ok
</syntaxhighlight>
Output:
<pre>
Line 3,613:
=={{header|Ruby}}==
<
%w(Bush Washington).each do |needle|
Line 3,621:
raise "#{needle} is not in haystack\n"
end
end</
{{out}}
<pre>
Line 3,631:
'''Extra credit'''
<
last = haystack.rindex(item)
if last > haystack.index(item)
Line 3,638:
end
end
#=> Bush last appears at index 7</
or
<
# 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]</
=={{header|Run BASIC}}==
<
needle$ = "Zag Wally Bush Chicken"
Line 3,668:
print thisNeedle$;" is not in the list"
end if
wend</
{{out}}
<pre>Zag located at:5
Line 3,679:
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>.
<
let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag"];
Line 3,687:
println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob"));
}
</syntaxhighlight>
{{out}}
Line 3,698:
===Version that panics===
<
let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag"];
Line 3,706:
println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob").unwrap());
}
</syntaxhighlight>
{{out}}
Line 3,717:
=={{header|S-lang}}==
<
define find(needle)
Line 3,732:
($1, $2) = find("Ronald"); % returns 3, 9
($1, $2) = find("McDonald"); % throws ApplicationError, labelled "an exception"
</syntaxhighlight>
=={{header|Sather}}==
{{trans|C_sharp}}
<
main is
haystack :ARRAY{STR} := |"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"|;
Line 3,750:
end;
end;
end;</
=={{header|Scala}}==
Line 3,762:
not using those or similar methods might be written like this:
<
def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head
def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last</
It does raise an exception if there's no needle.
=={{header|Scheme}}==
<
'("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))
Line 3,784:
(if tail
(- (length tail) 1)
(throw 'needle-missing)))))</
{{out}}
<pre>
Line 3,794:
=={{header|SenseTalk}}==
<
put ("apple", "banana", "cranberry" ,"durian", "eggplant", "grape", "banana", "appl", "blackberry") into fruitList
Line 3,812:
end if
end findInList
</syntaxhighlight>
Note: Sensetalk indexes from 1
=={{header|Sidef}}==
<
%w(Bush Washington).each { |needle|
Line 3,825:
die "#{needle} is not in haystack";
}
}</
{{out}}
<pre>
Line 3,832:
</pre>
Extra credit:
<
say haystack.last_index{|item| item == "Bush"};</
{{out}}
<pre>
Line 3,840:
=={{header|Slate}}==
<
{'Washington'. 'Bush'} do: [| :needle |
(haystack indexOf: needle)
Line 3,848:
lastIndex: (haystack lastIndexOf: word).
lastIndex isNotNil /\ (lastIndex > firstIndex) ifTrue:
[inform: 'last occurrence of ' ; word ; ' is at index ' ; lastIndex]]].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}{{works with|Smalltalk/X}}
Notice: Smalltalk indexes start at 1.
<
haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
{ 'Washington' . 'Bush' } do: [:word |
Line 3,867:
('last occurence of %1 is at index %2' % { word . l }) displayNl ]
]
].</
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.
<
haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
[
Line 3,892:
'but I don''t care and proceed...' printCR.
ex proceed.
]</
{{out}}
<pre>not found exception raised for: Washington
Line 3,901:
=={{header|Standard ML}}==
<
fun loop (n, []) = NONE
| loop (n, x::xs) = if pred x then SOME n
Line 3,915:
SOME i => print (Int.toString i ^ " " ^ needle ^ "\n")
| NONE => print (needle ^ " is not in haystack\n"))
["Washington", "Bush"];</
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<
for needle in ["Washington","Bush"] {
if let index = haystack.indexOf(needle) {
Line 3,926:
print("\(needle) is not in haystack")
}
}</
{{works with|Swift|1.x}}
<
for needle in ["Washington","Bush"] {
if let index = find(haystack, needle) {
Line 3,935:
println("\(needle) is not in haystack")
}
}</
The second task:
{{works with|Swift|2.x+}}
<
// 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,963:
</syntaxhighlight>
=={{header|Tcl}}==
<
foreach needle {Bush Washington} {
if {[set idx [lsearch -exact $haystack $needle]] == -1} {
Line 3,973:
puts "$needle appears at index $idx in the haystack"
}
}</
'''Extra credit:'''
<
foreach needle {Bush Washington} {
set indices [lsearch -all -exact $haystack $needle]
Line 3,983:
puts "$needle appears first at index [lindex $indices 0] and last at [lindex $indices end]"
}
}</
=={{header|TorqueScript}}==
Line 3,991:
Find multiple needles in a haystack:
<
{
%hc = getWordCount(%haystack);
Line 4,025:
return %string;
}</
How to use it:
<
returns:
<
=={{header|TUSCRIPT}}==
<
SET haystack="Zig'Zag'Wally'Ronald'Bush'Krusty'Charlie'Bush'Bozo"
PRINT "haystack=",haystack
Line 4,051:
ENDIF
RELEASE S_TABLE needle
ENDLOOP</
{{out}}
Line 4,067:
{{works with|pdksh}}
{{works with|Z Shell}}
<
haystack="Zip Zag Wally Ronald Bush Krusty Charlie Bush Bozo"
Line 4,081:
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</
{{out}}
Line 4,094:
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.
<
indices = ||<'missing'>!% ~&nSihzXB+ ~&lrmPE~|^|/~& num</
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 4,121:
Test program:
<
test = indices/'bar' <'foo','bar','baz','bar'></
{{out}}
<pre>(1,3)</pre>
=={{header|VBA}}==
<
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 4,159:
End If
Next i
End Sub</
Bush is at position 5. And last position is 8.</pre>
=={{header|VBScript}}==
Shamelessly derived from the BASIC version.
<syntaxhighlight 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,193:
End If
Loop
</syntaxhighlight>
{{out}}
<pre>F:\VBScript>cscript /nologo search_a_list.vbs
Line 4,219:
Wart uses the function <code>pos</code> to search a list for an element.
Here's how it's implemented:
<
default n :to 0
if seq
if (head = x)
n
(pos x tail n+1)</
{{out|Usage}}
Line 4,234:
=={{header|Wren}}==
{{libheader|Wren-seq}}
<
var find = Fn.new { |haystack, needle|
Line 4,255:
System.print("The needle is %(needle).")
find.call(haystack, needle)
}</
{{out}}
Line 4,283:
=={{header|XPL0}}==
<
include c:\cxpl\stdlib; \provides StrCmp routine, etc.
int Haystack; \('int' is used instead of 'char' for 2D array)
Line 4,307:
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);
]</
{{out}}
Line 4,318:
=={{header|Yabasic}}==
<
dim item$(1)
Line 4,337:
else
if j > 1 print "Last index for ", line$, ": ", t
end if</
=={{header|Yorick}}==
<
needles = ["Bush", "Washington"];
for(i = 1; i <= numberof(needles); i++) {
Line 4,349:
if(numberof(w) > 1)
write, format="Needle %s appears last at index %d\n", needles(i), w(0);
}</
=={{header|zkl}}==
<
L("Krusty","Charlie","Bozo","Bozo").index("fred") //--> throws index error</
Find last needle:
<
haystack.filterNs('==("Bozo"))[-1]; // -->3, indexError if not found
haystack.len() - 1 - haystack.reverse().index("Bozo"); // or this</
Use a bit bucket of ASCIIZ strings
<
if((n:=haystack.findString("Charlie")) != Void) n else throw(Exception.IndexError);
//-->7</
|