4
4
5
5
This part of the manual is a tutorial introduction to the
6
6
OCaml language. A good familiarity with programming in a conventional
7
- languages (say, Pascal or C ) is assumed, but no prior exposure to
7
+ languages (say, C or Java ) is assumed, but no prior exposure to
8
8
functional languages is required. The present chapter introduces the
9
9
core language. Chapter~\ref{c:moduleexamples} deals with the
10
10
module system, chapter~\ref{c:objectexamples} with the
@@ -61,10 +61,10 @@ usual basic data types: booleans, characters, and immutable character strings.
61
61
"Hello world";;
62
62
\end{caml_example}
63
63
64
- Predefined data structures include tuples, arrays, and lists. General
65
- mechanisms for defining your own data structures are also provided.
66
- They will be covered in more details later; for now, we concentrate on lists.
67
- Lists are either given in extension as a bracketed list of
64
+ Predefined data structures include tuples, arrays, and lists. There are also
65
+ general mechanisms for defining your own data structures, such as records and
66
+ variants, which will be covered in more detail later; for now, we concentrate
67
+ on lists. Lists are either given in extension as a bracketed list of
68
68
semicolon-separated elements, or built from the empty list "[]"
69
69
(pronounce ``nil'') by adding elements in front using the "::"
70
70
(``cons'') operator.
@@ -79,8 +79,8 @@ explicit handling of pointers: the OCaml compiler silently introduces
79
79
pointers where necessary.
80
80
81
81
As with most OCaml data structures, inspecting and destructuring lists
82
- is performed by pattern-matching. List patterns have the exact same
83
- shape as list expressions, with identifier representing unspecified
82
+ is performed by pattern-matching. List patterns have exactly the same
83
+ form as list expressions, with identifiers representing unspecified
84
84
parts of the list. As an example, here is insertion sort on a list:
85
85
\begin{caml_example}{toplevel}
86
86
let rec sort lst =
@@ -110,11 +110,16 @@ sort [3.14; 2.718];;
110
110
The "sort" function above does not modify its input list: it builds
111
111
and returns a new list containing the same elements as the input list,
112
112
in ascending order. There is actually no way in OCaml to modify
113
- in-place a list once it is built: we say that lists are {\em immutable}
113
+ a list in-place once it is built: we say that lists are {\em immutable}
114
114
data structures. Most OCaml data structures are immutable, but a few
115
115
(most notably arrays) are {\em mutable}, meaning that they can be
116
116
modified in-place at any time.
117
117
118
+ The OCaml notation for the type of a function with multiple arguments is \\
119
+ "arg1_type -> arg2_type -> ... -> return_type". For example,
120
+ the type inferred for "insert", "'a -> 'a list -> 'a list", means that "insert"
121
+ takes two arguments, an element of any type "'a" and a list with elements of
122
+ the same type "'a" and returns a list of the same type.
118
123
\section{Functions as values}
119
124
\pdfsection{Functions as values}
120
125
@@ -204,7 +209,7 @@ With this functional update notation, the record on the left-hand side
204
209
of "with" is copied except for the fields on the right-hand side which
205
210
are updated.
206
211
207
- The declaration of a variant type lists all possible shapes for values
212
+ The declaration of a variant type lists all possible forms for values
208
213
of that type. Each case is identified by a name, called a constructor,
209
214
which serves both for constructing values of the variant type and
210
215
inspecting them by pattern-matching. Constructor names are capitalized
@@ -262,7 +267,7 @@ type 'a btree = Empty | Node of 'a * 'a btree * 'a btree;;
262
267
\end{caml_example}
263
268
This definition reads as follows: a binary tree containing values of
264
269
type "'a" (an arbitrary type) is either empty, or is a node containing
265
- one value of type "'a" and two subtrees containing also values of type
270
+ one value of type "'a" and two subtrees also containing values of type
266
271
"'a", that is, two "'a btree".
267
272
268
273
Operations on binary trees are naturally expressed as recursive functions
@@ -290,9 +295,9 @@ let rec insert x btree =
290
295
Though all examples so far were written in purely applicative style,
291
296
OCaml is also equipped with full imperative features. This includes the
292
297
usual "while" and "for" loops, as well as mutable data structures such
293
- as arrays. Arrays are either given in extension between "[|" and "|]"
294
- brackets, or allocated and initialized with the "Array.make"
295
- function, then filled up later by assignments. For instance, the
298
+ as arrays. Arrays are either created by listing semicolon-separated element
299
+ values between "[|" and "|]" brackets, or allocated and initialized with the
300
+ "Array.make" function, then filled up later by assignments. For instance, the
296
301
function below sums two vectors (represented as float arrays) componentwise.
297
302
\begin{caml_example}{toplevel}
298
303
let add_vect v1 v2 =
@@ -320,7 +325,7 @@ OCaml has no built-in notion of variable -- identifiers whose current
320
325
value can be changed by assignment. (The "let" binding is not an
321
326
assignment, it introduces a new identifier with a new scope.)
322
327
However, the standard library provides references, which are mutable
323
- indirection cells (or one-element arrays) , with operators "!" to fetch
328
+ indirection cells, with operators "!" to fetch
324
329
the current contents of the reference and ":=" to assign the contents.
325
330
Variables can then be emulated by "let"-binding a reference. For
326
331
instance, here is an in-place insertion sort over arrays:
@@ -357,9 +362,9 @@ let ( := ) r newval = r.contents <- newval;;
357
362
\end{caml_example}
358
363
359
364
In some special cases, you may need to store a polymorphic function in
360
- a data structure, keeping its polymorphism. Without user-provided
361
- type annotations, this is not allowed, as polymorphism is only
362
- introduced on a global level . However, you can give explicitly
365
+ a data structure, keeping its polymorphism. Doing this requires
366
+ user-provided type annotations, since polymorphism is only introduced
367
+ automatically for global definitions . However, you can explicitly give
363
368
polymorphic types to record fields.
364
369
\begin{caml_example}{toplevel}
365
370
type idref = { mutable id: 'a. 'a -> 'a };;
@@ -374,9 +379,10 @@ g r;;
374
379
375
380
OCaml provides exceptions for signalling and handling exceptional
376
381
conditions. Exceptions can also be used as a general-purpose non-local
377
- control structure. Exceptions are declared with the "exception"
378
- construct, and signalled with the "raise" operator. For instance, the
379
- function below for taking the head of a list uses an exception to
382
+ control structure, although this should not be overused since it can
383
+ make the code harder to understand. Exceptions are declared with the
384
+ "exception" construct, and signalled with the "raise" operator. For instance,
385
+ the function below for taking the head of a list uses an exception to
380
386
signal the case where an empty list is given.
381
387
\begin{caml_example}{toplevel}
382
388
exception Empty_list;;
@@ -409,11 +415,12 @@ name_of_binary_digit 0;;
409
415
name_of_binary_digit (-1);;
410
416
\end{caml_example}
411
417
412
- The "with" part is actually a regular pattern-matching on the
413
- exception value. Thus, several exceptions can be caught by one
418
+ The "with" part does pattern matching on the
419
+ exception value with the same syntax and behavior as "match". Thus,
420
+ several exceptions can be caught by one
414
421
"try"\ldots"with" construct. Also, finalization can be performed by
415
- trapping all exceptions, performing the finalization, then raising
416
- again the exception:
422
+ trapping all exceptions, performing the finalization, then re- raising
423
+ the exception:
417
424
\begin{caml_example}{toplevel}
418
425
let temporarily_set_reference ref newval funct =
419
426
let oldval = !ref in
@@ -626,7 +633,12 @@ The source code must be put in a file with extension ".ml". It
626
633
consists of a sequence of phrases, which will be evaluated at runtime
627
634
in their order of appearance in the source file. Unlike in interactive
628
635
mode, types and values are not printed automatically; the program must
629
- call printing functions explicitly to produce some output. Here is a
636
+ call printing functions explicitly to produce some output. The ";;" used
637
+ in the interactive examples is not required in
638
+ source files created for use with OCaml compilers, but can be helpful
639
+ to mark the end of a top-level expression unambiguously even when
640
+ there are syntax errors.
641
+ Here is a
630
642
sample standalone program to print Fibonacci numbers:
631
643
\begin{verbatim}
632
644
(* File fib.ml *)
0 commit comments