/ F#

HR F#: Filter Positions in a List

The next one is Filter Positions in a List:

For a given list with N integers, return a new list removing the elements at odd positions.

There are a few methods in the Seq module that looks relevant: iteri and mapi. They both apply the function considering the index of the item in the sequence. Probably filteri is exactly what is needed to solve the problem, but Seq does not have it. Let's create it then:

let filteri f s =
  |> Seq.mapi (fun i v -> (i, v))
  |> Seq.filter (fun v -> f (fst v) (snd v))
  |> Seq.map (fun v -> snd v)

fst and snd return first and second elements of a tuple.

Now let's use it in the main method to filter by index:

let main argv = 
    let items = readItemsFromInput ()
    |> filteri (fun i _ -> i % 2 = 1)
    |> Seq.iter (fun v -> printfn "%A" v)
    0 // return an integer exit code
Alex Netkachov

Alex Netkachov

Alex Netkachov is a Senior Software Developer, currently working in Central London on new generation of energy trading solutions for brokers, traders and exchanges.

Read More

Why not to stay updated if the subject is interesting? Join Telegram channel Alex@Net or follow alex_at_net on Twitter. Or just, use the comments form below.