1

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

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

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

据我了解,流水线有助于反转函数调用,但我不确定如何使用流水线检索特定索引处的元素。

4

2 回答 2

11

对于listand seq,我通常使用

let fifthElement = sequence |> Seq.nth index

你也可以写

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

或更简洁地没有管道  

let fifthElement = sequence.[index]

对于任何具有Indexed Property的对象。

使用索引属性的优点是它实际上O(1)在数组上,而Seq.nth在数组上是O(N).

于 2012-09-08T16:50:28.603 回答
6

只是一个更新: nth已弃用,您现在可以item用于序列和列表

例子:

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

结果 = 8

于 2015-09-14T16:44:45.453 回答