Solved Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
ocaml
print_string "Hello world!\n";;
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
ocaml
"\\#{'}${\"}/"
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
ocaml
"This\nIs\nA\nMultiline\nString"
"This
Is
A
Multiline
String"
Is
A
Multiline
String"
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
ocaml
Printf.printf "%d+%d=%d" a b (a+b);;
Printf.printf "%d+%d=%d" a b (a+b);;
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
ocaml
let reverse str =
let len = String.length str in
let buf = Buffer.create len in
for i = 0 to len-1 do
Buffer.add_char buf str.[len-i-1]
done;
Buffer.contents buf;
let len = String.length str in
let buf = Buffer.create len in
for i = 0 to len-1 do
Buffer.add_char buf str.[len-i-1]
done;
Buffer.contents buf;
Reverse the words in a string
Given the string
"This is a end, my only friend!", produce the string "friend! only my end, the is This"
ocaml
let reverse str =
let len = String.length str in
let buf = Buffer.create len in
for i = 0 to len-1 do
Buffer.add_char buf str.[len-i-1]
done;
Buffer.contents buf;;
let len = String.length str in
let buf = Buffer.create len in
for i = 0 to len-1 do
Buffer.add_char buf str.[len-i-1]
done;
Buffer.contents buf;;
Text wrapping
Wrap the string
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
ocaml
(* ocamlbuild -no-hygiene textwrap.native && ./textwrap.native *)
let wrap s prefix width =
let width = width - (String.length prefix) in
let len = String.length s in
let rec loop start =
if start >= len then
[]
else
let stop = min (len - start) width in
let sub = String.sub s start stop in
(prefix ^ sub) :: loop (start+stop)
in
loop 0
in
let wrap_and_print s prefix width =
List.iter print_endline (wrap s prefix width)
in
let s = ref "" in
for i = 1 to 10 do
s := !s ^ "The quick brown fox jumps over the lazy dog. "
done;
wrap_and_print !s "> " 78
let wrap s prefix width =
let width = width - (String.length prefix) in
let len = String.length s in
let rec loop start =
if start >= len then
[]
else
let stop = min (len - start) width in
let sub = String.sub s start stop in
(prefix ^ sub) :: loop (start+stop)
in
loop 0
in
let wrap_and_print s prefix width =
List.iter print_endline (wrap s prefix width)
in
let s = ref "" in
for i = 1 to 10 do
s := !s ^ "The quick brown fox jumps over the lazy dog. "
done;
wrap_and_print !s "> " 78
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
ocaml
String.uppercase "Space Monkey";;
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
ocaml
String.lowercase "Caps ARE overRated";;
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.);;
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;;
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;;
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;;
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);;
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);;
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
ocaml
if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0
then print_string "ok";;
then print_string "ok";;
Define an empty list
Assign the variable
"list" to a list with no elements
ocaml
let list = [];;
Define a static list
Define the list
[One, Two, Three, Four, Five]
ocaml
let list = [ "One"; "Two"; "Three"; "Four"; "Five" ];;
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
ocaml
let list = [ "Apple"; "Banana"; "Carrot" ];;
let f str_so_far elem = str_so_far ^ ", " ^ elem in
let str = List.fold_left f list;;
print_string str;;
let f str_so_far elem = str_so_far ^ ", " ^ elem in
let str = List.fold_left f list;;
print_string str;;
Join the elements of a list, in correct english
Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
ocaml
let join list =
let rec join' list acc =
match list with
| [] -> ""
| [single] -> single
| one::[two] ->
if acc = "" then one ^ " and " ^ two
else acc ^ one ^ ", and " ^ two
| first::others -> join' others (acc ^ first ^ ", ")
in
join' list ""
let rec join' list acc =
match list with
| [] -> ""
| [single] -> single
| one::[two] ->
if acc = "" then one ^ " and " ^ two
else acc ^ one ^ ", and " ^ two
| first::others -> join' others (acc ^ first ^ ", ")
in
join' list ""
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
ocaml
let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;;
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
ocaml
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.nth list ( (List.length list) - 1 );;
let last = List.nth list ( (List.length list) - 1 );;
let list = [ "Red"; "Green"; "Blue" ] in
let last = List.hd (List.rev list);;
let last = List.hd (List.rev list);;
Find the common items in two lists
Given two lists, find the common items. E.g. given beans =
['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
ocaml
let beans = ["broad"; "mung"; "black"; "red"; "white"]
let colors = ["black"; "red"; "blue"; "green"]
let f common c = if List.mem c beans then c::common else common
let common = List.fold_left f [] colors;;
(* common will contain a list with the common elements *)
let colors = ["black"; "red"; "blue"; "green"]
let f common c = if List.mem c beans then c::common else common
let common = List.fold_left f [] colors;;
(* common will contain a list with the common elements *)
Display the unique items in a list
Display the unique items in a list, e.g. given ages =
[18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
ocaml
let ages = [18; 16; 17; 18; 16; 19; 14; 17; 19; 18]
let f res e = if List.mem e res then res else e::res
let unique = List.fold_left f [] ages;;
let f res e = if List.mem e res then res else e::res
let unique = List.fold_left f [] ages;;
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
ocaml
let remove i list =
let rec rem i list' acc =
match list' with
| h::t when i > 0 -> rem (i-1) t (h::acc)
| h::t when i = 0 -> (List.rev acc)@t
| [] -> List.rev acc (* not enough elements *)
in
rem i list []
let rec rem i list' acc =
match list' with
| h::t when i > 0 -> rem (i-1) t (h::acc)
| h::t when i = 0 -> (List.rev acc)@t
| [] -> List.rev acc (* not enough elements *)
in
rem i list []
Remove the last element of a list
ocaml
let remove_last list =
match (List.rev list) with
| h::t -> List.rev t
| [] -> []
match (List.rev list) with
| h::t -> List.rev t
| [] -> []
Rotate a list
Given a list
["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
ocaml
let rotate list =
match list with
| head::tail -> tail@[head]
| [] -> []
match list with
| head::tail -> tail@[head]
| [] -> []
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[2, 3, 4, 5]
ocaml
List.map String.length ["ox"; "cat"; "deer"; "whale"];;
Perform an action if a condition is true (IF .. THEN)
Given a variable name, if the value is
"Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
ocaml
if name = "Bob"
then print_string "Hello, Bob!"
else ()
then print_string "Hello, Bob!"
else ()
Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)
Given a variable age, if the value is greater than 42 display
"You are old", otherwise display "You are young"
ocaml
if age = 42
then print_string "Youre are old"
else print_string "You are young"
then print_string "Youre are old"
else print_string "You are young"
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
ocaml
let rec write_hello = function
0 -> ()
| 1 ->
print_string "Hello" ;
write_hello (n-1)
;;
write_hello 5;;
0 -> ()
| 1 ->
print_string "Hello" ;
write_hello (n-1)
;;
write_hello 5;;
produces a copy of its own source code
In computing, a quine is a computer program which produces a copy of its own source code as its only output.
ocaml
(fun s -> Printf.printf "%s %S" s s) "(fun s -> Printf.printf \"%s %S\" s s)"
