/ Functional Programming

HR F#: Hello World N Times

One more HR F# challenge for today - Hello World N Times:

Print "Hello World" N amount of times. ... A single line of input containing integer N, the number of times to print "Hello World".

The iterative process in F# can be constructed in three ways:

  • the well-known for loop
  • the sequence generator
  • recursion

There are three implementations that demonstrates each of these three approaches:

// using loop to iterate over the range
let printHello1 n =
  for _ in 1..n do
    printn "Hello World"

// generate sequence and invoke function for each item
let printHello2 n =
  seq { 1 .. n }
  |> Seq.iter (fun _ -> printfn "Hello World")

// call itself recursively until end
let rec printHello3 n =
  match n with
  | 0 -> ()
  | _ -> printfn "Hello World"
         printHello3 (n-1) 

Without tail recusrion optimisation enabled the printHello3 function drains stack memory for large n.

The complete for-loop solution:

open System

let printHello n =
  for _ in 1..n do printfn "Hello World"

[<EntryPoint>]
let main argv = 
    Console.ReadLine()
    |> int
    |> printHello
    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 chat about this post? Join Telegram group Alex@Net or message on Twitter to alex_at_net. Alternatively, use the comments form below.