D347th
D347th

Reputation: 707

Getting an object's numerical position in a list

Is there any way to determine an object's numerical position in a list? That is in the list [1, 2, 3, 4] 1 would have the position of 0 and in the list "Hello, World!" l would have the position of 2? I tried to make a counter that bumped up while it was reading the list, but forgot Haskell doesn't allow variables to change. Any help is appreciated and thank you for reading

Upvotes: 3

Views: 264

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153210

Try Hoogle for this variety of question. For example, I just tried the (wrong, it turns out) type signature [a] -> a -> Int there, and the top two results were

elemIndex :: Eq a => a -> [a] -> Maybe Int
elemIndices :: Eq a => a -> [a] -> [Int]

which do just what you ask. Take a look at their source if you're curious how.

Upvotes: 8

Related Questions