Anonymous user
Search a list: Difference between revisions
m
→[[#ALGOL 68]]: add FOR loop version with no exception
(Adding Haskell) |
m (→[[#ALGOL 68]]: add FOR loop version with no exception) |
||
Line 1:
{{task|Text processing}}
Find the index of a string (needle) in an array of strings (haystack), or else raise an exception if the needle is missing.
If there is more then one occurrence then return smallest i such that haystack[i] = needle.
Line 34:
end "+";
Haystack : List := "Zig"+"Zag"+"
procedure Check (Needle : String) is
Line 51:
<pre>
Washington is not in
Bushat
</pre>
=={{header|ALGOL 68}}==
===Using a FORMAT "value error" exception===
FORMAT hay stack := $c("Zig","Zag","
[]STRING needles = ("Washington","Bush");
Line 80 ⟶ 81:
<pre>
Washington is not in haystack
</pre>
===Using a manual FOR loop with no exception===
[]STRING hay stack = ("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
PROC index = ([]STRING hay stack, STRING needle)INT:(
INT index;
FOR i FROM LWB hay stack TO UPB hay stack DO
index := i;
IF hay stack[index] = needle THEN
found
FI
OD;
else:
LWB hay stack - 1
EXIT
found:
index
);
[]STRING needles = ("Washington","Bush");
FOR i TO UPB needles DO
STRING needle := needles[i];
INT result = index(hay stack, needle);
IF result >= LWB hay stack THEN
printf(($d" "gl$, result, needle))
ELSE
printf(($g" "gl$,needle, "is not in haystack"))
FI
OD
Output:<pre>
Washington is not in haystack
5 Bush
</pre>
Line 87 ⟶ 120:
import Data.List
haystack=["Zig","Zag","
needles = ["Washington","Bush"]
I use 'lambda' notation for readability.
:Find 'just' an index:
*Main> map (\x -> (x,findIndex (==x) haystack)) needles
[("Washington",Nothing),("Bush",Just
Want to know if there are there more Bushes hiding in the haystack?
*Main> map (\x -> (x,findIndices (==x) haystack)) needles
[("Washington",[]),("Bush",[
To be complete. Here is the 'point free' version of the task:
import Control.Monad
Line 101 ⟶ 134:
*Main> map (ap (,) (flip findIndex haystack . (==))) needles
[("Washington",Nothing),("Bush",Just
=={{header|J}}==
Line 107 ⟶ 140:
J has a general and optimized lookup function, <tt>i.</tt>. For example:
H =: ;:'Zig Zag Wally Ronald
N =: ;:'Washington Bush'
H i. N
Line 119 ⟶ 152:
H ;:^:_1@(](>@{:@]|."_1(,.>@{.))i.({;(~:_1+#))1|.'is not in haystack';":&.>@i.@#@[) N
Washington is not in haystack
To elaborate a bit: Array-oriented languages (like J) consume the input and produce the output ''in toto''.
Line 138 ⟶ 171:
import java.util.Arrays;
List<String> haystack = Arrays.asList("Zig","Zag","
for (String needle : new String[]{"Washington","Bush"}) {
Line 149 ⟶ 182:
for arrays, you have to do it manually:
<java>String[] haystack = {"Zig","Zag","
OUTERLOOP:
Line 169 ⟶ 202:
=={{header|Python}}==
<python>
haystack=["Zig","Zag","
for needle in ("Washington","Bush"):
|