OCaml is provided with a wide range of useful built-in functions, in addition to the ones we have already seen, called the OCaml Standard Library. These functions are divided into modules, one for each area of functionality (in the next chapter, we will learn how to write our own modules). Here are a few examples of modules in the standard library:
We will take the List
module as an example. You can find
the documentation for the OCaml Standard Library installed with your
copy of OCaml, or on the internet.
The functions from a module can be used by putting a period (full
stop) between the module name and the function. For example the
length
function in the List
module can be used
like this:
OCaml
# List.length [1; 2; 3; 4; 5];;
- : int = 5
We can look at the type too by writing just the name of the function:
OCaml
# List.length;;
- : 'a list -> int = <fun>
Here’s the documentation for List.length
:
We will talk about val
in the next
chapter. Sometimes, more information is required:
For example,
OCaml
# List.nth [1; 2; 4; 8; 16] 3;;
- : int = 8
In the documentation, we are told what the function does for each argument, and what exceptions may be raised. Functions which are not tail-recursive and so may fail on huge arguments are marked as such.
The questions for this chapter use functions from the standard library, so you will need to have a copy of the documentation to hand.
Write your own version of the function List.concat
.
The implementation OCaml provides is not tail-recursive. Can you write
one which is?
Use List.mem
to write a function which returns
true
only if every list in a bool list list contains
true
somewhere in it.
Write a function to count the number of exclamation marks in a
string, using one or more functions from the String
module.
Use the String.map
function to write a function to
return a new copy of a string with all exclamation marks replaced with
periods (full stops).
Use the String
module to write a function which
concatenates a list of strings together.
Do the same with the Buffer
module. This will be
faster.
Use the String
module to count the number of
occurrences of the string "OCaml"
within a given
string.