/ 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"

let main argv = 
    |> int
    |> printHello
    0 // return an integer exit code
Alex Netkachov

Alex Netkachov

Alex likes functional programming and algorithms. Apart from programming, his favourites are walking with his family in the parks and national trails and reading about universe and history.

Read More