/ F#

HR F#: Filter Array

The next HackerRank functional problem is Filter Array.

Filter a given array of integers and output only those values that are less than a specified value X.

The idea is to create a filtering function, not using the one from the standard library. With what is already known from solving previous problem[1], following the recommended method signature should not be difficult.

The recommended signature is upper limit and list, returns list.

Instead of lists, let's use the sequence:

let f x s =
  seq { for v in s do if v < x then yield v }

readItemsFromInput was introduced in the solution for the problem "List Replication".

The solution:

open System

let f x s =
  seq { for v in s do if v < x then yield v }

let rec readItemsFromInput () = seq {
    let line = Console.ReadLine ()
    match line with
    | null -> ()
    | _ -> yield line |> int
           yield! readItemsFromInput ()         

let main argv = 
    let x = Console.ReadLine () |> int
    let items = readItemsFromInput ()
    |> f x
    |> Seq.iter (fun v -> printfn "%A" v)
    0 // return an integer exit code

  1. HR F#: List Replication, https://alexatnet.com/hr-f-list-replication/ ↩︎

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 chat about this post? Join Telegram group Alex@Net or message on Twitter to alex_at_net. Alternatively, use the comments form below.