Search code examples
f#functional-programmingsequencepipelined-function

Pipelining to find an element at an index


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.


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