流水线操作以在索引处查找元素

时间:2012-09-08 16:47:47

标签: f# functional-programming sequence pipelined-function

我想在F#中执行以下操作:

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

但是,最后一行无效。我想要做的是实际检索sequence中索引为5的元素。我做错了吗?

据我所知,流水线操作有助于反转函数调用,但我不知道如何使用流水线技术检索特定索引处的元素。

2 个答案:

答案 0 :(得分:11)

对于listseq,我通常使用

let fifthElement = sequence |> Seq.nth index

你也可以写

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

或更简洁,没有管道

let fifthElement = sequence.[index]

对于Indexed Property的任何对象。

使用Indexed Property的优势在于它在数组上实际为O(1),而在数组上Seq.nthO(N)

答案 1 :(得分:7)

只是更新: 不推荐使用nth,您现在可以将item用于序列和列表

示例:

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

result = 8

相关问题