1

I have read a file in to a list, the format of the file for example is:

 blue
 yellow
 green
 red

and now i want to find the location (index) of item "green" if done correctly the result would be "3" as it is the 3rd item in the list.

maybe I'm not good at searching google but I couldn't find a solution anywhere :/ so the whole idea of this is:

if (item.exists(List, "green")) {
    index = indexOf(List, "green")
}

First i must know if it exists before I get the index of it. Also I'm trying to do this without having to make any new functions that I would have to call.

thanks for any help

ace007
  • 577
  • 1
  • 10
  • 20
  • 1
    seehttp://stackoverflow.com/questions/1459152/erlang-listsindex-of-function – Rachel Gallen Jan 23 '13 at 11:51
  • @Rachel Gallen just 1 problem, I get an error if the item does not exist, that's why in the psudo code i wrote "if (item.exists(List, "green")) {" before it tries to get the index of the item. – ace007 Jan 23 '13 at 16:56

1 Answers1

2

One way is to use a zip to lace numbers on the list:

L = [blue, yellow, green, red],
case lists:keyfind(green, 1, lists:zip(L, lists:seq(1, length(L))) of
  false -> not_there;
  {green, Idx} -> {found, Idx}
end,
...

(not tested)

The problem is that you want an index. We rarely, if ever, use indices in erlang programs. Rather, we would probably represent the list as a set:

Set = sets:from_list(L),
case sets:is_element(green, Set) of
   true -> ...;
   false -> ...
end,
I GIVE CRAP ANSWERS
  • 18,739
  • 3
  • 42
  • 47