Question

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.

Was it helpful?

Solution

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).

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top