OCaml, lesson 8
Text is everywhere: names, commands, lines of a file. OCaml strings are immutable sequences of
bytes, and the String module has the tools to work with them.
s.[i] gives the character at position i, counting from 0. Characters are a different type
from strings: 'H' is a char, "H" is a string. To turn a char into a one-letter string use
String.make 1 c, and to change its case use Char.uppercase_ascii. %c prints a char in
.
2 exercises to try what you just read.
PrintfBecause strings are immutable, functions like uppercase_ascii return a new string. The
original is untouched.
String.split_on_char cuts a string at every occurrence of a character, and String.concat
glues a list of strings together with a separator:
Filter out the empty pieces with List.filter (fun w -> w <> "") when the input may contain
repeated spaces.
~prefix: is a labelled argument: you name it when calling, which makes the call easier to
read.
For a few pieces, ^ or Printf.sprintf are best. sprintf works like printf but returns the
string instead of printing it:
%-8s pads the string to 8 characters on the right, %5d pads the number to 5 on the left.
This is handy for lining up columns.
The final exercise is a little receipt printer. It uses almost every lesson: reading input, converting text to numbers, a function, a fold over a list, string splitting and formatted output. Plan it before you type:
List.fold_left.Read a full name on one line. Print the initials in upper case, each followed by a dot. The name may be in any case and may contain extra spaces between words.
Sample input:
Sample output:
Each input line describes one item: a name, a quantity and a unit price, separated by single
spaces. Prices are whole numbers. For every item print name: quantity x price = subtotal, then
finish with the total number of items and the total cost. Ignore empty lines.
Sample input:
Sample output:
let s = "Hello, OCaml"
let () =
Printf.printf "%d\n" (String.length s); (* 12 *)
Printf.printf "%c\n" s.[0]; (* H : a char *)
print_endline (String.sub s 7 5); (* OCaml : start 7, length 5 *)
print_endline (String.uppercase_ascii s); (* HELLO, OCAML *)
print_endline (String.trim " padded ") (* padded *)let words = String.split_on_char ' ' "red green blue"
(* ["red"; "green"; ""; "blue"] : two spaces in a row give an empty string *)
let csv = String.concat "," ["a"; "b"; "c"] (* "a,b,c" *)String.starts_with ~prefix:"http" url
String.ends_with ~suffix:".ml" file
String.contains "banana" 'n' (* true *)
String.index_opt "banana" 'n' (* Some 2 *)let line = Printf.sprintf "%-8s %5d" "apples" 12 (* "apples 12" *)grace brewster hopperG.B.H.apple 3 2
bread 1 4
cheese 2 7apple: 3 x 2 = 6
bread: 1 x 4 = 4
cheese: 2 x 7 = 14
Items: 6
Total: 24