32
votes

Giving an element in a list, which function can I use to find its index?

For instance, I want to find the index of 3 in the list [1, 2, 3, 4].

Which function exists in Haskell that I can use for this?

1
If you need the index of an element in a list you're not thinking in Haskell yet. Haskell lists are more like streams of elements. You wouldn't ask C++ for the index of an element in stdin would you? You probably want a finite length data structure such as Data.Vector.Jason Dagit
Does your question also apply to the more general case of the list being, say, [1,2,3,4,3]? That is, would your desired function return both of those indexes, or maybe just the first one it found?wlangstroth
@JasonDagit I don't think it is true. E.g. I'm doing an implementation of a database (part of a student project), and there is a header of a table with column names, and a list of rows with according values. Given a key, the only way I see, is to find an index in header, and take according to the index values from every row.Hi-Angel

1 Answers