Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# filtering list

Tags:

f#

How would I filter out a list by the index ? List: [400; 5; 401; 6; 403; 7] Filtered List: [5; 6; 7;]

I want to filter out the odd index numbers. So I could compare the values and then print out the largest value.

like image 810
Shiro Pie Avatar asked Apr 05 '18 21:04

Shiro Pie


People also ask

What does ⟨F⟩ mean?

This sound is usually considered to be an allophone of /h/, which is pronounced in different ways depending upon its context; Japanese /h/ is pronounced as [ɸ] before /u/. In Welsh orthography, ⟨f⟩ represents /v/ while ⟨ff⟩ represents /f/. In Slavic languages, ⟨f⟩ is used primarily in words of foreign (Greek, Latin, or Germanic) origin.

What does the letter F mean in math?

In countries such as the United States, the letter "F" is defined as a failure in terms of academic evaluation. Other countries that use this system include Saudi Arabia, Venezuela, and the Netherlands. In the hexadecimal number system, the letter "F" or "f" is used to represent the hexadecimal digit fifteen (equivalent to 15 10 ).

What does F stand for in the Etruscan alphabet?

In the Etruscan alphabet, 'F' probably represented /w/, as in Greek, and the Etruscans formed the digraph 'FH' to represent /f/.

Is the letter F doubled at the end of words?

It is often doubled at the end of words. Exceptionally, it represents the voiced labiodental fricative / v / in the common word "of". F is the twelfth least frequently used letter in the English language (after C, G, Y, P, B, V, K, J, X, Q, and Z ), with a frequency of about 2.23% in words.


2 Answers

A simple and straight forward approach would be to recurse through the list and pick every second element:

let getOddIndexed list =
    let rec aux acc xs =
        match xs with
        | _::x::tail -> aux (x::acc) tail
        | _ -> acc |> List.rev
    aux [] list
like image 63
John Reynolds Avatar answered Nov 15 '22 11:11

John Reynolds


In the specific case you asked about (keeping the odd index numbers and dropping the even ones), John Reynolds' answer will work. But in the general case where your index-based filter is more complicated, you'd want to use Seq.indexed, which turns any list of items into a list of (index, item) pairs. E.g.:

["apple"; "banana"; "cherry"] |> Seq.indexed |> List.ofSeq
// Produces [(0, "apple"); (1, "banana"); (2, "cherry")]

With this approach, you would then use Seq.filter to do the filtering you want, then turn the sequence back into a list at the end:

let keepOdd (idx, item) =
    // A more complicated filter might use the item parameter too
    idx % 2 <> 0

let input = [400; 5; 401; 6; 403; 7]
input |> Seq.indexed |> Seq.filter keepOdd |> List.ofSeq
like image 37
rmunn Avatar answered Nov 15 '22 11:11

rmunn