简体   繁体   中英

Positional indexing in F#

Given a list, I would like to produce a second list of elements selected from the first one.

For example:

let l1 = [1..4]
let n = [0; 2]
l1.[n]

should return 1 and 3 , the first and third element of l1 . Unfortunately, it returns an error:

error FS0001: This expression was expected to have type
int but here has type int list

Now, I wonder, does exist a way to pass an argument n representing a list or, even better, an expression?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM