【问题标题】:Pipelining to find an element at an index流水线在索引处查找元素
【发布时间】:2012-09-02 04:40:06
【问题描述】:

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    示例:

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

    结果 = 8

    【讨论】:

      【解决方案2】:

      对于listseq,我通常使用

      let fifthElement = sequence |> Seq.nth index
      

      你也可以写

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

      或者更简洁,没有管道

      let fifthElement = sequence.[index]
      

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

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

      【讨论】:

      • 不是Seq.nth O(N) 而不是Array.getO(1)?可能是O(1),只有当它使用动态类型测试来专门针对数组时,是这样吗?
      • @toyvo:在这种情况下,序列是一个列表,所以它是O(N)。我会为每种类型使用特定的函数,而不是进行类型测试
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2017-09-23
      • 2015-05-07
      相关资源
      最近更新 更多