-
Comments
-
Comments are written between
(*
and*)
. - Comments can be nested.
-
Comments are written between
-
Variables
-
define and initialise a variable
#> let x = 50;;
-
it is possible to add type annotations
#> let (x: int) = 50;;
-
define and initialise a variable
-
References
-
declare a reference
#> let x = ref 0;;
-
get the value of a reference
#> let y = !x;;
-
modify the value of a reference
#> x := 1;;
-
aliasing a reference
#> let z = x;;
-
declare a reference
-
Comparisons
-
Stdlib
moduleval (=) : 'a -> 'a -> bool
e1 = e2
tests for structural equality ofe1
ande2
. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raisesInvalid_argument
. Equality between cyclic data structures may not terminate. Comparison between cyclic structures may not terminate.val (<>) : 'a -> 'a -> bool
Negation of (=)
.val (<) : 'a -> 'a -> bool
See (>=)
.val (>) : 'a -> 'a -> bool
See (>=)
.val (<=) : 'a -> 'a -> bool
See (>=)
.val (>=) : 'a -> 'a -> bool
Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with (=)
. As in the case of(=)
, mutable structures are compared by contents. Comparison between cyclic structures may not terminate.val compare : 'a -> 'a -> int
Returns 0
ifx
is equal toy
, a negative integer ifx
is less thany
, and a positive integer ifx
is greater thany
. The ordering implemented by compare is compatible with the comparison predicates(=)
,(<)
and(>)
defined above, with one difference on the treatment of the float valuenan
.val min : 'a -> 'a -> 'a
Return the smaller of the two arguments. The result is unspecified if one of the arguments contains the float value nan
.val max : 'a -> 'a -> 'a
Return the greater of the two arguments. The result is unspecified if one of the arguments contains the float value nan
.val (==) : 'a -> 'a -> bool
e1 == e2
tests for physical equality ofe1
ande2
. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables,e1 == e2
is true if and only if physical modification ofe1
also affectse2
. On non-mutable types, the behaviour of(==)
is implementation-dependent; however, it is guaranteed thate1 == e2
impliescompare e1 e2 = 0
.val (!=) : 'a -> 'a -> bool
Negation of (==)
.
-
-
Function
-
define a function
#> let max a b = if a < b then b else a;;
#> let max = fun a b -> if a < b then b else a;;
-
define a recursive function
#> let rec range a b = if a > b then [] else a :: range (a + 1) b;;
-
with type annotations
#> let rec pow (x : int) (y : int) : int = if y = 0 then 1 else x * pow x (y - 1);;
unit
if no value is returned#> let print_flat_tree (n: node): unit = print_endline (string_of_list (list_of_tree n))
-
to make a function tail recursive
-
Change the function into a helper function. Add an extra argument: the accumulator, often named
acc
. - Write a new “main” version of the function that calls the helper. It passes the original base case’s return value as the initial value of the accumulator.
- Change the helper function to return the accumulator in the base case.
- Change the helper function’s recursive case. It now needs to do the extra work on the accumulator argument, before the recursive call.
#> let factorial n =
let rec fact_aux n acc =
if n = 0 then acc else fact_aux (n - 1) (n * acc) in
fact_aux n 1 ;;
val factorial : int -> int = <fun> -
Change the function into a helper function. Add an extra argument: the accumulator, often named
-
parameters can be labelled
#> let f ~name1:arg1 ~name2:arg2 = arg1 + arg2;;
#> f ~name2:3 ~name1:4;; -
labels can be used and no variable names are to be given
#> let f ~name1 ~name2 = name1 + name2;;
-
the syntax to write both a labeled argument and an explicit type annotation
#> let f ~name1:(arg1 : int) ~name2:(arg2 : int) = arg1 + arg2;;
-
it is possible to make some arguments optional, a default value is provided
#> let f ?name:(arg1=8) arg2 = arg1 + arg2;;
-
anonymous function, also called lambda expressions
#> let inc = fun x -> x + 1;;
-
define mutually recursive functions
#> let rec even n =
match n with
| 0 -> true
| x -> odd (x - 1)
and odd n =
match n with
| 0 -> false
| x -> even (x - 1);; -
The application operator
@@
applies the function defined on the left side to the argument defined on the right side#> succ @@ 4 + 5;;
- : int = 10 -
The reverse application operator (a.k.a. pipeline operator)
|>
applies the function defined on the right side to the argument defined on the left side#> 4 + 5 |> succ;;
- : int = 10
-
define a function
-
Operator
-
=
,<
, and>
are polymorphic. -
An operator between parentheses is a function
#> ( + ) ;;
- : int -> int -> int = <fun>
#> ( + ) 2 3 ;;
- : int = 5 -
defining an infix operator
#> let ( ** ) f g x = x |> g |> f ;;
val ( ** ) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
#> let g x = x *. x ;;
val g : float -> float = <fun>
#> let f x = -. x ;;
val f : float -> float = <fun>
#> let _ = (f**g) 1.1 ;;
- : float = -1.21000000000000019 -
defining a prefix operator
#> let ( !// ) f x = 1. /. ( f x ) ;;
val ( !// ) : ('a -> float) -> 'a -> float = <fun>
#> let f x = x *. x ;;
val f : float -> float = <fun>
#> let _ = (!// f) 2. ;;
- : float = 0.25
-
-
conditional expressions use
if … then … else …
#> let rec gcd a b = if b = 0 then a else gcd b (a mod b);;
-
Pattern matching
-
_
matches anything. -
Patterns can be combined
#> let isvowel c =
match c with
'a' | 'e' | 'i' | 'o' | 'u' -> true
| _ -> false -
Pattern matching on records
type node = Node of { left : node; value : int; right : node } | Nil
match nd with
| Nil -> …
| Node _ -> …match nd with
| Nil -> …
| Node n -> …match nd with
| Nil -> …
| Node { left = l; value = v; right = r } -> …match nd with
| Nil -> …
| Node { left; value; right } -> …match nd with
| Nil -> …
| Node { left = l; value = v; right = r } as n -> … -
function
keyword automatically has pattern matching#> let foo = function
0 -> "zero"
| 1 -> "one"
| 2 -> "couple"
| 3 -> "few"
| _ -> "many";;
-
-
Data types
-
The Basic types are
-
int
: 63-bit signed int on 64-bit processors, or 31-bit signed int on 32-bit processors -
float
: IEEE double-precision floating point -
bool
: Boolean, written eithertrue
orfalse
-
char
: 8-bit character -
string
: sequence of 8 bit chars
-
-
Int
moduleval zero : int
zero
is the integer0
.val one : int
one
is the integer1
.val minus_one : int
minus_one
is the integer-1
.val neg : int -> int
neg x
is~-x
.val add : int -> int -> int
add x y
is the additionx + y
.val sub : int -> int -> int
sub x y
is the subtractionx - y
.val mul : int -> int -> int
mul x y
is the multiplicationx * y
.val div : int -> int -> int
div x y
is the divisionx / y
.val rem : int -> int -> int
rem x y
is the remainderx mod y
.val succ : int -> int
succ x
isadd x 1
.val pred : int -> int
pred x
issub x 1
.val abs : int -> int
abs x
is the absolute value of x. That isx
ifx
is positive andneg x
ifx
is negative.
Warning. This may be negative if the argument isInt.min_int
.val max_int : int
max_int
is the greatest representable integer,2{^[Sys.int_size - 1]} - 1
.val min_int : int
min_int
is the smallest representable integer,-2{^[Sys.int_size - 1]}
. -
Strings
-
Use
^
to concatenate two strings. -
\
is to be used to escape"
and\
. -
Quoted strings
#> {|This is a quoted string, here, neither \ nor " are special characters|};
#> {delimiter|the end of this|}quoted string is here|delimiter} -
String
moduleval empty : string
Return an empty string. val length : string -> int
Return the length of the string. val split_on_char : char -> string -> string list
split_on_char sep s
is the list of all (possibly empty) substrings ofs
that are delimited by the charactersep
.
-
Use
-
Options
-
create an option containing
42
Some 42
-
create an empty option
None
-
pattern matching on an option
#> let extract o =
match o with
| Some i -> string_of_int i
| None -> "";; -
get the value if not
None
, otherwise a default value#> Option.value (Some 77) ~default:(-1);;
-
Option
moduleval is_none : 'a option -> bool
is_none o
is true if and only ifo
isNone
.val is_some : 'a option -> bool
is_some o
is true if and only ifo
isSome o
.val get : 'a option -> 'a
get o
isv
ifo
isSome v
and raise otherwise.
RaisesInvalid_argument
ifo
isNone
.val value : 'a option -> default:'a -> 'a
value o ~default
isv
ifo
isSome v
anddefault
otherwise.val map : ('a -> 'b) -> 'a option -> 'b option
map f o
isNone
ifo
isNone
andSome (f v)
ifo
isSome v
.
-
create an option containing
-
Lazy
-
create a lazy expression
#> let a = lazy ( expr );;
-
force the evaluation of the expression, the result is memoized
#> let b = force a;;
-
create a lazy expression
-
Lists
- An ordered collection of any number of elements sharing the same type.
-
Syntax
#> [];;
#> [1];;
#> [1; 2];;
#> [1; 2; 3];; -
head and tail of a list
#> List.hd [1; 2; 3];;
- : int = 1
#> List.tl [1; 2; 3];;
- : int list = [2; 3] -
The cons operator
::
adds one element to the front of a list.#> 1 :: [2; 3];;
-
The append operator
@
combines two lists.#> [1] @ [2; 3];;
-
List
moduleval cons : 'a -> 'a list -> 'a list
Add one element to the front of a list. cons x xs
is the same asx :: xs
.val hd : 'a list -> 'a
Return the first element of the given list.
RaisesFailure
if the list is empty.val tl : 'a list -> 'a list
Return the given list without its first element.
RaisesFailure
if the list is empty.val length : 'a list -> int
Return the length of the list. val compare_lengths : 'a list -> 'b list -> int
Compare the lengths of two lists, the computation stops after reaching the end of the shortest list. val compare_length_with : 'a list -> int -> int
Compare the length of a list to an integer, the computation stops after at most len
iterations on the list.val nth : 'a list -> int -> 'a
Return the n-th element of the given list.
RaisesFailure
if the list is too short;Invalid_argument
ifn
is negative.val nth_opt : 'a list -> int -> 'a option
Return the n-th element of the given list. Return None
if the list is too short.
RaisesInvalid_argument
ifn
is negative.val append : 'a list -> 'a list -> 'a list
Concatenate two lists. Same function as the infix operator @
. Not tail-recursive (length of the first argument). The@
operator is not tail-recursive either.val concat : 'a list list -> 'a list
val flatten : 'a list list -> 'a list
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list). val map : ('a -> 'b) -> 'a list -> 'b list
Apply function f
toa1, …, an
, and builds the list[f a1; …; f an]
. Not tail-recursive.val iter : ('a -> unit) -> 'a list -> unit
iter f [a1; …; an]
applies functionf
in turn to[a1; …; an]
. It is equivalent tof a1; f a2; …; f an
.val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
map2 f [a1; …; an] [b1; …; bn]
is[f a1 b1; …; f an bn]
. Not tail-recursive.
RaisesInvalid_argument
if the two lists are determined to have different lengths.val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit
iter2 f [a1; …; an] [b1; …; bn]
calls in turnf a1 b1; …; f an bn
.
RaisesInvalid_argument
if the two lists are determined to have different lengths.val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
fold_right f [a1; …; an] init
isf a1 (f a2 (… (f an init) …))
. Not tail-recursive.val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
fold_left f init [b1; …; bn]
isf (… (f (f init b1) b2) …) bn
.val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b list -> 'a * 'c list
fold_left_map
is a combination offold_left
and map that threads an accumulator through calls tof
.val concat_map : ('a -> 'b list) -> 'a list -> 'b list
concat_map f l
gives the same result asList.concat (List.map f l)
. Tail-recursive.val mem : 'a -> 'a list -> bool
mem a list
is true if and only ifa
is equal to an element oflist
.val memq : 'a -> 'a list -> bool
Same as List.mem
, but uses physical equality instead of structural equality to compare list elements.val for_all : ('a -> bool) -> 'a list -> bool
for_all f [a1; …; an]
checks if all elements of the list satisfy the predicatef
. That is, it returns(f a1) >> (f a2) >> … >> (f an)
for a non-empty list andtrue
if the list is empty.val exists : ('a -> bool) -> 'a list -> bool
exists f [a1; …; an]
checks if at least one element of the list satisfies the predicatef
. That is, it returns(f a1) || (f a2) || … || (f an)
for a non-empty list andfalse
if the list is empty.val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as List.for_all
, but for a two-argument predicate.
RaisesInvalid_argument
if the two lists are determined to have different lengths.val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as List.exists
, but for a two-argument predicate.
RaisesInvalid_argument
if the two lists are determined to have different lengths.val find : ('a -> bool) -> 'a list -> 'a
find f l
returns the first element of the listl
that satisfies the predicatef
.
RaisesNot_found
if there is no value that satisfiesf
in the listl
.val find_opt : ('a -> bool) -> 'a list -> 'a option
find_opt f l
returns the first element of the listl
that satisfies the predicatef
. ReturnsNone
if there is no value that satisfiesf
in the listl
.val filter : ('a -> bool) -> 'a list -> 'a list
val find_all : ('a -> bool) -> 'a list -> 'a list
filter f l
returns all the elements of the listl
that satisfy the predicatef
. The order of the elements in the input list is preserved.
find_all
is another name forfilter
.val partition : ('a -> bool) -> 'a list -> 'a list * 'a list
partition f l
returns a pair of lists(l1, l2)
, wherel1
is the list of all the elements ofl
that satisfy the predicatef
, andl2
is the list of all the elements ofl
that do not satisfyf
. The order of the elements in the input list is preserved.val assoc : 'a -> ('a * 'b) list -> 'b
assoc a l
returns the value associated with keya
in the list of pairsl
. That is,assoc a [ …; (a,b); …] = b
if(a,b)
is the leftmost binding ofa
in listl
.
RaisesNot_found
if there is no value associated witha
in the listl
.val assoc_opt : 'a -> ('a * 'b) list -> 'b option
assoc_opt a l
returns the value associated with keya
in the list of pairsl
. That is,assoc a [ …; (a,b); …] = Some b
if(a,b)
is the leftmost binding ofa
in listl
.ReturnsNone
if there is no value associated witha
in the listl
.val split : ('a * 'b) list -> 'a list * 'b list
Transform a list of pairs into a pair of lists: split [(a1,b1); …; (an,bn)]
is([a1; …; an], [b1; …; bn])
. Not tail-recursive.val combine : 'a list -> 'b list -> ('a * 'b) list
Transform a pair of lists into a list of pairs: combine [a1; …; an] [b1; …; bn]
is[(a1,b1); …; (an,bn)]
. Not tail-recursive.
RaisesInvalid_argument
if the two lists have different lengths.val sort : ('a -> 'a -> int) -> 'a list -> 'a list
Sort a list in increasing order according to a comparison function.
-
Tuples
- A fixed number of elements together. This is useful when a function returns several values, we no not have to define a record.
-
Syntax
#> (true, 0.0, 0.45, 0.73, "french blue");;
-
Destructuring
let
#> let v = (1, true, "bonjour", 'a');;
val v : int * bool * string * char = (1, true, "bonjour", 'a')
#> let (a,b,c,d) = v;;
val a : int = 1
val b : bool = true
val c : string = "bonjour"
val d : char = 'a'#> let a,b,c,d = v;;
val a : int = 1
val b : bool = true
val c : string = "bonjour"
val d : char = 'a' -
We can use tuple as a function argument. This gives a nice syntax, but this is less performant because a tuple need to be built.
#> let f (x,y) = x + y;;
val f : int * int -> int = <fun>
#> f (1,2);;
- : int = 3 -
syntax to define a type
#> type square = int * int * int * int * int * int * int * int * int;;
#> let print_square (sq: square) : unit =
let (a ,b, c, d, e, f, g, h, i) = sq
in Printf.printf "%d %d %d\n%d %d %d\n%d %d %d\n" a b c d e f g h i;;
-
Records
- A fixed number of labelled elements.
-
Syntax
#> type colour = {websafe : bool; r : float; g : float; b : float; name : string};;
#> let b = {websafe = true; r = 0.0; g = 0.45; b = 0.73; name = "french blue"};; -
Use the dot notation to get a field
#> b.name;;
#> match b with {websafe = _; r = _; g = _; b = _; name = n} -> n;;
#> match b with {websafe ; r ; g ; b ; name } -> name;;;
-
It is possible to copy a record while modifying some fields
#> let c = { b with websafe = false; name = "bleu français" };;
-
Records may be mutable
#> type person = {first_name : string; surname : string; mutable age : int};;
#> let birthday p = p.age <- p.age + 1;; -
Record types may be recursive
#> type node = {value : int; next : node};;
-
Fixed-length array
-
A mutable compound data type contain elements of the same type.
Its elements may be accessed in constant time. -
Syntax
#> let arr = [|1; 2; 3|];;
#> arr.(0) <- 0;; -
Array
moduleval length : 'a array -> int
Return the length (number of elements) of the given array. val get : 'a array -> int -> 'a
get a n
returns the element numbern
of arraya
. The first element has number0
.
You can writea.(n)
instead ofget a n
.
-
A mutable compound data type contain elements of the same type.
-
Variants
-
A variant type is a collection of constructors.
type point = float * float
type shape =
| Point of point
| Circle of point * float (* center and radius *)
| Rect of point * point (* lower-left and upper-right corners *)
let area = function
| Point _ -> 0.0
| Circle (_, r) -> Float.pi *. (r ** 2.0)
| Rect ((x1, y1), (x2, y2)) ->
let w = x2 -. x1 in
let h = y2 -. y1 in
w *. h
let center = function
| Point p -> p
| Circle (p, _) -> p
| Rect ((x1, y1), (x2, y2)) -> ((x2 +. x1) /. 2.0, (y2 +. y1) /. 2.0)
-
A variant type is a collection of constructors.
-
The Basic types are
-
Printing
-
Built-in print functions:
print_char
,print_string
,print_int
, andprint_float
. -
print_endline "str"
prints a string followed by a newline. -
print_newline ())
prints a newline. -
Printf
moduleval printf : ('a, out_channel, unit) format -> 'a
Format a message and print it on stdout
.val eprintf : ('a, out_channel, unit) format -> 'a
Format a message and print it on stderr
.
-
Built-in print functions:
-
Stdlib
module- This module is automatically opened at the beginning of each compilation.
-
val ignore : 'a -> unit
Discard the value of its argument and return ()
. For instance,ignore(f x)
discards the result of the side-effecting functionf
. It is equivalent tof x; ()
, except that the latter may generate a compiler warning; writingignore(f x)
instead avoids the warning.val print_char : char -> unit
Print a character on standard output. val print_string : string -> unit
Print a string on standard output. val print_bytes : bytes -> unit
Print a byte sequence 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 and flush 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. val float_of_int : int -> float
val float : int -> float
Convert an integer to floating-point. val int_of_float : float -> int
val truncate : float -> int
Truncate the given floating-point number to an integer. The result is unspecified if the argument is nan or falls outside the range of representable integers. val int_of_string_opt : string -> int option
Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with 0u
), in hexadecimal (if it begins with0x
or0X
), in octal (if it begins with0o
or0O
), or in binary (if it begins with0b
or0B
).
The0u
prefix reads the input as an unsigned integer in the range[0, 2*max_int+1]
. If the input exceedsmax_int
it is converted to the signed integermin_int + input - max_int - 1
.
The_
(underscore) character can appear anywhere in the string and is ignored.
ReturnNone
if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in typeint
.val int_of_string : string -> int
Same as int_of_string_opt
, but raiseFailure "int_of_string"
instead of returningNone
.val fst : 'a * 'b -> 'a
Return the first component of a pair. val snd : 'a * 'b -> 'b
Return the second component of a pair.
-
Sys
moduleval argv : string array
The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. let seed = int_of_string Sys.argv.(1)
-
Random
moduleval int : int -> int
Return a random integer between 0 (inclusive) and bound (exclusive). bound must be greater than 0 and less than 230. val init : int -> unit
Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. val full_init : int array -> unit
Same as Random.init
but takes more data as seed.val self_init : unit -> unit
Initialize the domain-local generator with a random seed chosen in a system-dependent way. If /dev/urandom
is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state).
let _ = Random.self_init ()
let a = Random.int 999 -
Exceptions
-
define an exception
#> exception Error ;;
exception Error
#> exception Unix_error of string ;;
exception Unix_error of string -
raise an exception
#> raise ( Unix_error "File not found" ) ;;
Exception: Unix_error "File not found". -
catching an exception
#> let safe_divide x y =
try ( x / y ) with
| Division_by_zero -> 666 ;;
val safe_divide : int -> int -> int = <fun>
#> safe_divide 1 0 ;;
- : int = 666 -
There are some predefined exceptions.
-
Exit
can be used to terminate an iteration, like a break statement. -
Not_found
should be raised when searching failed because there isn't anything satisfactory to be found. -
Invalid_argument
should be raised when a parameter can't be accepted.
It can be raised usingval invalid_arg : string -> 'a
-
Failure
should be raised when a result can't be produced.
It can be raised usingval failwith : string -> 'a
-
-
Example: verifying the command lines arguments
let start = if (Array.length Sys.argv) != 2 then invalid_arg ("Syntax: " ^ Sys.argv.(0) ^ " <seed>"); int_of_string Sys.argv.(1)
-
define an exception
-
Loops
-
Three types of loops
-
while e1 do e2 done
-
for x=e1 to e2 do e3 done
-
for x=e1 downto e2 do e3 done
-
-
Three types of loops
-
Zarith: arithmetic and logical operations over arbitrary-precision integers
-
example
open Z
let c =
let a = Z.of_string "12345678901234567890" in
let b = Z.of_string "98765432109876543210" in
a + b
let _ = Printf.printf "Sum: %s\n" (Z.to_string c);
-
Z
moduletype t
Type of integers of arbitrary length. exception Overflow
Raised by conversion functions when the value cannot be represented in the destination type. val zero : t
The number 0. val one : t
The number 1. val minus_one : t
The number -1. val of_int : int -> t
Converts from a base integer. val to_int : t -> int
Converts to a base integer. May raise an Overflow
.val of_string : string -> t
Converts a string to an integer.
An optional-
prefix indicates a negative number, while a+
prefix is ignored.
An optional prefix0x
,0o
, or0b
(following the optional-
or+
prefix) indicates that the number is, represented, in hexadecimal, octal, or binary, respectively.
Otherwise, base 10 is assumed. (Unlike C, a lone0
prefix does not denote octal.)val to_string : t -> string
Gives a human-readable, decimal string representation of the argument. val add : t -> t -> t
val (+) : t -> t -> t
Addition. val succ : t -> t
Returns its argument plus one. val pred : t -> t
Returns its argument minus one. val sub : t -> t -> t
val (-) : t -> t -> t
Subtraction . val shift_left : t -> int -> t
Shifts to the left. Equivalent to a multiplication by a power of 2. The second argument must be non-negative. val shift_right : t -> int -> t
Shifts to the right. This is an arithmetic shift, equivalent to a division by a power of 2 with rounding towards -oo. The second argument must be non-negative. val shift_right_trunc : t -> int -> t
Shifts to the right, rounding towards 0. This is equivalent to a division by a power of 2, with truncation. The second argument must be non-negative
-
example
-
Installation
-
Using Docker
-
a simple installation process:
docker run --name ocaml -it ocaml/opam:ubuntu-22.04-ocaml-4.13 bash
opam install utop
exit -
then use this container with
docker start ocaml
docker exec -it ocaml basheval $(opam env)
utop -
at the end, exit from utop
exit 0;;
exit
docker stop ocaml
-
a simple installation process:
-
Using Docker
-
Set up the environment
-
on Linux
#> eval $(opam env)
-
on all OSes, to run a command with the environment being set up
#> opam exec <cmd>
-
on Linux
-
Tools
-
ocamlc
-
Compile to bytecodes
#> ocamlc foobar.ml
#> ./camlprog.exe
-
ocamlc
can take in input-
.ml
which are taken to be source files -
.mli
which are taken to be source files for compilation unit interfaces -
.cmo
which are taken to be compiled object bytecode -
.cma
which are taken taken to be libraries of object bytecode (generated withocaml -a
) -
.c
which are taken taken to be C sources files, assed to the C compiler, which generates a.o
/.obj
object file -
.o
(.obj
on Windows) which are assumed to be C object files -
.a
(.lib
on Windows) which are assumed to be C libraries -
.so
(.dll
on Windows) which are assumed to be C shared libraries
-
-
When compiling a
.ml
-
If a
.mli
file already exists,ocamlc
checks that it checks that the.ml
repects it.
Otherwise it generates one. -
ocamlc
generates a.cmo
. -
ocamlc
generates a bytecode filea.out
(camlprog.exe
on Windows).
-
If a
-
Compile to bytecodes with debug information and run with stacktrace dump
#> ocamlc -g foobar.ml
#> OCAMLRUNPARAM=b ./camlprog.exe
-
Compile to bytecodes
-
ocamlrun
-
Run a bytecode file.
Most of the time, bytecode files can be run directly, without usingocamlrun
.
-
Run a bytecode file.
-
ocamldebug
-
Start the debugger
#> ocamldebug camlprog.exe
-
Start the debugger
-
opam
-
Initialise the
~/.opam
directory#> opam init
-
Synchronize opam's database with the package repositories
#> opam update
-
List installed packages
#> opam list
-
List all available packages
#> opam list -a
-
Install the package
<name>
#> opam install <name>
-
It is possible to constrain the version to install
#> opam install <name>.<version>
#> opam install "<name>>=<version>"
-
Upgrade package
<name>
#> opam upgrade <name>
-
Upgrade all installed package
<name>
#> opam upgrade
-
Uninstall the package
<name>
#> opam remove <name>
-
Prints appropriate shell variable assignments to stdout
#> opam env
#> eval $(opam env)
-
Initialise the
-
dune
-
Initialise the project
<project_name>
#> dune init proj <project_name>
-
Build the project in the current directory
#> dune build
-
Run the tests of the project in the current directory
#> dune test
-
Run the project
#> dune exec <project_name>
-
Initialise the project
-