mat*_*att 1 f# functional-programming sequence pipelined-function
我想在F#中执行以下操作:
let index = 5
let sequence = [0..10]
let fifthElement =
sequence
|> .[index]
Run Code Online (Sandbox Code Playgroud)
但是,最后一行无效.我想要做的是实际检索索引为5的元素sequence.我做错了吗?
根据我的理解,流水线操作有助于反转函数调用,但我不确定如何使用流水线技术检索特定索引处的元素.
pad*_*pad 11
对于list和seq,我通常使用
let fifthElement = sequence |> Seq.nth index
Run Code Online (Sandbox Code Playgroud)
你也可以写
let fifthElement = sequence |> fun sq -> sq.[index]
Run Code Online (Sandbox Code Playgroud)
或更简洁,没有管道
let fifthElement = sequence.[index]
Run Code Online (Sandbox Code Playgroud)
对于具有索引属性的任何对象.
使用Indexed Property的优点是它实际上O(1)在数组上而Seq.nth在数组上O(N).
只是更新:
nth不推荐使用,您现在可以item用于序列和列表
例:
let lst = [0..2..15]
let result = lst.item 4
Run Code Online (Sandbox Code Playgroud)
结果= 8