/ 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 =
  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:

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

Alex Netkachov

Alex likes functional programming, algorithms and code reviews. Apart from programming, his favourites are walking with his family in the parks and national trails and reading books.

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.