Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positional indexing in F#

Tags:

list

indexing

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?

like image 448
Worice Avatar asked Nov 13 '16 17:11

Worice


People also ask

What are positional indexes?

To enable faster phrase search performance and faster relevance ranking with the Phrase module, your project builds index data out of word positions. This is called positional indexing.

What is the advantage of a positional index?

Advantage: because the positional index is similar in construction as the traditional inverted index it inherits the same advantage. That is, when doing an AND query it can jump ahead whenever one of the words doesn't occur in the document it is looking at.

How is positional index different from an inverted index in information retrieval?

As we have the precise position of the position index, it is possible to do proximity queries and the indexing is faster. Another advantage is that compare to the inverted index, the position index has more information. The positional index can be used in ranked retrieval systems (Manning et.


1 Answers

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 ;)

like image 67
scrwtp Avatar answered Sep 19 '22 12:09

scrwtp