View Category

Find the distance between two points

ocaml
type point = { x:float; y:float };;
let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);;

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
ocaml
Printf.printf "%08d" 42;;
let s = Printf.sprintf "%08d" 42 in
print_string s;;

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
ocaml
Printf.printf "%-6i" 1024;;

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
ocaml
Printf.printf "%4.2f" (7. /. 8.);;
let s = Printf.sprintf "%4.2f" (7. /. 8.) in
print_string s;;

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
ocaml
Printf.printf "%10d" 73;;

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
ocaml
Random.self_init ();;
let a = 100 and b = 200 in
Random.int ( b - a + 1 ) + a;;

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.
ocaml
let random_stream seed =
Random.init seed;
let state = ref (Random.get_state ()) in
Stream.from
(fun x ->
Random.set_state !state;
let res = Random.float 1. in
state := Random.get_state ();
Some res);;

Stream.npeek 5 (random_stream 1);;
Stream.npeek 5 (random_stream 1);;