Skip to content
Browse files

Remove all ```tryocaml

On the way mane code blocks were also corrected.
Fixes #282
  • Loading branch information...
1 parent 6726e10 commit 7abfd3f49f0cdf8ef888a2a985743e1028a143d6 @Chris00 Chris00 committed Nov 27, 2013
Showing with 953 additions and 935 deletions.
  1. +1 −0 script/code.ml
  2. +7 −1 site/css/bootstrap_mod.css
  3. +109 −88 site/learn/faq.md
  4. +65 −60 site/learn/taste.fr.md
  5. +14 −14 site/learn/taste.md
  6. +7 −5 site/learn/tutorials/basics.fr.md
  7. +20 −18 site/learn/tutorials/basics.it.md
  8. +18 −17 site/learn/tutorials/calling_c_libraries.md
  9. +3 −3 site/learn/tutorials/calling_fortran_libraries.md
  10. +1 −1 site/learn/tutorials/camlp4_3.10.md
  11. +1 −1 site/learn/tutorials/camlp4_3.10/dynamic_functor_example.md
  12. +2 −1 site/learn/tutorials/camlp4_3.10/dynamic_old_syntax.md
  13. +1 −1 site/learn/tutorials/camlp4_3.10/quick_non_extensible_example.md
  14. +1 −2 site/learn/tutorials/camlp4_3.10/static_functor_example.md
  15. +1 −2 site/learn/tutorials/camlp4_3.10/static_old_syntax.md
  16. +3 −3 site/learn/tutorials/command-line_arguments.md
  17. +37 −36 site/learn/tutorials/common_error_messages.md
  18. +6 −6 site/learn/tutorials/compiling_ocaml_projects.md
  19. +18 −15 site/learn/tutorials/compiling_with_gnu_make.md
  20. +1 −1 site/learn/tutorials/compiling_with_omake.md
  21. +82 −103 site/learn/tutorials/debug.md
  22. +2 −2 site/learn/tutorials/dev_tools.md
  23. +1 −2 site/learn/tutorials/filenames.md
  24. +73 −94 site/learn/tutorials/functional_programming.fr.md
  25. +40 −37 site/learn/tutorials/garbage_collection.md
  26. +142 −129 site/learn/tutorials/labels.md
  27. +23 −23 site/learn/tutorials/null_pointers_asserts_and_warnings.fr.md
  28. +164 −160 site/learn/tutorials/objects.md
  29. +8 −8 site/learn/tutorials/performance_and_profiling.md
  30. +38 −37 site/learn/tutorials/stream_expressions.md
  31. +62 −63 site/learn/tutorials/structure_of_ocaml_programs.it.md
  32. 0 site/{img → learn/tutorials}/users.bin.gz
  33. +2 −2 site/releases/caml-light/license.md
View
1 script/code.ml
@@ -105,6 +105,7 @@ let highlight_ocaml =
("\\b\\(type\\|in\\|begin\\|end\\|struct\\|sig\\|val\\|\
object\\|inherit\\|initializer\\|include\\)\\b\\([^\"]\\)",
"<span class=\"governing\">\\1</span>\\2");
+ ("\\b\\(end\\)$", "<span class=\"governing\">\\1</span>");
("\\b\\(fun\\|as\\|of\\|if\\|then\\|else\\|match\\|with\
\\|for\\|to\\|do\\|downto\\|done\\|while\
\\|raise\\|failwith\\|try\\|assert\
View
8 site/css/bootstrap_mod.css
@@ -53,6 +53,12 @@ blockquote {
padding-left: 2ex;
}
+blockquote p {
+ font-size: inherit;
+ line-height: inherit;
+ margin: 0;
+}
+
/* Section headers too close to the following text. */
h1.ruled + ul {
padding-top: 1ex;
@@ -68,4 +74,4 @@ h1.ruled + pre {
p + pre {
margin-top: -13px;
-}
+}
View
197 site/learn/faq.md
@@ -10,7 +10,7 @@ which is widely used by the OCaml community.
* * *
### Basic types
-Is it possible to do computations with arbritrary precision arithmetics?
+#### Is it possible to do computations with arbritrary precision arithmetics?
OCaml and Caml Light both provide a library that handles exact
arithmetic computation for rational numbers. The library is called `Num`
@@ -20,7 +20,7 @@ You build big numbers using conversion from (small) integers or
character strings. For printing in the toplevel, a custom printer can be
used. An example under OCaml is given below.
-```tryocaml
+```ocamltop
#load "nums.cma";;
open Num
open Format;;
@@ -32,15 +32,16 @@ let rec fact n =
if n <= 0 then (num_of_int 1) else num_of_int n */ (fact (n - 1));;
fact 100;;
```
+
### Data structures
-My array is modified, and I don't know why
+#### My array is modified, and I don't know why
This is due to the physical sharing of two arrays that you missed. In
OCaml there are no implicit array copying. If you give two names to the
same array, every modification on one array will be visible to the
other:
-```tryocaml
+```ocamltop
let v = Array.make 3 0;;
let w = v;;
w.(0) <- 4;;
@@ -51,15 +52,15 @@ if these elements are also vectors, the sharing of these vectors implies
that modifying one of these elements modifies the others (see also the
entry below).
-How to define multidimensional arrays?
+#### How to define multidimensional arrays?
The only way is to define an array whose elements are arrays themselves
(OCaml arrays are unidimensional, they modelize mathematical vectors).
The naive way to define multidimensional arrays is bogus: the result is
not right because there is some unexpected physical sharing between the
lines of the new array (see also previous entry):
-```tryocaml
+```ocamltop
let m = Array.make 2 (Array.make 3 0);;
m.(0).(0) <- 1;;
m;;
@@ -73,7 +74,7 @@ matrix with all elements equal to the initial value provided.
Alternatively, write the program that allocates a new line for each line
of your matrix. For instance:
-```tryocaml
+```ocamltop
let matrix n m init =
let result = Array.make n (Array.make m init) in
for i = 1 to n - 1 do
@@ -85,7 +86,7 @@ In the same vein, the `copy_vect` primitive gives strange results, when
applied to matrices: you need to write a function that explicitly copies
each line of the matrix at hand:
-```tryocaml
+```ocamltop
let copy_matrix m =
let l = Array.length m in
if l = 0 then m else
@@ -95,20 +96,21 @@ let copy_matrix m =
done;
result
```
+
### Types definitions
-How to define an enumerated type?
+#### How to define an enumerated type?
An enumerated type is a sum type with only constants. For instance, a
type with 3 constants:
-```tryocaml
+```ocamltop
type color = Blue | White | Red;;
Blue;;
```
The names `Blue`, `White` and `Red` are the constructors of the `color`
type. One can define functions on this type by pattern matching:
-```tryocaml
+```ocamltop
let string_of_color =function
| Blue -> "blue"
| White -> "white"
@@ -119,39 +121,40 @@ How to share a label between two different record types?
When you define two types sharing a label name, the last defined type
hides the labels of the first type. For instance:
-```tryocaml
+```ocamltop
type point_3d = {x : float; y : float; z : float};;
type point_2d = {x : float; y : float};;
{x = 10.; y = 20.; z = 30.};;
```
The simplest way to overcome this problem is simply ... to use different
names! For instance
-```tryocaml
+```ocamltop
type point3d = {x3d : float; y3d : float; z3d : float};;
type point2d = {x2d : float; y2d : float};;
```
With OCaml, one can propose two others solutions. First, it is possible
to use modules to define the two types in different name spaces:
-```tryocaml
+```ocamltop
module D3 = struct
type point = {x : float; y : float; z : float}
-end;;
+end
module D2 = struct
type point = {x : float; y : float}
-end;;
+end
```
+
This way labels can be fully qualified as `D3.x` `D2.x`:
-```tryocaml
+```ocamltop
{D3.x = 10.; D3.y = 20.; D3.z = 30.};;
{D2.x = 10.; D2.y = 20.};;
```
You can also use objects that provide overloading on method names:
-```tryocaml
+```ocamltop
class point_3d ~x ~y ~z = object
method x : float = x
method y : float = y
@@ -163,11 +166,12 @@ class point_2d ~x ~y = object
method y : float = y
end;;
```
+
Note that objects provide you more than overloading: you can define
truly polymorphic functions, working on both `point_3d` and `point_2d`,
and you can even coerce a `point_3d` to a `point_2d`.
-How to define two sum types that share constructor names?
+#### How to define two sum types that share constructor names?
Generally speaking you cannot. As for all other names, you must use
distinct name constructors. However, you can define the two types in two
@@ -177,51 +181,54 @@ module names. With OCaml you can alternatively use polymorphic variants,
i.e. constructors that are, in some sense, *predefined*, since they are
not defined by a type definition. For instance:
-```tryocaml
+```ocamltop
type ids = [ `Name | `Val ];;
type person = [ `Name of string ];;
let f : person -> string = function `Name s -> s;;
let is_name : ids -> bool = function `Name -> true | _ -> false;;
```
+
### Functions and procedures
-How to define a function?
+#### How to define a function?
In OCaml, the syntax to define functions is close to the mathematical
usage: the definition is introduced by the keyword `let`, followed by
the name of the function and its arguments; then the formula that
computes the image of the argument is written after an `=` sign.
-```tryocaml
+```ocamltop
let successor (n) = n + 1;;
```
In fact, parens surrounding the argument may be omitted, so we generally
write:
-```tryocaml
+```ocamltop
let successor n = n + 1;;
```
-How to define a recursive function?
+
+#### How to define a recursive function?
You need to explicitly tell that you want to define a recursive
-function: use let rec instead of let”. For instance:
+function: use `let rec` instead of `let`. For instance:
-```tryocaml
+```ocamltop
let rec fact n =
if n = 0 then 1 else n * fact (n - 1);;
let rec fib n =
if n <= 1 then n else fib (n - 1) + fib (n - 2);;
```
Functions may be mutually recursive:
-```tryocaml
+```ocamltop
let rec odd n =
if n = 0 then true
else if n = 1 then false else even (n - 1)
and even n =
if n = 0 then false
else if n = 1 then true else odd (n - 1);;
```
-How to apply a function?
+
+#### How to apply a function?
Functions are applied as in mathematics: write the function's name,
followed by its argument enclosed in parens: f (x). In practice, parens
@@ -234,108 +241,117 @@ number: to apply `f` to `-1` you must write `f (-1)` and **not** `f -1`
that is syntactically similar to `f - 1` (hence it is a subtraction, not
an application).
-How to define a procedure?
+#### How to define a procedure?
Recall that *procedures* are commands that produce an *effect* (for
instance printing something on the terminal or writing some memory
-location), but have no mathematically meaningful result.<br />
- In OCaml, there is no special treatment of procedures: they are just
+location), but have no mathematically meaningful result.
+
+In OCaml, there is no special treatment of procedures: they are just
considered as special cases of functions that return the special
“meaningless” value `()`. For
instance, the `print_string` primitive that prints a character string on
the terminal, just returns `()` as a way of indicating that its job has
-been properly completed.<br />
- Procedures that do not need any meaningful argument, get `()` as dummy
+been properly completed.
+
+Procedures that do not need any meaningful argument, get `()` as dummy
argument. For instance, the `print_newline` procedure, that outputs a
newline on the terminal, gets no meaningful argument: it has type
-`unit -> unit`.<br />
- Procedures with argument are defined exactly as ordinary functions. For
+`unit -> unit`.
+
+Procedures with argument are defined exactly as ordinary functions. For
instance:
-```tryocaml
+```ocamltop
let message s = print_string s; print_newline();;
message "Hello world!";;
```
-How to define a procedure/function that takes no argument?
+
+#### How to define a procedure/function that takes no argument?
Note that it is impossible to define a procedure without any argument at
all: its definition would imply to execute it, and there would be no way
to call it afterwards. In the following fragment `double_newline` is
bound to `()`, and its further evaluation never produces carriage
returns as may be erroneously expected by the user.
-```tryocaml
+```ocamltop
let double_newline = print_newline(); print_newline();;
double_newline;;
```
The correct definition and usage of this procedure is:
-```tryocaml
+```ocamltop
let double_newline () = print_newline(); print_newline();;
double_newline;;
double_newline ();;
```
-How to define a function with more than one argument?
+
+### How to define a function with more than one argument?
Just write the list of successive arguments when defining the function.
For instance:
-```tryocaml
+```ocamltop
let sum x y = x + y;;
```
then gives the actual arguments in the same order when applying the
function:
-```tryocaml
+```ocamltop
sum 1 2;;
```
These functions are named “curried” functions, as opposed to functions
with tuples as argument:
-```tryocaml
+```ocamltop
let sum' (x, y) = x + y;;
sum' (1, 2);;
```
-How to define a function that has several results?
+
+#### How to define a function that has several results?
You can define a function that return a pair or a tuple:
-```tryocaml
+```ocamltop
let div_mod x y = (x / y, x mod y);;
div_mod 15 7;;
```
-What is an “anonymous function”?
+
+#### What is an “anonymous function”?
You may use functions that have no names: we call them functional values
or anonymous functions. A functional value is introduced by the keyword
`fun`, followed by its argument, then an arrow `->` and the function
body. For instance:
-```tryocaml
+```ocamltop
fun x -> x + 1;;
(fun x -> x + 1) 2;;
```
-What is the difference between `fun` and `function`?
+
+#### What is the difference between `fun` and `function`?
Functions are usually introduced by the keyword `fun`. Each parameter is
introduced by its own `fun` construct. For instance, the construct:
-```tryocaml
+```ocaml
fun x -> fun y -> ...
```
defines a function with two parameters `x` and `y`. An equivalent but
shorter form is:
-```tryocaml
+```ocaml
fun x y -> ...
```
Functions that use pattern-matching are introduced by the keyword
`function`. For example:
-```tryocaml
+```ocamltop
function None -> false | Some _ -> true
```
-My function is never applied
+
+#### My function is never applied
This is probably due to a missing argument: since OCaml is a functional
programming language, there is no error when you evaluate a function
@@ -344,27 +360,28 @@ but the function is evidently not applied. Example: if you evaluate
`print_newline` without argument, there is no error, but nothing
happens. The compiler issues a warning in case of a blatant misuse.
-```tryocaml
+```ocamltop
print_newline;;
print_newline ();;
```
+
### Pattern matching
-How to do nested pattern matching?
+#### How to do nested pattern matching?
You imperatively need to enclose between parens a pattern matching which
is written inside another pattern matching. In effect, the internal
pattern matching “catches” all the pattern matching clauses that are
written after it. For instance:
-```tryocaml
+```ocaml
let f = function
| 0 -> match ... with | a -> ... | b -> ...
| 1 -> ...
| 2 -> ...
```
is parsed as
-```tryocaml
+```ocaml
let f = function
| 0 ->
match ... with
@@ -373,12 +390,13 @@ let f = function
| 1 -> ...
| 2 -> ...
```
+
This error may occur for every syntactic construct that involves pattern
matching: `function`, `match .. with` and `try ... with`. The
usual trick is to enclose inner pattern matchings with `begin` and
`end`. One write:
-```tryocaml
+```ocaml
let f = function
| 0 ->
begin match ... with
@@ -388,9 +406,10 @@ let f = function
| 1 -> ...
| 2 -> ...
```
-### Exceptions
+
+<!-- ### Exceptions -->
### Typing
-Error message: a type is not compatible with itself
+#### Error message: a type is not compatible with itself
You may obtain the message: This expression has type “some type” but is
used with type “the same some type”. This may occur very often when
@@ -399,7 +418,7 @@ using the interactive system.<br />
compiler does not confuse the two types, but the types are evidently
written the same. Consider for instance:
-```tryocaml
+```ocamltop
type t = T of int;;
let x = T 1;;
type t = T of int;;
@@ -414,7 +433,7 @@ new session.
A function obtained through partial application is not polymorphic
enough
-The more common case to get a ``not polymorphic enough'' definition is
+The more common case to get a not polymorphic enough definition is
when defining a function via partial application of a general
polymorphic function. In OCaml polymorphism is introduced only through
the “let” construct, and results from application are weakly polymorph;
@@ -425,20 +444,20 @@ with an explicit functional abstraction, that is, add a `function`
construct or an extra parameter (this rewriting is known as
eta-expansion):
-```tryocaml
+```ocamltop
let map_id = List.map (function x -> x) (* Result is weakly polymorphic *);;
map_id [1;2];;
map_id (* No longer polymorphic *);;
let map_id' l = List.map (function x -> x) l;;
map_id' [1;2];;
map_id' (* Still fully polymorphic *);;
```
+
The two definitions are semantically equivalent, and the new one can be
assigned a polymorphic type scheme, since it is no more a function
application.
-The type of this expression contains type variables that cannot be
-generalized
+#### The type of this expression contains type variables that cannot be generalized
This message appears when the OCaml compiler tries to compile a function
or a value which is monorphic, but for which some types have not been
@@ -447,10 +466,11 @@ are are called “weak” (and are displayed by an underscore: `'_a`); they
will disappear thanks to type inference as soon as enough informations
will be given.
-```tryocaml
+```ocamltop
let r = ref [];;
let f = List.map (fun x -> x);;
```
+
Since the expression mentionned in the error message cannot be compiled
as is, two cases must be envisioned:
@@ -467,24 +487,25 @@ How to write a function with polymorphic arguments?
In ML, an argument of a function cannot be polymorphic inside the body
of the function; hence the following typing:
-```tryocaml
+```ocamltop
let f (g : 'a -> 'a) x y = g x, g y;;
```
The function is not as polymorphic as we could have hoped.<br />
Nevertheless, in OCaml it is possible to use first-order polymorphism.
For this, you can use either records or objects; in the case of records,
you need to declare the type before using it in the function.
-```tryocaml
+```ocamltop
let f (o : < g : 'a. 'a -> 'a >) x y = o#g x, o#g y;;
type id = { g : 'a. 'a -> 'a };;
let f r x y = r.g x, r.g y;;
```
FIXME: A direct way now exists.
+
### Intput/output
-Why some printing material is mixed up and does not appear in the right
-order?
+
+#### Why some printing material is mixed up and does not appear in the right order?
If you use printing functions of the `format` module, you might not mix
printing commands from `format` with printing commands from the basic
@@ -494,11 +515,10 @@ order to find out the proper line breaking to perform with the material
at hand. By contrast low level output is performed with no more
buffering than usual I/O buffering.
-```tryocaml
+```ocamltop
print_endline "before";
Format.print_string "MIDDLE";
print_endline "after";;
-
```
To avoid this kind of problems you should not mix printing orders from
`format` and basic printing commands; that's the reason why when using
@@ -508,7 +528,7 @@ printing functions by the high level printing functions provided by
`format`.
## General Questions
-### What is OCaml?
+#### What is OCaml?
OCaml is a programming language. It is a functional language, since the
basic units of programs are functions. It is a strongly-typed language;
@@ -519,15 +539,15 @@ available on almost every Unix platform (including Linux and MacOS X)
and on PCs under Windows. A brief tour on main
[features](description.html) of OCaml.
-### Under what licensing terms is the OCaml software available?
+#### Under what licensing terms is the OCaml software available?
The OCaml system is open source software: the compiler is distributed
under the terms of the Q Public License, and its library is under LGPL;
please read the [license](/docs/license.html) document for more details. A
BSD-style license is also available for a fee through the [OCaml
Consortium](/community/support.html#consortium).
-### What is the meaning of the name “OCaml”
+#### What is the meaning of the name “OCaml”
“Caml” is an acronym: it stands for “Categorical Abstract Machine
Language”. The “Categorical Abstract Machine” is an abstract machine to
@@ -540,23 +560,23 @@ object oriented features were available in the language.<br />
by Robin Milner in 1978, and used as the programming language to write
the “proof tactics” in the LCF proof system.
-### Do you write “Caml” or “CAML”, “OCaml”, “Ocaml” or “OCAML”?
+#### Do you write “Caml” or “CAML”, “OCaml”, “Ocaml” or “OCAML”?
We write OCaml.
According to usual rules for acronyms, we should write CAML, as we
write USA. On the other hand, this upper case name seems to yell all
over the place, and writing OCaml is far more pretty and elegant — with
“O” and “C” capitalized.
-### Is OCaml a compiled or interpreted language?
+#### Is OCaml a compiled or interpreted language?
OCaml is compiled. However each OCaml compiler offers a top-level
interactive loop, that is similar to an interpreter. In fact, in the
interactive system, the user may type in program chunks (we call these
pieces OCaml “phrases”) that the system handles at once, compiling them,
executing them, and writing their results.
-### What are the differences between Caml V3.1, Caml Light, and OCaml?
+#### What are the differences between Caml V3.1, Caml Light, and OCaml?
These are different Caml implementations that have been developed
successively at Inria. These systems share many features since they all
@@ -570,40 +590,40 @@ other users have switched to OCaml, the latest variant of the language.
This is the version we suggest using in new software developments. See
our brief [history](history.html) of the OCaml language.
-### How to report a bug in the compilers?
+#### How to report a bug in the compilers?
Use the [bug tracking system](http://caml.inria.fr/mantis/) to browse
bug reports and features request, and submit new ones.
## Module Language
-### Can I have two mutually recursive compilation units / structures / signatures / functors?
+#### Can I have two mutually recursive compilation units / structures / signatures / functors?
Currently not in the stable langage. However there exists an [OCaml
extension](http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#toc75)
(which is subject to change or removal at any time) which adresses some
of these problems.
-### How do I express sharing constraints between modules?
+#### How do I express sharing constraints between modules?
Use manifest type specifications in the arguments of the functor. For
instance, assume defined the following signatures:
-```tryocaml
+```ocaml
module type S1 = sig ... type t ... end
module type S2 = sig ... type u ... end
```
To define a functor `F` that takes two arguments `X:S1` and `Y:S2` such
that `X.t` and `Y.u` are the same, write:
-```tryocaml
+```ocaml
module F (X: S1) (Y: S2 with type u = X.t) =
struct ... end
```
Indeed, internally this expands to
-```tryocaml
+```ocaml
module F (X: S1) (Y: sig ... type u = X.t ... end) =
struct ... end
```
@@ -617,19 +637,20 @@ library.
## Development Tools
### Interactive loop (toplevel)
-How to stop the evaluation (execution) of an expression?
+
+#### How to stop the evaluation (execution) of an expression?
It is often possible to interrupt a program or the OCaml system by
typing some combination of keys that is operating system dependent:
under Unix send an interrupt signal (generally `Control-C`), under
Macintosh OS type `Command-.`, under Windows use the “OCaml” menu.
-How to quit the interactive loop?
+#### How to quit the interactive loop?
With Caml Light, type `quit();;`. With OCaml, type `#quit;;`. In both,
you can also send an end-of-file (CTRL-D for Unix, CTRL-Z for DOS,
etc.).
-### Batch Compilers
-### Yacc
-### Lex
+<!-- ### Batch Compilers -->
+<!-- ### Yacc -->
+<!-- ### Lex -->
View
125 site/learn/taste.fr.md
@@ -1,14 +1,15 @@
<!-- ((! set title Une centaine de lignes d'OCaml !)) ((! set learn !)) -->
# Une centaine de lignes d'OCaml
-*Sur cette page*
+
+*Table of contents*
## Fonctions élémentaires
Avec le système interactif, définissons la fonction `square` (carré) et
la fonction factorielle dans sa version récursive. Puis, appliquons ces
fonctions à quelques valeurs choisies :
-```tryocaml
+```ocamltop
let square x = x * x;;
square 3;;
let rec fact x =
@@ -25,15 +26,15 @@ Les listes sont prédéfinies en OCaml. La liste vide est notée `[]`. Le
constructeur d'ajout d'un élément à une liste est noté `::` (sous forme
infixe).
-```tryocaml
+```ocamltop
let l = 1 :: 2 :: 3 :: [];;
[1; 2; 3];;
5 :: l;;
```
## Polymorphisme : le tri des listes
Le tri par insertion est défini à l'aide de deux fonctions récursives.
-```tryocaml
+```ocamltop
let rec sort = function
| [] -> []
| x :: l -> insert x (sort l)
@@ -47,7 +48,7 @@ est représenté par une *variable de types* `'a`. La fonction `sort` peut
donc être appliquée aussi bien à une liste d'entiers qu'à une liste de
chaînes de caractères.
-```tryocaml
+```ocamltop
sort [2; 1; 0];;
sort ["yes"; "ok"; "sure"; "ya"; "yep"];;
```
@@ -56,7 +57,7 @@ Représentons les polynômes des tableaux de coefficients entiers. Alors,
pour ajouter deux polynômes, on alloue d'abord le tableau résultat, puis
on le remplit à l'aide de deux boucles `for` successives.
-```tryocaml
+```ocamltop
let add_polynom p1 p2 =
let n1 = Array.length p1
and n2 = Array.length p2 in
@@ -74,96 +75,96 @@ OCaml offre des cellules mémoire modifiables appelées *références* :
On peut redéfinir `fact` à l'aide d'une référence et d'une boucle `for`
:
-```tryocaml
- let fact n =
- let result = ref 1 in
- for i = 2 to n do
- result := i * !result
- done;
- !result;;
- fact 5;;
+```ocamltop
+let fact n =
+ let result = ref 1 in
+ for i = 2 to n do
+ result := i * !result
+ done;
+ !result;;
+fact 5;;
```
## Fonctions d'ordre supérieur
Il n'y a pas de restriction sur les fonctions, qui peuvent donc être
passés en argument à d'autres fonctions. Définissons une fonction
`sigma` qui renvoie la somme des résultats de l'application d'une
fonction `f` donnée aux éléments d'une liste :
-```tryocaml
- let rec sigma f = function
- | [] -> 0
- | x :: l -> f x + sigma f l
+```ocamltop
+let rec sigma f = function
+ | [] -> 0
+ | x :: l -> f x + sigma f l
```
On peut définir des fonctions anonymes à l'aide de la construction `fun`
ou `function` :
-```tryocaml
+```ocamltop
sigma (fun x -> x * x) [1; 2; 3];;
```
Polymorphisme et fonctions d'ordre supérieur permettent de définir la
composition de fonctions sous sa forme la plus générale :
-```tryocaml
- let compose f g = fun x -> f (g x);;
- let square_o_fact = compose square fact;;
- square_o_fact 5;;
+```ocamltop
+let compose f g = fun x -> f (g x);;
+let square_o_fact = compose square fact;;
+square_o_fact 5;;
```
## La puissance des fonctions
La puissance des fonctions ne peut pas être mieux illustrée que par la
fonction « puissance » :
-```tryocaml
- let rec power f n =
- if n = 0 then fun x -> x
- else compose f (power f (n - 1));;
+```ocamltop
+let rec power f n =
+ if n = 0 then fun x -> x
+ else compose f (power f (n - 1));;
```
La dérivée `n`<sup>ième</sup> d'une fonction peut alors se définir comme
en mathématiques en élevant la fonction dérivée à la puissance `n` :
-```tryocaml
- let derivative dx f = fun x -> (f (x +. dx) -. f x) /. dx;;
- let sin''' = power (derivative 1e-5) 3 sin;;
- let pi = 4.0 *. atan 1.0 in sin''' pi;;
+```ocamltop
+let derivative dx f = fun x -> (f (x +. dx) -. f x) /. dx;;
+let sin''' = power (derivative 1e-5) 3 sin;;
+let pi = 4.0 *. atan 1.0 in sin''' pi;;
```
## Calcul symbolique
Considérons des expressions symboliques simples comprenant des entiers,
des variables, un opérateur de liaison `let`, et des opérateurs
binaires. Ces expressions peuvent être définies à l'aide d'un nouveau
type de données, de la façon suivante :
-```tryocaml
- type expression =
- | Num of int
- | Var of string
- | Let of string * expression * expression
- | Binop of string * expression * expression;;
+```ocamltop
+type expression =
+ | Num of int
+ | Var of string
+ | Let of string * expression * expression
+ | Binop of string * expression * expression;;
```
L'évaluation de ces expressions utilise un environnement qui à un
identificateur associe une valeur, représenté par une liste de paires.
-```tryocaml
- let rec eval env = function
- | Num i -> i
- | Var x -> List.assoc x env
- | Let (x, e1, in_e2) ->
- let val_x = eval env e1 in
- eval ((x, val_x) :: env) in_e2
- | Binop (op, e1, e2) ->
- let v1 = eval env e1 in
- let v2 = eval env e2 in
- eval_op op v1 v2
- and eval_op op v1 v2 =
- match op with
- | "+" -> v1 + v2
- | "-" -> v1 - v2
- | "*" -> v1 * v2
- | "/" -> v1 / v2
- | _ -> failwith ("Unknown operator: " ^ op);;
+```ocamltop
+let rec eval env = function
+ | Num i -> i
+ | Var x -> List.assoc x env
+ | Let (x, e1, in_e2) ->
+ let val_x = eval env e1 in
+ eval ((x, val_x) :: env) in_e2
+ | Binop (op, e1, e2) ->
+ let v1 = eval env e1 in
+ let v2 = eval env e2 in
+ eval_op op v1 v2
+and eval_op op v1 v2 =
+ match op with
+ | "+" -> v1 + v2
+ | "-" -> v1 - v2
+ | "*" -> v1 * v2
+ | "/" -> v1 / v2
+ | _ -> failwith ("Unknown operator: " ^ op);;
```
Évaluons par exemple la phrase `let x = 1 in x + x` :
-```tryocaml
- eval [] (Let ("x", Num 1, Binop ("+", Var "x", Var "x")));;
+```ocamltop
+eval [] (Let ("x", Num 1, Binop ("+", Var "x", Var "x")));;
```
L'emploi du filtrage facilite la définition des fonctions opérant sur
des données symboliques, en donnant aux définitions de fonctions une
@@ -175,8 +176,8 @@ type `expression`.
Pour terminer, voici le moyen le plus élémentaire pour espionner les
fonctions :
-```tryocaml
- let rec fib x = if x <= 1 then 1 else fib (x - 1) + fib (x - 2);;
+```ocaml
+let rec fib x = if x <= 1 then 1 else fib (x - 1) + fib (x - 2);;
# #trace fib;;
fib is now traced.
# fib 3;;
@@ -191,5 +192,9 @@ fib --> 1
fib --> 2
fib --> 3
- : int = 3
-
```
+
+Continuez en
+[essayant OCaml dans votre navigateur](http://try.ocamlpro.com/) ou
+en l'[installant](/docs/install.fr.html) et en lisant des
+« [tutoriaux](tutorials/index.fr.html) ».
View
28 site/learn/taste.md
@@ -22,7 +22,7 @@ Then, let us apply these functions to sample values. Unlike the majority
of languages, OCaml uses parentheses for grouping but not for the
arguments of a function.
-```tryocaml
+```ocamltop
let square x = x * x;;
square 3;;
let rec fact x =
@@ -38,15 +38,15 @@ Lists are predefined in OCaml. The empty list is written `[]`. The
constructor that allows prepending an element to a list is written `::`
(in infix form).
-```tryocaml
+```ocamltop
let l = 1 :: 2 :: 3 :: [];;
[1; 2; 3];;
5 :: l;;
```
## Polymorphism: sorting lists
Insertion sort is defined using two recursive functions.
-```tryocaml
+```ocamltop
let rec sort = function
| [] -> []
| x :: l -> insert x (sort l)
@@ -59,7 +59,7 @@ Note that the type of the list elements remains unspecified: it is
represented by a *type variable* `'a`. Thus, `sort` can be applied both
to a list of integers and to a list of strings.
-```tryocaml
+```ocamltop
sort [2; 1; 0];;
sort ["yes"; "ok"; "sure"; "ya"; "yep"];;
```
@@ -68,7 +68,7 @@ Let us encode polynomials as arrays of integer coefficients. Then, to
add two polynomials, we first allocate the result array, then fill its
slots using two successive `for` loops.
-```tryocaml
+```ocamltop
let add_polynom p1 p2 =
let n1 = Array.length p1
and n2 = Array.length p2 in
@@ -85,7 +85,7 @@ current contents of `cell`, and `cell := v` writes the value `v` into
We may redefine `fact` using a reference cell and a `for` loop:
-```tryocaml
+```ocamltop
let fact n =
let result = ref 1 in
for i = 2 to n do
@@ -100,21 +100,21 @@ arguments to other functions. Let us define a function `sigma` that
returns the sum of the results of applying a given function `f` to each
element of a list:
-```tryocaml
+```ocamltop
let rec sigma f = function
| [] -> 0
| x :: l -> f x + sigma f l
```
Anonymous functions may be defined using the `fun` or `function`
construct:
-```tryocaml
+```ocamltop
sigma (fun x -> x * x) [1; 2; 3];;
```
Polymorphism and higher-order functions allow defining function
composition in its most general form:
-```tryocaml
+```ocamltop
let compose f g = fun x -> f (g x);;
let square_o_fact = compose square fact;;
square_o_fact 5;;
@@ -123,7 +123,7 @@ square_o_fact 5;;
The power of functions cannot be better illustrated than by the `power`
function:
-```tryocaml
+```ocamltop
let rec power f n =
if n = 0 then fun x -> x
else compose f (power f (n - 1));;
@@ -132,7 +132,7 @@ The `n`<sup>th</sup> derivative of a function can be computed as in
mathematics by raising the derivative function to the `n`<sup>th</sup>
power:
-```tryocaml
+```ocamltop
let derivative dx f = fun x -> (f (x +. dx) -. f x) /. dx;;
let sin''' = power (derivative 1e-5) 3 sin;;
let pi = 4.0 *. atan 1.0 in sin''' pi;;
@@ -142,7 +142,7 @@ Let us consider simple symbolic expressions made up of integers,
variables, `let` bindings, and binary operators. Such expressions can be
defined as a new data type, as follows:
-```tryocaml
+```ocamltop
type expression =
| Num of int
| Var of string
@@ -152,7 +152,7 @@ type expression =
Evaluation of these expressions involves an environment that maps
identifiers to values, represented as a list of pairs.
-```tryocaml
+```ocamltop
let rec eval env = function
| Num i -> i
| Var x -> List.assoc x env
@@ -173,7 +173,7 @@ and eval_op op v1 v2 =
```
As an example, we evaluate the phrase `let x = 1 in x + x`:
-```tryocaml
+```ocamltop
eval [] (Let ("x", Num 1, Binop ("+", Var "x", Var "x")));;
```
Pattern matching eases the definition of functions operating on symbolic
View
12 site/learn/tutorials/basics.fr.md
@@ -1,5 +1,7 @@
<!-- ((! set title Notions de base !)) ((! set learn !)) -->
+*Table of contents*
+
# Notions de base
## Commentaires
Les commentaires OCaml sont délimités par `(*` et `*)`, comme ceci:
@@ -114,7 +116,7 @@ let average a b =
Tapez ceci dans le « toplevel » OCaml (sous Unix, tapez `ocaml` depuis
le shell) et voici ce que vous verrez :
-```tryocaml
+```ocamltop
let average a b =
(a +. b) /. 2.0
```
@@ -230,7 +232,7 @@ En OCaml, `1 + 2.5` est une erreur de type. L'opérateur `+` en OCaml
requiert deux arguments entiers, et si on lui donne un int et un float,
il indique cette erreur :
-```tryocaml
+```ocamltop
1 + 2.5;;
```
Cela signifie "ceci est un float, mais ici j'attendais un int".
@@ -241,7 +243,7 @@ Pour ajouter deux floats, il faut utiliser un opérateur différent, `+.`
OCaml ne convertit pas les ints en floats automatiquement, donc le code
suivant est également incorrect :
-```tryocaml
+```ocamltop
1 +. 2.5;;
```
Dans ce cas OCaml se plaint du premier argument.
@@ -290,7 +292,7 @@ Contrairement au langage C et ses dérivés, une fonction en OCaml n'est
récursive que si vous le précisez en utilisant `let rec` au lieu de
seulement `let`. Voici un exemple de fonction récursive :
-```tryocaml
+```ocamltop
let rec range a b =
if a > b then []
else a :: range (a+1) b
@@ -399,7 +401,7 @@ pratiquer ce genre de sport.
Retournons maintenant à la fonction `average` que nous avions tapé ainsi
dans le toplevel :
-```tryocaml
+```ocamltop
let average a b =
(a +. b) /. 2.0
```
View
38 site/learn/tutorials/basics.it.md
@@ -1,6 +1,9 @@
<!-- ((! set title Le basi !)) ((! set learn !)) -->
# Le basi
+
+*Table of contents*
+
## Commenti
In OCaml i commenti sono delimitati da `(*` e `*)`, come segue:
@@ -101,14 +104,14 @@ chi pensa in Java) nei nostri linguaggi. Come lo facciamo in OCaml?
La sintassi di OCaml è piacevolmente concisa. Ecco una funzione che
prende due numeri floating point e ne calcola la media:
-```tryocaml
+```ocamltop
let average a b =
(a +. b) /. 2.0;;
```
Scrivete questo nel "toplevel" di OCaml (su Unix, scrivete il comando
`ocaml` dalla shell) e vedrete così:
-```tryocaml
+```ocamltop
let average a b =
(a +. b) /. 2.0
```
@@ -216,7 +219,7 @@ errore di tipo. L'operatore `+` in OCaml richiede come argomenti due
int, e qui gli stiamo dando un int e un float, dunque esso riposta
questo errore:
-```tryocaml
+```ocamltop
1 + 2.5;;
```
(Nel linguaggio "tradotto dal francese" dei messaggi di errore di OCaml
@@ -228,7 +231,7 @@ Per sommare insieme due float dovete utilizzare un operatore differente,
OCaml non promuove gli int a float automaticamente, quindi è un errore
anche il seguente:
-```tryocaml
+```ocamltop
1 +. 2.5;;
```
Qui OCaml si sta ora lamentando per il primo argomento.
@@ -237,7 +240,7 @@ E se davvere volete sommare insieme un intero ed un numero floating
point? (Mettiamo che siano conservati in variabili chiamate `i` e `f`).
In OCaml dovete fare un cast esplicito:
-```tryocaml
+```ocaml
float_of_int i +. f;;
```
`float_of_int` è una funzione che prende un `int` e restituisce un
@@ -249,7 +252,7 @@ Visto che convertire un `int` in un `float` è un'operazione
particolarmente comune, la funzione `float_of_int` ha un alias più
breve: l'esempio sopra avrebbe potuto essere semplicemente scritto
-```tryocaml
+```ocaml
float i +. f;;
```
(Si noti che diversamente da quanto si ha in C, è perfettamente valido
@@ -275,7 +278,7 @@ Diversamente che nei linguaggi derivati da C, una funzione non è
ricorsiva se non lo dite esplicitamente utilizzando `let rec` invece che
semplicemente `let`. Ecco un esempio di funzione ricorsiva:
-```tryocaml
+```ocamltop
let rec range a b =
if a > b then []
else a :: range (a+1) b
@@ -300,7 +303,7 @@ quindi dovete conoscere la relativa sintassi Per una funzione `f` che
prende gli argomenti `arg1`, `arg2`, ... `argn`, e restituisce il tipo
`rettype`, il compilatore stamperà:
-```tryocaml
+```ocaml
f : arg1 -> arg2 -> ... -> argn -> rettype
```
La sintassi con le frecce sembrerà ora strana, ma quando più tardi
@@ -310,41 +313,41 @@ vi darò soltanto degli esempi.
La nostra funzione `repeated` che prende una stringa e un intero e
restituisce una stringa ha tipo:
-```tryocaml
+```ocaml
repeated : string -> int -> string
```
La nostra funzione `average` che prende due float e restituisce un float
ha tipo:
-```tryocaml
+```ocaml
average : float -> float -> float
```
La funzione standard OCaml di cast `int_of_char`:
-```tryocaml
+```ocaml
int_of_char : char -> int
```
Se una funzione non ritorna nulla (`void` per programmatori C e Java),
scriviamo che restituisce il tipo `unit`. Ecco, per esempio,
l'equivalente in OCaml di `fputc`:
-```tryocaml
+```ocaml
output_char : out_channel -> char -> unit
```
### Funzioni polimorfiche
Vediamo qualche cosa di un po' più particolare. Che dire di una funzione
che prende *qualsiasi cosa* come argomento? Ecco una strana funzione che
prende un argomento, ma semplicemente lo ignora e restituisce sempre 3:
-```tryocaml
+```ocaml
let give_me_a_three x = 3;;
```
Qual è il tipo di questa funzione? In OCaml utilizziamo uno speciale
segnaposto per significare "qualsiasi tipo voi immaginiate". È un
carattere di virgoletta singola (NdT: un apice) seguito da una lettera.
Il tipo dela funzione sopra sarebbe normalmente scritto:
-```tryocaml
+```ocaml
give_me_a_three : 'a -> int
```
Dove `'a` significa in realtà qualsiasi tipo. Potete, ad esempio,
@@ -382,10 +385,9 @@ guru probabilmente necessiteranno di aggirare il controllo dei tipi.
Ritorniamo alla funzione `average` che abbiamo digitato nel toplevel di
OCaml:
-```tryocaml
-# let average a b =
+```ocamltop
+let average a b =
(a +. b) /. 2.0;;
-val average : float -> float -> float = <fun>
```
Mirabile dictu! OCaml ha ricavato tutto da solo che la funzione prende
due argomenti `float` e restituisce un `float`.
@@ -400,7 +402,7 @@ medesimo del valore restituito dalla funzione `average`, dunque
`average` deve restituire un `float`. La conclusione è che `average` ha
la seguente traccia di tipi:
-```tryocaml
+```ocaml
average : float -> float -> float
```
L'inferenza dei tipi è ovviamente facile per un programma così corto, ma
View
35 site/learn/tutorials/calling_c_libraries.md
@@ -34,7 +34,7 @@ I also wanted to rationalise the module naming scheme for Gtk. So there
is exactly one top-level module called (surprise!) `Gtk` and all classes
are inside this module. A test program looks like this:
-```tryocaml
+```ocaml
let win = new Gtk.window ~title:"My window" ();;
let lbl = new Gtk.label ~text:"Hello" ();;
win#add lbl;;
@@ -46,7 +46,7 @@ I defined a single abstract type to cover all `GtkObject`s (and
"subclasses" of this C structure). In the `Gtk` module you'll find this
type definition:
-```tryocaml
+```ocaml
type obj
```
As discussed in the last chapter, this defines an abstract type of which
@@ -55,7 +55,7 @@ functions are going to create instances of this type. For instance, the
function which creates new labels (ie. `GtkLabel` structures) is defined
this way:
-```tryocaml
+```ocaml
external gtk_label_new : string -> obj = "gtk_label_new_c"
```
This strange function definition defines an \<dfn\>external
@@ -69,7 +69,7 @@ from OCaml's internal types and C types. `gtk_label_new_c` (note the
additional `_c`) is my wrapper around the real Gtk C function called
`gtk_label_new`. Here it is. I'll explain more about it later.
-```tryocaml
+```C
CAMLprim value
gtk_label_new_c (value str)
{
@@ -86,7 +86,7 @@ class is derived `GtkWidget` and the whole variety of Gtk widgets are
derived from this. So we define our own `GtkObject` equivalent class
like this (note that `object` is a reserved word in OCaml).
-```tryocaml
+```ocaml
type obj
class virtual gtk_object (obj : obj) =
@@ -107,7 +107,7 @@ pass the return value of, for instance, `gtk_label_new` (go back and
have a look at how that `external` function was typed). This is shown
below:
-```tryocaml
+```ocaml
(* Example code, not really part of MiniGtk! *)
class label text =
let obj = gtk_label_new text in
@@ -121,7 +121,7 @@ Of course the real `label` class doesn't inherit directly from
Following the Gtk class hierarchy the only class derived directly from
`gtk_object` is our `widget` class, defined like this:
-```tryocaml
+```ocaml
external gtk_widget_show : obj -> unit = "gtk_widget_show_c"
external gtk_widget_show_all : obj -> unit = "gtk_widget_show_all_c"
@@ -136,7 +136,7 @@ class virtual widget ?show obj =
This class is considerably more complex. Let's look at the
initialization code first:
-```tryocaml
+```ocaml
class virtual widget ?show obj =
object (self)
inherit gtk_object obj
@@ -157,7 +157,7 @@ of external functions. These are basically direct calls to the C library
(well, in fact there's a tiny bit of wrapper code, but that's not
functionally important).
-```tryocaml
+```ocaml
method show = gtk_widget_show obj
method show_all = gtk_widget_show_all obj
```
@@ -171,7 +171,7 @@ between `widget` and `label` is `misc`, a generic class which describes
a large class of miscellaneous widgets. This class just adds padding and
alignment around a widget such as a label. Here is its definition:
-```tryocaml
+```ocaml
let may f x =
match x with
| None -> ()
@@ -192,6 +192,7 @@ class virtual misc ?alignment ?padding ?show obj =
may (gtk_misc_set_padding obj) padding
end
```
+
We start with a helper function called
`may : ('a -> unit) -> 'a option -> unit` which invokes its first
argument on the contents of its second unless the second argument is
@@ -204,7 +205,7 @@ initialization code. First notice that we take optional `alignment` and
and mandatory `obj` arguments directly up to `widget`. What do we do
with the optional `alignment` and `padding`? The initializer uses these:
-```tryocaml
+```ocaml
initializer
may (gtk_misc_set_alignment obj) alignment;
may (gtk_misc_set_padding obj) padding
@@ -221,7 +222,7 @@ this is done.
Now we can finally get to the `label` class, which is derived directly
from `misc`:
-```tryocaml
+```ocaml
external gtk_label_new :
string -> obj = "gtk_label_new_c"
external gtk_label_set_text :
@@ -255,7 +256,7 @@ virtual. You can create instances of this class which means it finally
has to call `gtk_..._new`. This is the initialization code (we discussed
this pattern above):
-```tryocaml
+```ocaml
class label ~text ... () =
let obj = gtk_label_new text in
object (self)
@@ -271,7 +272,7 @@ instances?)
Now we'll look in more detail at actually wrapping up calls to C library
functions. Here's a simple example:
-```tryocaml
+```C
/* external gtk_label_set_text :
obj -> string -> unit
= "gtk_label_set_text_c" */
@@ -330,7 +331,7 @@ garbage collector when you finish using those roots too, of course. This
is done by framing the function within `CAMLparamN` ... `CAMLreturn`.
Hence:
-```tryocaml
+```C
CAMLparam2 (obj, str);
...
CAMLreturn (Val_unit);
@@ -343,7 +344,7 @@ what code is inlined when you write `CAMLparam2 (obj, str)`. This is the
generated code (with the author's version of OCaml, so it might vary
between implementations slightly):
-```tryocaml
+```C
struct caml__roots_block *caml__frame
= local_roots;
struct caml__roots_block caml__roots_obj;
@@ -357,7 +358,7 @@ caml__roots_obj.tables [1] = &str;
```
And for `CAMLreturn (foo)`:
-```tryocaml
+```C
local_roots = caml__frame;
return (foo);
```
View
6 site/learn/tutorials/calling_fortran_libraries.md
@@ -76,7 +76,7 @@ second element of the temperature array as computed by the function and
ignore the other return values (this is a very frequent use of the
function). This function will be in the source file wrapper.c.
-```tryocaml
+```C
CAMLprim value gtd6_t (value iydV, value secVal, value altVal, value latVal, value lonVal) {
CAMLparam5( iydV, secVal, altVal, latVal, lonVal );
long iyd = Long_val( iydV );
@@ -123,7 +123,7 @@ functions that are used.
Now in an OCaml file (gtd6.ml) we have to define the external reference
to the function and a function to call it.
-```tryocaml
+```ocaml
external temp : int -> float -> float -> float -> float -> float = "gtd6_t"
let () =
@@ -137,7 +137,7 @@ At this point, the steps that are given are to compile this into
bytecode. I don't yet have much experience compiling to native so I'll
let some else help out (or wait until I learn how to do it).
-```tryocaml
+```
prompt> ocamlc -c gtd6.ml prompt> ocamlc -o test gtd6.cmo wrapper.so
```
And voila, we've called the fortran function from OCaml.
View
2 site/learn/tutorials/camlp4_3.10.md
@@ -73,7 +73,7 @@ Only the `.cmi` files from the include path are needed.
So as an example:
-```tryocaml
+```
$ ocamlc -I +camlp4 -pp camlp4orf -c dynamic_functor_example3.ml
```
## The .cma files
View
2 site/learn/tutorials/camlp4_3.10/dynamic_functor_example.md
@@ -3,7 +3,7 @@
# Camlp4 3.10 dynamic_functor_example.ml
dynamic_functor_example.ml:
-```tryocaml
+```ocaml
type t1 = A | B
type t2 = Foo of string * t1
open Camlp4
View
3 site/learn/tutorials/camlp4_3.10/dynamic_old_syntax.md
@@ -3,7 +3,8 @@
# Camlp4 3.10 dynamic_old_syntax.ml
dynamic_old_syntax.ml:
-```tryocaml
+```ocamltop
+#load "camlp4o.cma";;
type t1 = A | B
type t2 = Foo of string * t1
open Pcaml
View
2 site/learn/tutorials/camlp4_3.10/quick_non_extensible_example.md
@@ -3,7 +3,7 @@
# Camlp4 3.10: quick non extensible example
quick_non_extensible_example.ml
-```tryocaml
+```ocaml
(* This scheme only works when the grammar value is not really
used for other things than entry creation. In fact grammars
are now static by default. *)
View
3 site/learn/tutorials/camlp4_3.10/static_functor_example.md
@@ -3,7 +3,7 @@
# Camlp4 3.10: static functor example
static_functor_example.ml
-```tryocaml
+```ocaml
type t1 = A | B
type t2 = Foo of string * t1
open Camlp4.PreCast
@@ -20,5 +20,4 @@ EXTEND Gram
END;;
Gram.parse_string foo (Loc.mk "<string>") "foo x?" = Foo("x", A)
DELETE_RULE Gram foo: "foo"; LIDENT; bar END
-
```
View
3 site/learn/tutorials/camlp4_3.10/static_old_syntax.md
@@ -3,7 +3,7 @@
# Camlp4 3.10: static old syntax
static_old_syntax.ml:
-```tryocaml
+```ocaml
type t1 = A | B
type t2 = Foo of string * t1
module Gram = Grammar.GMake(...)
@@ -16,5 +16,4 @@ GEXTEND Gram
END;;
Gram.Entry.parse foo (Stream.of_string "foo x?") = Foo("x", A)
GDELETE_RULE Gram foo: "foo"; LIDENT; bar END
-
```
View
6 site/learn/tutorials/command-line_arguments.md
@@ -17,7 +17,7 @@ array. It is obtained using the `Array.length` function.
The following program displays the arguments with their position in
`Sys.argv`:
-```tryocaml
+```ocamltop
open Printf
let () =
@@ -28,7 +28,7 @@ let () =
If you save the program above as `args.ml`, and run
`ocaml args.ml arg1 arg2 arg3`, here is what you get:
-```tryocaml
+```
[0] args.ml
[1] arg1
[2] arg2
@@ -39,7 +39,7 @@ where argv is `args.ml arg1 arg2 arg3`. You can also compile your
program using `ocamlopt -o args args.ml`, and then run
`./args arg1 arg2 arg3` and you will get:
-```tryocaml
+```
[0] ./args
[1] arg1
[2] arg2
View
73 site/learn/tutorials/common_error_messages.md
@@ -1,5 +1,7 @@
<!-- ((! set title Common error messages !)) ((! set learn !)) -->
+*Table of contents*
+
# Common error messages
This page gives a list of quick explanations for some error or warning
messages that are emitted by the OCaml compilers. Longer explanations
@@ -10,7 +12,7 @@ are usually given in dedicated sections of this tutorial.
When the type of an object is not compatible with the context in which
it is used, it is frequent to obtain this kind of message:
-```tryocaml
+```ocamltop
1 + 2.5;;
```
"This expression has type *X* but is here used with type *Y*" means that
@@ -21,14 +23,14 @@ around (1 + ...) tells that the gap expects an expression of type *Y*
More disturbing is the following message:
-```tryocaml
- This expression has type my_type but is here used with type my_type
+```text
+This expression has type my_type but is here used with type my_type
```
This error happens often while testing some type definitions using the
toplevel. In OCaml, it is perfectly legal to define a type with a name
that is already taken by another type. Consider the following session:
-```tryocaml
+```ocamltop
type my_type = A | B;;
let a = A;;
type my_type = A | B;;
@@ -48,12 +50,12 @@ discouraged.
Functions with optional arguments must have at least one non-labelled
argument. For instance, this is not OK:
-```tryocaml
+```ocamltop
let f ?(x = 0) ?(y = 0) = print_int (x + y)
```
The solution is simply to add one argument of type unit, like this:
-```tryocaml
+```ocamltop
let f ?(x = 0) ?(y = 0) () = print_int (x + y);;
```
See the [Labels](labels.html "Labels") section for more details on
@@ -64,42 +66,42 @@ This happens in some cases when the full type of an object is not known
by the compiler when it reaches the end of the compilation unit (file)
but for some reason it cannot remain polymorphic. Example:
-```tryocaml
+```ocamltop
let x = ref None
```
triggers the following message during the compilation:
-```tryocaml
+```text
The type of this expression, '_a option ref,
contains type variables that cannot be generalized
```
Solution: help the compiler with a type annotation, like for instance:
-```tryocaml
+```ocamltop
let x : string option ref = ref None
```
or:
-```tryocaml
+```ocamltop
let x = ref (None : string option)
```
Data of type `'_a` may be allowed temporarily, for instance during a
toplevel session. It means that the given object has an unknown type,
but it cannot be any type: it is not polymorphic data. In the toplevel,
our example gives these results:
-```tryocaml
+```ocamltop
let x = ref None
```
The compiler tells us that the type of x is not fully known yet. But by
using `x` later, the compiler can infer the type of `x`:
-```tryocaml
+```ocamltop
x := Some 0
```
Now `x` has a known type:
-```tryocaml
+```ocamltop
x;;
```
More details are given in the [OCaml
@@ -112,11 +114,11 @@ to intentionally keep such code. It may happen when the programmer
introduced a catch-all pattern unintentionally such as in the following
situation:
-```tryocaml
- let test_member x tup =
- match tup with
- | (y, _) | (_, y) when y = x -> true
- | _ -> false;;
+```ocamltop
+let test_member x tup =
+ match tup with
+ | (y, _) | (_, y) when y = x -> true
+ | _ -> false;;
```
Obviously, the programmer had a misconception of what OCaml's pattern
matching is about. Remember the following:
@@ -132,7 +134,7 @@ matching is about. Remember the following:
In our example, it is now clear that only the first item of the pair
will ever be tested. This leads to the following results:
-```tryocaml
+```ocamltop
test_member 1 (1, 0);;
test_member 1 (0, 1);;
```
@@ -142,49 +144,48 @@ exhaustive or not, based on the *type* only. So in the following
example, the compiler doesn't know what range of ints the "mod" operator
would return:
-```tryocaml
- let is_even x =
- match x mod 2 with
- | 0 -> true
- | 1 | -1 -> false
+```ocamltop
+let is_even x =
+ match x mod 2 with
+ | 0 -> true
+ | 1 | -1 -> false
```
A short solution without pattern matching would be:
-```tryocaml
+```ocamltop
let is_even x = x mod 2 = 0
```
In general, that kind of simplification is not possible and the best
solution is to add a catch-all case which should never be reached:
-```tryocaml
- let is_even x =
- match x mod 2 with
- | 0 -> true
- | 1 | -1 -> false
- | _ -> assert false
+```ocamltop
+let is_even x =
+ match x mod 2 with
+ | 0 -> true
+ | 1 | -1 -> false
+ | _ -> assert false
```
## Problems recompiling valid programs
### x.cmi is not a compiled interface
When recompiling some old program or compiling a program from an
external source that was not cleaned properly, it is possible to get
this error message:
-```tryocaml
+```text
some_module.cmi is not a compiled interface
```
It means that some_module.cmi is not valid according to the *current
version* of the OCaml compiler. Most of the time, removing the old
compiled files (*.cmi, *.cmo, *.cmx, ...) and recompiling is
sufficient to solve this problem.
-
+
### Warning: Illegal backslash escape in string
Recent versions of OCaml warn you against unprotected backslashes in
strings since they should be doubled. Such a message may be displayed
-when compiling an older program, and can be turned off with the "-w x"
+when compiling an older program, and can be turned off with the `-w x`
option.
-```tryocaml
+```ocamltop
"\e\n" (* bad practice *);;
"\\e\n" (* good practice *);;
-
```
View
12 site/learn/tutorials/compiling_ocaml_projects.md
@@ -35,7 +35,7 @@ using `ocamlopt`. For now, we also assume that they do not use any other
library than the standard library, which is automatically loaded. You
can compile the program in one single step:
-```tryocaml
+```
ocamlopt -o progprog module1.ml module2.ml
```
That's it. The compiler produced an executable named `progprog` or
@@ -64,7 +64,7 @@ to 3D graphics. You must understand the following:
If your program uses only the unix library (provides system calls not
only for Unix systems), the command line would be:
-```tryocaml
+```
ocamlopt -o progprog unix.cmxa module1.ml module2.ml
```
`.cmxa` is the extension of native code libraries, while `.cma` is the
@@ -97,7 +97,7 @@ ocamlfind.
You can see which packages and subpackages are available in your system
by typing:
-```tryocaml
+```
ocamlfind list
```
This shows the list of package names, with their version ID.
@@ -109,7 +109,7 @@ worry about that since `ocamlfind` knows it.
The command for compiling our program will be:
-```tryocaml
+```
ocamlfind ocamlopt -o progprog -linkpkg \
-package lablGL,sdl,sdl.sdlimage,sdl.sdlmixer,sdl.sdlttf \
module1.ml module2.ml
@@ -122,7 +122,7 @@ you want to recompile only some parts of the programs. Here are the
equivalent commands that perform a separate compilation of the source
files and link them together in a final step:
-```tryocaml
+```
ocamlfind ocamlopt -c \
-package lablGL,sdl,sdl.sdlimage,sdl.sdlmixer,sdl.sdlttf \
module1.ml
@@ -137,4 +137,4 @@ Separate compilation is usually not performed manually but only when
using a Makefile that will take care of recompiling only what it
necessary. See next section.
-## Automated build systems
+<!-- ## Automated build systems -->
View
33 site/learn/tutorials/compiling_with_gnu_make.md
@@ -2,6 +2,8 @@
# Compiling with GNU make
+*Table of contents*
+
## Using GNU make with OCamlMakefile
[OCamlMakefile](http://omake.metaprl.org/index.html "OCamlMakefile") is
a generic Makefile that greatly facilitates the process of compiling
@@ -11,7 +13,7 @@ For a basic OCaml program or library that doesn't use any library
besides the standard library, just copy OCamlMakefile to the current
directory and create the following Makefile:
-```tryocaml
+```makefile
RESULT = myprogram
SOURCES = \
mymodule1.mli mymodule1.ml \
@@ -30,7 +32,7 @@ The included OCamlMakefile provides a variety of targets. For details
please refer to the documentation of OCamlMakefile, but here are the
main ones:
-```tryocaml
+```text
nc make a native code executable
bc make a bytecode executable
ncl make a native code library
@@ -41,6 +43,7 @@ top make a custom toplevel from all your modules
clean remove everything that matches one of the files that could have been
automatically created by OCamlMakefile
```
+
## OCamlMakefile + libraries + Camlp4 parsing
The recommended tool for installing OCaml libraries is
[Findlib](http://www.camlcity.org/archive/programming/findlib.html "Findlib")
@@ -53,14 +56,14 @@ by setting the LIBS and INCDIRS variable. LIBS is the list of the name
of the library files (xxx.cma or xxx.cmxa) without the .cma or .cmxa
extension:
-```tryocaml
+```makefile
LIBS = str unix
```
If you use non-standard libraries that are not installed in the same
directory as the standard library, the INCDIRS variable must contain the
list of these directories:
-```tryocaml
+```makefile
INCDIRS = /path/to/somelibdirectory/
```
Usually this requires some preliminary configuration as it is
@@ -70,13 +73,13 @@ directories which are not included in the search path by default such as
/path/to/stdlib/camlp4. In this case, this should be enough and
portable:
-```tryocaml
+```makefile
INCDIRS = +camlp4
```
OK, but we prefer libraries that are installed with ocamlfind. To use
them with OCamlMakefile, the PACKS variable must be set:
-```tryocaml
+```makefile
PACKS = netstring num
```
Note that libraries that not part of the standard library but are
@@ -90,25 +93,25 @@ extensions, which are bytecode units that are loaded by the
preprocessor. With OCamlMakefile, a preprocessor to be used can be
defined in the first line of the file:
-```tryocaml
+```ocaml
(*pp ...
```
So it could be something like:
-```tryocaml
+```ocaml
(*pp camlp4o -I /path/to/pa_infix pa_infix.cmo *)
```
Well, this form is not very convenient, so we will use the same
preprocessor for each file and store its value in the PP variable of the
Makefile:
-```tryocaml
+```makefile
PP = camlp4o -I /path/to/pa_infix pa_infix.cmo
export PP
```
So each OCaml file will start with:
-```tryocaml
+```ocaml
(*pp $PP *)
```
This way of defining the preprocessor is still not satisfying: we would
@@ -119,13 +122,14 @@ Every package which we use will listed as usual in the PACKS variable,
and camlp4find will call ocamlfind to know which syntax extensions to
load:
-```tryocaml
+```makefile
PACKS = unix micmatch_pcre \
pa_tryfinally pa_lettry pa_forin pa_forstep pa_repeat pa_arg
PP = camlp4find $(PACKS)
export PP
```
-**Summary:**
+
+## Summary
You need:
@@ -140,7 +144,7 @@ You need:
Full example using ocamllex and the unix and micmatch_pcre libraries.
The Makefile file would be:
-```tryocaml
+```makefile
RESULT = myprogram
SOURCES = mymodule1.mll mymodule2.mli mymodule2.ml mymainmodule.ml
PACKS = unix micmatch_pcre
@@ -152,7 +156,6 @@ include $(OCAMLMAKEFILE)
```
And each .ml or .mli file starts with:
-```tryocaml