2

I would like to do the following in F#:

let index = 5
let sequence = [0..10]
let fifthElement =
    sequence
    |> .[index]

However, the last line is invalid. What I'd like to do is to actually retrieve the element at the index of 5 in the sequence. Am I doing things wrong?

From what I understand, pipelining helps to reverse the function call, but I am not sure how to retrieve the element at a particular index using pipelining.

pad
  • 41,040
  • 7
  • 92
  • 166
matt
  • 2,857
  • 7
  • 33
  • 58

2 Answers2

11

For list and seq, I usually use

let fifthElement = sequence |> Seq.nth index

You could also write

let fifthElement = sequence |> fun sq -> sq.[index]

or more concisely without piping  

let fifthElement = sequence.[index]

for any object with Indexed Property.

The advantage of using Indexed Property is that it's actually O(1) on array while Seq.nth on array is O(N).

pad
  • 41,040
  • 7
  • 92
  • 166
  • Isn't `Seq.nth` `O(N)` versus `Array.get` being `O(1)`? It might be `O(1)` only if it uses dynamic type tests to specialize for arrays, is that the case? – t0yv0 Sep 09 '12 at 11:59
  • @toyvo: In this case, sequence is a list so it's `O(N)`. I would use a specific function for each type rather than do type tests – pad Sep 09 '12 at 16:51
8

Just an update: nth is deprecated, you can now use item for sequences and lists

example:

let lst = [0..2..15] 
let result = lst.item 4

result = 8

rmunn
  • 34,942
  • 10
  • 74
  • 105
schmoopy
  • 6,419
  • 11
  • 54
  • 89