/ F#

HR F#: List Replication

This is going to be more interesting than[1] previous[2] three[3].

Given a list, repeat each element in the list n amount of times.

The first line of the input is a number specifying how many times repeat every element of the list. The list items follow this number, one item per line.

The fist interesting task is how to read the input. Console.ReadLine() returns either the line or the null if there are no lines left. The approach for reading the lines is similar to recurrent iterating from "Hello World N Times"[3:1]:

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

yield! concatenates the items from the sequence to the generated sequence.

The main method is very simple:

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

It just reads first line of the input, then reads items, then replicates them and prints.

Although the replicating task sounds like it is complicated, in fact its implementation takes less characters than its description:

let replicate n s =
    seq { for v in s do yield! seq { for _ in 1 .. n do yield v } }

  1. Solving HackerRank's Functional Challenges in F#: Solve Me First FP, https://alexatnet.com/hr-fp-solve-me-first/ ↩︎

  2. HR F#: Hello World, https://alexatnet.com/hr-f-hello-world/ ↩︎

  3. HR F#: Hello World N Times, https://alexatnet.com/hr-fp-hello-world-n-times/ ↩︎ ↩︎

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.