View Category

Find the distance between two points

fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
fsharp
printfn "%08d" 42
let formatted = sprintf "%08d" 42
printfn "%s" formatted
let buffer = new StringBuilder()
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
let formatted = String.Format("{0,8:D8}", 42)
Console.WriteLine(formatted)
let formatted = Convert.ToString(42).PadLeft(8, '0')
Console.WriteLine(formatted)

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
fsharp
printfn "%-6d" 1024
let formatted = String.Format("{0,-6:D}", 1024)
Console.WriteLine(formatted)
let formatted = Convert.ToString(1024).PadRight(6)
Console.WriteLine(formatted)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
fsharp
printfn "%3.2f" (0.7 / 0.8)
let formatted = String.Format("{0,3:F2}", (0.7 / 0.8))
Console.WriteLine(formatted)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
fsharp
let formatted = sprintf "%10d" 73
printfn "%s" formatted
let formatted = String.Format("{0,10:D}", 73)
Console.WriteLine(formatted)
let formatted = Convert.ToString(73).PadLeft(10)
Console.WriteLine(formatted)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
fsharp
let rnd = new Random()
let rndInt = rnd.Next(100, 201)

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
fsharp
let (seed, lb, ub) = (12345, 100, 200)

let mutable rnd = new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""

rnd <- new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""