Download here - The Caml language

Transcript
Chapter 1. The core language
23
Answer: the generic lexer provided by Genlex recognizes negative integer literals as one integer
token. Hence, x-1 is read as the token Ident "x" followed by the token Int(-1); this sequence
does not match any of the parser rules. On the other hand, the second space in x - 1 causes the
lexer to return the three expected tokens: Ident "x", then Kwd "-", then Int(1).
1.9
Standalone Caml programs
All examples given so far were executed under the interactive system. Caml code can also be
compiled separately and executed non-interactively using the batch compilers ocamlc or ocamlopt.
The source code must be put in a file with extension .ml. It consists of a sequence of phrases, which
will be evaluated at runtime in their order of appearance in the source file. Unlike in interactive
mode, types and values are not printed automatically; the program must call printing functions
explicitly to produce some output. Here is a sample standalone program to print Fibonacci numbers:
(* File fib.ml *)
let rec fib n =
if n < 2 then 1 else fib(n-1) + fib(n-2);;
let main () =
let arg = int_of_string Sys.argv.(1) in
print_int(fib arg);
print_newline();
exit 0;;
main ();;
Sys.argv is an array of strings containing the command-line parameters. Sys.argv.(1) is thus
the first command-line parameter. The program above is compiled and executed with the following
shell commands:
$ ocamlc -o fib fib.ml
$ ./fib 10
89
$ ./fib 20
10946