【问题标题】:F# slicing array by indices arrayF#按索引数组切片数组
【发布时间】:2015-04-10 04:28:02
【问题描述】:

如何为 F# 数组重载 .[] 以根据任意索引数组对数组进行切片?

例如:

let x = [|1..10|]; 
let indx = [|4;1|];

虽然

[| for i in indx ->x.[i]|] 

会工作,如果能够直接使用x.[indx] 会更好。

【问题讨论】:

  • 您的示例不执行 slicing - 它只检索数组的不同元素。切片会 f.ex.成为x.[2..6]

标签: f#


【解决方案1】:

您总是可以编写一个 F# 扩展方法来接近语法

let a = [| 1..10 |]
let idx = [|4;1|]

type 'T ``[]`` with   //'
    member this.Slice(indices:int array) =
        [| for i in indices -> this.[i] |]

printfn "%A" (a.Slice idx)

但由于数组已经有一个索引器,它似乎没有办法重载/更改它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多