Chapter 18 |
The core library |
|
This chapter describes the functions provided by the Objective Caml
core library module: module Pervasives. This module is special in two
ways:
-
It is automatically linked with the user's object code files by
the nmlc command (chapter 8).
- It is automatically ``opened'' when a compilation starts, or
when the toplevel system is launched. Hence, it is possible to use
unqualified identifiers to refer to the functions provided by the
Pervasives module, without adding a open Pervasives directive.
The declarations from the signature of the Pervasives module are
printed one by one in typewriter font, followed by a short comment.
All modules and the identifiers they export are indexed at the end of
this report.
18.1 |
Module Pervasives: the initially opened module |
|
This module provides the built-in types (numbers, booleans,
strings, exceptions, references, lists, arrays, input-output channels, ...)
and the basic operations over these types.
This module is automatically opened at the beginning of each compilation.
All components of this module can therefore be referred by their short
name, without prefixing them by Pervasives
.
type float = real
The type of floating-point numbers.
type int32
Obejective Caml's int32 type (32-bit integer numbers).
type int64
Obejective Caml's int64 type (64-bit integer numbers).
type nativeint
Obejective Caml's nativeint type (native integer numbers).
type 'a option = None | Some of 'a
The type of optional values.
type ('a, 'b, 'c) format
The type of format strings. 'a
is the type of the parameters
of the format, 'c
is the result type for the printf
-style
function, and 'b
is the type of the first argument given to
%a
and %t
printing functions (see module Printf
).
exception Match_failure of (string * int * int)
Exception raised when none of the cases of a pattern-matching
apply. The arguments are the location of the pattern-matching
in the source code (file name, position of first character,
position of last character).
exception Assert_failure of (string * int * int)
Exception raised when an assertion fails. The arguments are
the location of the pattern-matching in the source code
(file name, position of first character, position of last
character).
exception Invalid_argument of string
Exception raised by library functions to signal that the given
arguments do not make sense.
exception Failure of string
Exception raised by library functions to signal that they are
undefined on the given arguments.
exception Not_found
Exception raised by search functions when the desired object
could not be found.
exception Out_of_memory
Exception raised by the garbage collector
when there is insufficient memory to complete the computation.
exception Stack_overflow
Exception raised by the bytecode interpreter when the evaluation
stack reaches its maximal size. This often indicates infinite
or excessively deep recursion in the user's program.
exception Sys_error of string
Exception raised by the input/output functions to report
an operating system error.
exception End_of_file
Exception raised by input functions to signal that the
end of file has been reached.
exception Division_by_zero
Exception raised by division and remainder operations
when their second argument is null.
exception Exit
This exception is not raised by any library function. It is
provided for use in your programs.
exception Sys_blocked_io
A special case of Sys_error
raised when no I/O is possible
on a non-blocking I/O channel.
val invalid_arg: string -> 'a
Raise exception Invalid_argument
with the given string.
val failwith: string -> 'a
Raise exception Failure
with the given string.
val compare: 'a -> 'a -> int
compare x y
returns 0
if x=y
, a negative integer if
x<y
, and a positive integer if x>y
. The same restrictions
as for =
apply. compare
can be used as the comparison function
required by the Set
and Map
modules.
val min: 'a -> 'a -> 'a
Return the smaller of the two arguments.
val max: 'a -> 'a -> 'a
Return the greater of the two arguments.
val (or) : bool -> bool -> bool
The boolean ``or''. Evaluation is sequential, left-to-right:
in e1 || e2
, e1
is evaluated first, and if it returns true
,
e2
is not evaluated at all.
Integers are 31 bits wide (or 63 bits on 64-bit processors).
All operations are taken modulo 231 (or 263).
They do not fail on overflow.
val succ : int -> int
succ x
is x+1
.
val pred : int -> int
pred x
is x-1
.
val abs : int -> int
Return the absolute value of the argument.
val max_int: int
val min_int: int
The greatest and smallest representable integers.
val lnot: int -> int
Bitwise logical negation.
val asr: int -> int -> int
n asr m
shifts n
to the right by m
bits.
This is an arithmetic shift: the sign bit of n
is replicated.
The result is unspecified if m < 0
or m >= bitsize
.
Floating-point arithmetic |
|
Caml's floating-point numbers follow the
IEEE 754 standard, using double precision (64 bits) numbers.
Floating-point operations never raise an exception on overflow,
underflow, division by zero, etc. Instead, special IEEE numbers
are returned as appropriate, such as infinity
for 1.0 /. 0.0
,
neg_infinity
for -1.0 /. 0.0
, and nan
(``not a number'')
for 0.0 /. 0.0
. These special numbers then propagate through
floating-point computations as expected: for instance,
1.0 /. infinity
is 0.0
, and any operation with nan
as
argument returns nan
as result.
val sqrt : float -> float
Square root
val exp : float -> float
val log : float -> float
val log10 : float -> float
Exponential, natural logarithm, base 10 logarithm.
val cos : float -> float
val sin : float -> float
val tan : float -> float
val acos : float -> float
val asin : float -> float
val atan : float -> float
val atan2 : float -> float -> float
The usual trigonometric functions
val cosh : float -> float
val sinh : float -> float
val tanh : float -> float
The usual hyperbolic trigonometric functions
val ceil : float -> float
val floor : float -> float
Round the given float to an integer value.
floor f
returns the greatest integer value less than or
equal to f
.
ceil f
returns the least integer value greater than or
equal to f
.
val abs_float : float -> float
Return the absolute value of the argument.
val mod_float : float -> float -> float
mod_float a b
returns the remainder of a
with respect to
b
. The returned value is a -. n *. b
, where n
is the quotient a /. b
rounded towards zero to an integer.
val frexp : float -> float * int
frexp f
returns the pair of the significant
and the exponent of f
. When f
is zero, the
significant x
and the exponent n
of f
are equal to
zero. When f
is non-zero, they are defined by
f = x *. 2 ** n
and 0.5 <= x < 1.0
.
val ldexp : float -> int -> float
ldexp x n
returns x *. 2 ** n
.
val modf : float -> float * float
modf f
returns the pair of the fractional and integral
part of f
.
val float : int -> float
val float_of_int : int -> float
Convert an integer to floating-point.
val truncate : float -> int
val int_of_float : float -> int
Truncate the given floating-point number to an integer.
The result is unspecified if it falls outside the
range of representable integers.
More character operations are provided in module Char
.
val int_of_char : char -> int
Return the ASCII code of the argument.
val char_of_int : int -> char
Return the character with the given ASCII code.
Raise Invalid_argument "char_of_int"
if the argument is
outside the range 0--255.
val ignore : 'a -> unit
Discard the value of its argument and return ()
.
For instance, ignore(f x)
discards the result of
the side-effecting function f
. It is equivalent to
f x; ()
, except that the latter may generate a
compiler warning; writing ignore(f x)
instead
avoids the warning.
String conversion functions |
|
val string_of_bool : bool -> string
Return the string representation of a boolean.
val bool_of_string : string -> bool
Convert the given string to a boolean.
Raise Invalid_argument "bool_of_string"
if the string is not
"true"
or "false"
.
val string_of_int : int -> string
Return the string representation of an integer, in decimal.
val int_of_string : string -> int
Convert the given string to an integer.
The string is read in decimal (by default) or in hexadecimal,
octal or binary if the string begins with 0x
, 0o
or 0b
respectively.
Raise Failure "int_of_string"
if the given string is not
a valid representation of an integer.
val string_of_float : float -> string
Return the string representation of a floating-point number.
val float_of_string : string -> float
Convert the given string to a float.
The result is unspecified if the given string is not
a valid representation of a float.
val fst : 'a * 'b -> 'a
Return the first component of a pair.
val snd : 'a * 'b -> 'b
Return the second component of a pair.
type in_channel
type out_channel
The types of input channels and output channels.
val stdin : in_channel
val stdout : out_channel
val stderr : out_channel
The standard input, standard output, and standard error output
for the process.
Output functions on standard output |
|
val print_char : char -> unit
Print a character on standard output.
val print_string : string -> unit
Print a string on standard output.
val print_int : int -> unit
Print an integer, in decimal, on standard output.
val print_float : float -> unit
Print a floating-point number, in decimal, on standard output.
val print_endline : string -> unit
Print a string, followed by a newline character, on
standard output.
val print_newline : unit -> unit
Print a newline character on standard output, and flush
standard output. This can be used to simulate line
buffering of standard output.
Output functions on standard error |
|
val prerr_char : char -> unit
Print a character on standard error.
val prerr_string : string -> unit
Print a string on standard error.
val prerr_int : int -> unit
Print an integer, in decimal, on standard error.
val prerr_float : float -> unit
Print a floating-point number, in decimal, on standard error.
val prerr_endline : string -> unit
Print a string, followed by a newline character on standard error
and flush standard error.
val prerr_newline : unit -> unit
Print a newline character on standard error, and flush
standard error.
Input functions on standard input |
|
val read_line : unit -> string
Flush standard output, then read characters from standard input
until a newline character is encountered. Return the string of
all characters read, without the newline character at the end.
val read_int : unit -> int
Flush standard output, then read one line from standard input
and convert it to an integer. Raise Failure "int_of_string"
if the line read is not a valid representation of an integer.
val read_float : unit -> float
Flush standard output, then read one line from standard input
and convert it to a floating-point number.
The result is unspecified if the line read is not a valid
representation of a floating-point number.
type open_flag =
Open_rdonly | Open_wronly | Open_append
| Open_creat | Open_trunc | Open_excl
| Open_binary | Open_text | Open_nonblock
Opening modes for open_out_gen
and open_in_gen
.
Open_rdonly
: open for reading.
Open_wronly
: open for writing.
Open_append
: open for appending.
Open_creat
: create the file if it does not exist.
Open_trunc
: empty the file if it already exists.
Open_excl
: fail if the file already exists.
Open_binary
: open in binary mode (no conversion).
Open_text
: open in text mode (may perform conversions).
Open_nonblock
: open in non-blocking mode.
val open_out : string -> out_channel
Open the named file for writing, and return a new output channel
on that file, positionned at the beginning of the file. The
file is truncated to zero length if it already exists. It
is created if it does not already exists.
Raise Sys_error
if the file could not be opened.
val open_out_bin : string -> out_channel
Same as open_out
, but the file is opened in binary mode,
so that no translation takes place during writes. On operating
systems that do not distinguish between text mode and binary
mode, this function behaves like open_out
.
val open_out_gen : mode:open_flag list -> perm:int -> string -> out_channel
Open the named file for writing, as above. The extra argument mode
specify the opening mode. The extra argument perm
specifies
the file permissions, in case the file must be created.
open_out
and open_out_bin
are special cases of this function.
val flush : out_channel -> unit
Flush the buffer associated with the given output channel,
performing all pending writes on that channel.
Interactive programs must be careful about flushing standard
output and standard error at the right time.
val output_char : out_channel -> char -> unit
Write the character on the given output channel.
val output_string : out_channel -> string -> unit
Write the string on the given output channel.
val output : out_channel -> buf:string -> pos:int -> len:int -> unit
Write len
characters from string buf
, starting at offset
pos
, to the given output channel.
Raise Invalid_argument "output"
if pos
and len
do not
designate a valid substring of buf
.
val output_byte : out_channel -> int -> unit
Write one 8-bit integer (as the single character with that code)
on the given output channel. The given integer is taken modulo
256.
val output_binary_int : out_channel -> int -> unit
Write one integer in binary format on the given output channel.
The only reliable way to read it back is through the
input_binary_int
function. The format is compatible across
all machines for a given version of Objective Caml.
val output_value : out_channel -> 'a -> unit
Write the representation of a structured value of any type
to a channel. Circularities and sharing inside the value
are detected and preserved. The object can be read back,
by the function input_value
. See the description of module
Marshal
for more information. output_value
is equivalent
to Marshal.to_channel
with an empty list of flags.
val seek_out : out_channel -> int -> unit
seek_out chan pos
sets the current writing position to pos
for channel chan
. This works only for regular files. On
files of other kinds (such as terminals, pipes and sockets),
the behavior is unspecified.
val pos_out : out_channel -> int
Return the current writing position for the given channel.
val out_channel_length : out_channel -> int
Return the total length (number of characters) of the
given channel. This works only for regular files. On files of
other kinds, the result is meaningless.
val close_out : out_channel -> unit
Close the given channel, flushing all buffered write operations.
A Sys_error
exception is raised if any of the functions above
is called on a closed channel.
val set_binary_mode_out : out_channel -> bool -> unit
set_binary_mode_out oc true
sets the channel oc
to binary
mode: no translations take place during output.
set_binary_mode_out oc false
sets the channel oc
to text
mode: depending on the operating system, some translations
may take place during output. For instance, under Windows,
end-of-lines will be translated from \n
to \r\n
.
This function has no effect under operating systems that
do not distinguish between text mode and binary mode.
val open_in : string -> in_channel
Open the named file for reading, and return a new input channel
on that file, positionned at the beginning of the file.
Raise Sys_error
if the file could not be opened.
val open_in_bin : string -> in_channel
Same as open_in
, but the file is opened in binary mode,
so that no translation takes place during reads. On operating
systems that do not distinguish between text mode and binary
mode, this function behaves like open_in
.
val open_in_gen : mode:open_flag list -> perm:int -> string -> in_channel
Open the named file for reading, as above. The extra arguments
mode
and perm
specify the opening mode and file permissions.
open_in
and open_in_bin
are special cases of this function.
val input_char : in_channel -> char
Read one character from the given input channel.
Raise End_of_file
if there are no more characters to read.
val input_line : in_channel -> string
Read characters from the given input channel, until a
newline character is encountered. Return the string of
all characters read, without the newline character at the end.
Raise End_of_file
if the end of the file is reached
at the beginning of line.
val input : in_channel -> buf:string -> pos:int -> len:int -> int
Read up to len
characters from the given channel,
storing them in string buf
, starting at character number pos
.
It returns the actual number of characters read, between 0 and
len
(inclusive).
A return value of 0 means that the end of file was reached.
A return value between 0 and len
exclusive means that
not all requested len
characters were read, either because
no more characters were available at that time, or because
the implementation found it convenient to do a partial read;
input
must be called again to read the remaining characters,
if desired. (See also Pervasives.really_input
for reading
exactly len
characters.)
Exception Invalid_argument "input"
is raised if pos
and len
do not designate a valid substring of buf
.
val really_input : in_channel -> buf:string -> pos:int -> len:int -> unit
Read len
characters from the given channel, storing them in
string buf
, starting at character number pos
.
Raise End_of_file
if the end of file is reached before len
characters have been read.
Raise Invalid_argument "really_input"
if
pos
and len
do not designate a valid substring of buf
.
val input_byte : in_channel -> int
Same as input_char
, but return the 8-bit integer representing
the character.
Raise End_of_file
if an end of file was reached.
val input_binary_int : in_channel -> int
Read an integer encoded in binary format from the given input
channel. See output_binary_int
.
Raise End_of_file
if an end of file was reached while reading the
integer.
val input_value : in_channel -> 'a
Read the representation of a structured value, as produced
by output_value
, and return the corresponding value.
This function is identical to Marshal.from_channel
;
see the description of module Marshal
for more information,
in particular concerning the lack of type safety.
val seek_in : in_channel -> int -> unit
seek_in chan pos
sets the current reading position to pos
for channel chan
. This works only for regular files. On
files of other kinds, the behavior is unspecified.
val pos_in : in_channel -> int
Return the current reading position for the given channel.
val in_channel_length : in_channel -> int
Return the total length (number of characters) of the
given channel. This works only for regular files. On files of
other kinds, the result is meaningless.
val close_in : in_channel -> unit
Close the given channel. A Sys_error
exception is raised
if any of the functions above is called on a closed channel.
val set_binary_mode_in : in_channel -> bool -> unit
set_binary_mode_in ic true
sets the channel ic
to binary
mode: no translations take place during input.
set_binary_mode_out ic false
sets the channel ic
to text
mode: depending on the operating system, some translations
may take place during input. For instance, under Windows,
end-of-lines will be translated from \r\n
to \n
.
This function has no effect under operating systems that
do not distinguish between text mode and binary mode.
val incr : int ref -> unit
Increment the integer contained in the given reference.
Equivalent to fun r -> r := succ !r
.
val decr : int ref -> unit
Decrement the integer contained in the given reference.
Equivalent to fun r -> r := pred !r
.
val exit : int -> 'a
Flush all pending writes on stdout
and stderr
,
and terminate the process, returning the given status code
to the operating system (usually 0 to indicate no errors,
and a small positive integer to indicate failure.)
An implicit exit 0
is performed each time a program
terminates normally (but not if it terminates because of
an uncaught exception).
val at_exit: (unit -> unit) -> unit
Register the given function to be called at program
termination time. The functions registered with at_exit
will be called when the program executes exit
.
They will not be called if the program
terminates because of an uncaught exception.
The functions are called in ``last in, first out'' order:
the function most recently added with at_exit
is called first.