Tutorial OCaml
4 pages
English
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres
4 pages
English
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres

Description

OCaml E nvironment Set up Ocaml is avai lable for download here : http://caml.inri a.fr/download.en.h tmlThere are install ation instruct ions provided for Windows and Unix based operating s ystems. O nce installed, t ype ocaml in a ter minal windo w to start the inter active 'top leve l' OCam l env ironment. If top level starts up, y ou will see som ething like :Objective Caml version 3.10.0#Primitive Types The basic OCa ml t ypes are int, float, bool, char, string and unit (which is a return t ype similar to ' void' in C). When na ming values, we do not have to declare an y of these t ypes expli citly thanks to OCam l's t ype infer ence engine. So to nam e a charact er for exa mple, we u se th e let ke yword as follows:#let x = 'a';;In the inter active Top Leve l environ ment, the co mpiler will respond to the above state ment with :val x : char = 'a'This tells u s tha t the nam e x is as sociated with t ype char and holds the value ' a'.The state ment#let x = 2;;will define an integ er t ype with the value 2. If w e in tend to define a float, we u se the stat ement #let x = 2.0;;This is im portant to note especi ally because OCa ml is stati cally t yped, me aning we will not be able to simply convert x from an int to a float after it is defin ed. On a rela ted not e, the standard ari thmetic operators are not overloaded in OCam l as the y are in m any languages. Addition of in tegers is expressed using the s ymbol ' +' w hile the s ymbol ...

Informations

Publié par
Nombre de lectures 13
Langue English

Extrait

OCaml E nvironment Set up
Ocaml is avai lable for download here : http://caml.inri a.fr/download.en.h tml
There are install ation instruct ions provided for Windows and Unix based operating s ystems. O nce
installed, t ype ocaml in a ter minal windo w to start the inter active 'top leve l' OCam l env ironment. If
top level starts up, y ou will see som ething like :
Objective Caml version 3.10.0
#
Primitive Types
The basic OCa ml t ypes are int, float, bool, char, string and unit (which is a return t ype
similar to ' void' in C). When na ming values, we do not have to declare an y of these t ypes expli citly
thanks to OCam l's t ype infer ence engine. So to nam e a charact er for exa mple, we u se th e let ke yword
as follows:
#let x = 'a';;
In the inter active Top Leve l environ ment, the co mpiler will respond to the above state ment with :
val x : char = 'a'
This tells u s tha t the nam e x is as sociated with t ype char and holds the value ' a'.
The state ment
#let x = 2;;
will define an integ er t ype with the value 2. If w e in tend to define a float, we u se the stat ement
#let x = 2.0;;
This is im portant to note especi ally because OCa ml is stati cally t yped, me aning we will not be able to
simply convert x from an int to a float after it is defin ed. On a rela ted not e, the standard ari thmetic
operators are not overloaded in OCam l as the y are in m any languages. Addition of in tegers is
expressed using the s ymbol ' +' w hile the s ymbol ' +.' is u sed to express addit ion of floa ts.
OCaml will not i mplicitly cast an int eger to a float, so
#2.0 +. 2;;
yields the t ype error
This expression has type float but is here used with type float
(The language was developed and written in French. So me of the transl ations sound lik e Yoda s peak.)
We can, ho wever, expli citly cast an int to a float and vice versa using the bui lt in functions
float_of_int and int_of_float respectiv ely. -
Addition of floats:
#2.0 +. (float_of_int 2);;
- : float = 4.
Addition of integ ers:
#(int_of_float 2.0) + 2;;
: int = 4
Other casting funct ions:
• char_of_int
• int_of_char
• string_of_int
The ' of' na ming convent ion m ay seem odd at first, but i t m akes sen se when we consider that these
functions are m athematically defined functions. That is, when we sa y “ a funct ion f of a set X” we are
speaking of a funct ion whose dom ain is the set X.
Also note that no paren theses or bracke ts are requir ed around para meters in funct ion cal ls. If mo re th an
one param eter is passed into a function, a space is u sed as a deli miter.
Let It Be
The let ke yword is also used to defin e functions. Since OCam l infers t ype, we don 't specif y the t ypes
of input para meters. The para meter t ypes are inferred from the function defini tion.
#let square x =
x * x;;
val square : int → int <fun>
The t ype inf erence engine knew that th e input and output are both of t ype int bec ause of the *
operator. In the case that no t ype specifi c t ype is required in the func tion defin ition, an y t ype of input
type is perm itted. This function takes two input para meters and returns a list contain ing the m:
#let toList x y =
[x; y];;
val toList : 'a -> 'a -> 'a list = <fun>
No return state ment is requir ed. Instead, the last expression in the function defini tion is return ed as
output.
We can also define a loca l substitut ion of sorts using the co mbination let <name> = <expression> in.
This state ment essenti ally me ans 'sub stitute <expression> for <name> for ever y following occurr ence
of <name> unti l the s ymbol ;;'. For exam ple:
#let average x y z =
let sum =
x +. y +. z in
sum /. 3.0;;
In the last l ine, sum is repl aced with x +. y +. z to co mpute the average.
References
So far al l of the me mory alloc ations we've m ade have been i mmutable. If we need to be abl e to chang e
a variable's valu e, we need to nam e a referenc e. # let x = ref 5;;
Now we have a na med referen ce which holds the address of an int eger with the valu e 5. If we “change
the value” of x
# x := 20;;
we are actua lly chang ing the address held b y x. The reference now holds the address of an int eger with
the value 20.

Recursion
Recursive functions are essentia l to the funct ional program ming paradig m. To define a recursive
function, y ou m ust u se th e rec ke yword in the funct ion defini tion as follows:
# let rec fib n =
if n<=0 then 0
else begin
if n=1 then 1 else (fib (n-1)) + (fib (n-2))
end;;
This function returns the nth Fibonacci num ber. We haven't addressed if...then statements y et, but
they are si milar to what y ou have probabl y seen before. Notice that we don 't an y notat ion to group
simple stat ements, and that we u se begin and end to group mor e than one state ment in an if or else
block.
Modules
All com piled code is contain ed in a modu le. Let's escape the top lev el env ironment (ctrl+z in Unix,
probably ctrl+c in Windows) and crea te a mo dule. U sing y our favori te text ed itor, create a fil e na med
helloWorld. ml. Then ent er the following code :
print_string “Hello World”
In a com mand- line environ ment, naviga te to the fi le y ou ju st creat ed and t ype
(If y ou're using Windows...)
> ocamlc -o helloWorld.exe helloWorld.ml
(If y ou're using Unix...)
>ocamlc -o helloWorld helloWorld.ml
Then cal l the executab le y ou j ust creat ed.
>helloWorld.exe
or
>helloWorld
You should rece ive the expect ed one l ine of outpu t. Congratul ations on creating y our first OCa ml
module.Lots of modu les have been m ade avai lable to y ou via y our OCam l install ation. To use anoth er m odule
in y our code, y ou can either u se the open ke yword at the top of the fil e, or si mply use dot nota tion to
specify the m odule na me and m ethod to call. For exam ple, we can cre ate sim ple graphica l displa ys
using the Graphics m odule. (In a windows environm ent, y ou need to first crea te a custom top level b y
running this co mmand in a com mand window: ocamlmktop -o ocaml-graphics graphics.cma ).
Create a file nam ed graphi csTest.m l and open it in a t ext edi tor. Fir st, we want to inc lude th e graphics
module, and show a graph:
open Graphics;;
open_graph " 640x480";;
Now we 'll draw the si mplest recogn izable figure I could think of. The draw_circle m ethod tak es
three ar guments - the first two are the center in x, y coordin ates (where th e origin is the botto m lef t of
the graph) and the last ar gument is the radius. The arc is si milar, but with a vertic al and horizonta l
radius, and a beginning and ending angle in degrees. (Y ou can read the docum entation for the graphi cs
module here : http ://caml. inria.fr /pub/docs/ manual- ocaml/l ibref/Graphi cs.htm l).
draw_circle 250 250 20;
draw_circle 350 250 20;
draw_circle 300 200 120;
draw_arc 300 200 60 60 180 360;
read_line ();;
To co mpile this, we need to include the graphics m odule. On Windows:
ocamlc graphics.cma graphicsTest.ml -o graphicsTest.exe
Linux/Unix:
ocamlc graphics.cma graphicsTest.ml -o graphicsTest
Then j ust run the output fi le to see the graph!

  • Univers Univers
  • Ebooks Ebooks
  • Livres audio Livres audio
  • Presse Presse
  • Podcasts Podcasts
  • BD BD
  • Documents Documents