【问题标题】:F# Idiomatic Index plus one when printing an index [closed]打印索引时F#惯用索引加一[关闭]
【发布时间】:2020-12-11 21:42:32
【问题描述】:

有没有更惯用的方法来使用 F# 打印索引 +1 值?

let plusOne i = i + 1
let collection = [1..10]

collection |> List.iteri (fun index value -> printfn "%i %i" (plusOne index) value)

【问题讨论】:

  • 为什么不只是collection |> List.iteri (fun index value -> printfn "%i %i" (index + 1) value)

标签: f# idioms


【解决方案1】:

F# 确实有许多特殊的习语,但这并不意味着它打破了非常常见的习语,即列表/数组的索引...从零开始。

所以,回答问题:不,F# 没有任何特殊的索引加成语。

但是,如果您打算经常迭代索引加一的列表,则可以使用 Active Pattern 在参数声明中隐式增加索引,如下所示:

let (|Inc|) = (+) 1
let collection = [1..10]
collection |> List.iteri (fun (Inc i) value -> printfn "%i %i" i value)

【讨论】:

    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多