40

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?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Kap
  • 673
  • 2
  • 7
  • 10
  • 11
    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 Nov 25 '10 at 00:55
  • 1
    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 Nov 25 '10 at 03:46
  • 1
    @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 Jul 09 '15 at 19:23

1 Answers1

49

Take a look here:

i.e. use elemIndex from Data.List:

elemIndex :: Eq a => a -> [a] -> Maybe Int
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • 9
    Note that `elemIndex` returns type `Maybe Int`, so you can "extract" the value like this: `fromJust $ elemIndex 3 [1,2,3,4]` (import `Data.Maybe`) – vikingsteve Dec 22 '15 at 09:08
  • 5
    `fromJust` may throw an error. You can use [`fromMaybe`](https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Maybe.html#v:fromMaybe) to provide a default value in case the list doesn't contain the element : `fromMaybe (-1) $ elemIndex 3 [1,2,3,4]` – Matthias Braun May 16 '19 at 11:50