3

Good day.

How to find index of the element in array? No word about it in docs. Only way I found is:

let arr = [|1; 4; 5; 10|]
let elem = 5
let i = Array.findIndex (fun e -> e = elem) arr
6
  • seems to me you answered your own question already - so what is the question? Commented Jan 25, 2016 at 5:48
  • I thought my method is a kludge and there is more elegant one. Commented Jan 25, 2016 at 5:53
  • 4
    you could reduce the lambda to ((=) elem) and there is Array.IndexOf but basically those are just a matter of taste Commented Jan 25, 2016 at 6:05
  • 1
    Also consider tryFindIndex for those cases where you aren't 100 % sure that the element is in the array. Commented Jan 25, 2016 at 6:34
  • When you say 'kludge', do you mean 'inefficient' or do you mean 'ugly code'. If you mean 'inefficient', then consider using Map with your elements as the key and index as the value, thus providing fast lookup of the index value [O(log N)]. Commented Jan 26, 2016 at 5:59

1 Answer 1

5

You can create a shortcut function yourself if you use it frequently:

let findIndex arr elem = arr |> Array.findIndex ((=) elem)
...
let i = findIndex arr elem
Sign up to request clarification or add additional context in comments.

2 Comments

Or: let findIndex arr elem = arr |> Array.findIndex ((=) elem)
@Foole much more elegant. I'll incorporate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.