Positional indexing in F#

F# doesn't offer syntactical support for that sort of indexing. You can ask for a continuous slice of an array like below, but it doesn't cover your exact scenario.

let a = [|1 .. 4|]
let b = a.[0..2]
// returns [|1; 2; 3|]

You can easily write a function for that though:

let slice<'a> (indices: int list) (arr: 'a array) = 
    [| for idx in indices do yield arr.[idx] |]

slice [0; 2] a 
// returns [| 1; 3 |]

I'm leaving proper handling of out-of-bounds access as an exercise ;)


With indexed properties, you should be able to define this for your types: just define a member Item with get(indexes) which accepts a list/array. But standard lists and arrays already have Item defined, and you can't have two at once...


I solved it this way:

List.map (fun index -> l1.[index]) n

It's inefficient for large lists, but works for me.

Tags:

Indexing

List

F#