简体   繁体   English

F#中的位置索引

[英]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 . 应该返回13l1的第一个和第三个元素。 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? 现在,我想知道,确实存在一种传递参数n表示列表的方法,或者更好的是表达式?

F# doesn't offer syntactical support for that sort of indexing. F#不为这种索引提供语法支持。 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. 使用索引属性 ,您应该能够为您的类型定义它:只需member Item with get(indexes)定义一个接受列表/数组的member Item with get(indexes) But standard lists and arrays already have Item defined, and you can't have two at once... 但是标准列表和数组已经定义了Item ,你不能同时拥有两个......

I solved it this way: 我这样解决了:

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

It's inefficient for large lists, but works for me. 这对于大型列表来说效率很低,但对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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