Back to Contents
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
# List.length [1; 2; 3; 4; 5];;
- : int = 5
We can look at the type too by writing just the name of the function:
- : 'a list -> int = <fun>
Here’s the documentation for
We will talk about
val in the next
chapter. Sometimes, more information is required:
# 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
The implementation OCaml provides is not tail-recursive. Can you write
one which is?
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.map function to write a function to
return a new copy of a string with all exclamation marks replaced with
periods (full stops).
String module to write a function which
concatenates a list of strings together.
Do the same with the
Buffer module. This will be
String module to count the number of
occurrences of the string
"OCaml" within a given