Search a list

From Rosetta Code
Revision as of 01:00, 28 September 2008 by rosettacode>NevilleDNZ (Find the index of a string (needle) in an array of strings (haystack), or else raise an exception if the needle is missing.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Search a list
You are encouraged to solve this task according to the task description, using any language you may know.

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.

ALGOL 68

FORMAT hay stack := $c("Zig","Zag","Ronald","Bush","Krusty","Wally","Charlie","Bush","Bozo")$;

[]STRING needles = ("Washington","Bush");

FILE needle exception; STRING ref needle;
associate(needle exception, ref needle);

PROC index = (FORMAT haystack, REF STRING needle)INT:(
  INT out;
  ref needle := needle;
  getf(needle exception,(haystack, out));
  out
);

FOR i TO UPB needles DO
  STRING needle := needles[i];
  on value error(needle exception, (REF FILE f)BOOL: value error);
    printf(($d" "gl$,index(hay stack, needle), needle));
    end on value error;
  value error:
    printf(($g" "gl$,needle, "is not in haystack"));
  end on value error: reset(needle exception)
OD

Output:

Washington is not in haystack
4 Bush

python

<python> haystack=["Zig","Zag","Ronald","Bush","Krusty","Wally","Charlie","Bush","Bozo"]

for needle in ("Washington","Bush"):

 try:
   print haystack.index(needle), needle
 except ValueError, value_error:
   print needle,"is not in haystack"

</python> Output:

Washington is not in haystack
3 Bush