我想在 F# 中执行以下操作:
let index = 5
let sequence = [0..10]
let fifthElement =
sequence
|> .[index]
但是,最后一行无效。我想要做的是实际检索 5 中索引处的元素sequence
。我做错了吗?
据我了解,流水线有助于反转函数调用,但我不确定如何使用流水线检索特定索引处的元素。
我想在 F# 中执行以下操作:
let index = 5
let sequence = [0..10]
let fifthElement =
sequence
|> .[index]
但是,最后一行无效。我想要做的是实际检索 5 中索引处的元素sequence
。我做错了吗?
据我了解,流水线有助于反转函数调用,但我不确定如何使用流水线检索特定索引处的元素。
对于list
and 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)
.
只是一个更新:
nth
已弃用,您现在可以item
用于序列和列表
例子:
let lst = [0..2..15]
let result = lst.item 4
结果 = 8