F# slicing array by indices array

霸气de小男生 提交于 2019-12-24 02:11:45

问题


How can I overload .[] for F# array to slice an array based on an arbitrary index array?

For example:

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

although

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

would work, it would be nicer to be able using x.[indx] directly.


回答1:


You can always write an F# extension method to get close on the syntax

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)

but since arrays already have an indexer it doesn't appear there's a way to overload/change it.



来源:https://stackoverflow.com/questions/2357006/f-slicing-array-by-indices-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!