Search a list: Difference between revisions

Add Ecstasy example
m (→‎{{header|RPL}}: one-size-fits-all solution)
(Add Ecstasy example)
 
(4 intermediate revisions by 4 users not shown)
Line 44:
(defun index-of (e xs)
(index-of-r e xs 0))</syntaxhighlight>
 
=={{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!}}==
Line 1,442 ⟶ 1,466:
println(find("Ronald")) # prints 3
println(find("McDonald")) # will throw</syntaxhighlight>
 
=={{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 :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,452 ⟶ 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 4,400 ⟶ 4,471:
=={{header|Wren}}==
{{libheader|Wren-seq}}
<syntaxhighlight lang="ecmascriptwren">import "./seq" for Lst
 
var find = Fn.new { |haystack, needle|
162

edits