a concise introduction to objective caml

Upload: gteodorescu

Post on 04-Jun-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 A Concise Introduction to Objective Caml

    1/21

    A Concise Introduction to Objective Caml

    General

    Caml is a dialect of ML, developed primarily in France. This paper describes Objective Camlversion .!", or OCaml #pronounced $oh%camel$& for short' it does not (o into the object%

    oriented features of OCaml, ho)ever. Another dialect, Caml Lite !.*+, has almost identical

    synta, but the modules and many of the functions in the modules differ to a (reater or lesser

    etent.

    OCaml is case%sensitive.

    OCaml is interactive' you start it up, then you type epressions #at the prompt& to be

    evaluated. OCaml responds )ith both the value and the type of the result. -ample

    # 3 * 4;;- : int = 12

    -very epression ends )ith )ith twosemicolons.

    The# si(n is OCaml/s usual input prompt. In this paper, I typically include the prompt in

    one%line eamples, and leave it off lon(er eamples that are best loaded from a file. 0imilarly,

    I use boldface to indicate user input that is typed in at a prompt.

    To define a constant, use the form

    let pi = 3.1416;;

    Most values in OCaml are immutable#constants&. 1o)ever, arrays and strin(s can be altered

    in place.

    OCaml is anexpression-oriented lan(ua(e, not a statement%oriented lan(ua(e. That is,

    everythin( in it is considered to be an epression and to have a value. A fe) epressions that

    are eecuted for their side effects rather than their value #mostly output epressions& return

    theunit,(), as their value%%this is li2evoid in C or 3ava.

    To define a function, use one of the forms

    let sum (x, y) = x + y;; let add x y = x + y;;

    For reasons )hich )ill be eplained later, if you use parentheses around the ar(uments in the

    definition, you must use parentheses in the function call. If you omit parentheses in the

    function definition, you must omit them in the function call. 1ence

    # sum 3 5;;- : int = 8# add (3, 5);;

    - : int = 8

    http://caml.inria.fr/ocaml/http://caml.inria.fr/ocaml/http://caml.inria.fr/ocaml/http://caml.inria.fr/ocaml/
  • 8/13/2019 A Concise Introduction to Objective Caml

    2/21

    OCaml is stron(ly typed' ho)ever, OCaml almost al)ays fi(ures out the types for itself. If

    you need to help it alon(, you can specify the type of any identifier by follo)in( it by a colon

    and the name of the type, enclosed in parentheses, any)here the identifier occurs #not just in

    the parameter list&. For eample, in the function

    let max (x, y) = if x > y then x else y;;

    the variablesx andy could be int, float, char, or strin(. To define this function to use only

    char values, (ive OCaml a hint by attachin(:char to any one of the variables, anyplace in

    the function. For eample, you could say

    let max (x:ha!) (y) = if x > y then x else y;;

    o

    rlet max (x) (y:ha!) = if x > y then x else y;;

    o

    r let max (x) (y) = if x > y then (x:ha!) else y;;

    or any of several other possibilities.

    To eecute the epressions in filemyFile.sml #usually definitions that you are testin(&, use

    use "my#ile.sml";;

    4redefined OCaml functions are in (roups calledmodules, often or(ani5ed around some

    particular data type. A module is li2e a function library. The collection of these modules is

    called thecommon basis. The most common functions are in the $Pervasivesmodule,$

    )hich means you don/t have to do anythin( special to use them. For less commonly usedfunctions, you have to either prefi the function name )ith the name of the module, or you

    have to $open$ the module. Openin( the module means ma2in( the contents visible to the

    pro(ram.

    For eample, the follo)in( se6uence sho)s that the functionlength is not defined for

    strin(s until theopen tring command is issued

    # len$th "hell%";;!haracters "-: $n%o&nd val&e length# %pen &t!in$;;

    # len$th "hell%";;- : int = '

    7ote Caml Li(ht uses a sli(htly different synta%%#open string %% )here the# is

    typed by the user. The functions provided by each module are also different, often only in

    havin( a different name.

    Finally, comments are indicated as

    (* +his is a comment (* and comments may %e nested. *) *)

  • 8/13/2019 A Concise Introduction to Objective Caml

    3/21

    Identifiers

    Identifiers must be(in )ith a lowercaseletter or underscore, and may contain letters, di(its,

    underscores, and sin(le 6uotes. Most implementations also reco(ni5e accented characters,

    such as 8.

    Alphanumeric identifiers be(innin( )ith a, #sin(le 6uote& are used only for type identifiers.

    Often OCaml )ill use,a to indicate a variable #un2no)n or arbitrary& type. For eample,

    ,a listmeans a list )hose elements are of type,a. Additional variable types are indicated

    by,%,,c, and so on.

    The variable #an underscore all by itself& is used as a $)ildcard$ or $don/t care$ variable,

    for eample,

    let second ( x) = x

    Types

    There are several primitive types in OCaml' the follo)in( table (ives the most important

    ones.

    Primitive

    typeExamples Notes

    int" ' /2 -10"x""FF "o00 "%11"1

    - is used for unary minus' there is no unary 9

    "x or" starts a headecimal number'"o or"

    starts an octal number' and "% or"3 starts a binary

    number

    4loat"." -'.5 1.0e1/1.0e61/ 1e-1" Can/t start )ith a decimal point

    %ool tr&e 4alse These are the only bool values.

    string ne7n+o

    7n is ne)line,

    7t is tab,

    77 is bac2slash

    char ,a, ,7n, 0in(le 6uotes for chars, double 6uotes for strin(s.

    &nit () Thisis a value. It is the only value of its type, and is

  • 8/13/2019 A Concise Introduction to Objective Caml

    4/21

    often used )hen the value isn/t important #much li2e

    void in C&.

    There are three families of constructed types in OCaml lists, tuples, and functions.

    Listsare enclosed in brac2ets and the list elements are separated by semicolons. All elements

    in a list must be of the same type.

    Tuples are usually enclosed in parentheses, and the elements are separated by commas. The

    elements of a tuple may be of different types.

    Functionsarefirst-class objects they can be created, manipulated, passed as parameters, and

    other)ise treated li2e other 2inds of values. #1o)ever, )hen OCaml prints the result of an

    epression, and that result is a function, OCaml doesn/t print out the entire function' it just

    prints the )ordfn.& -very function ta2es eactly one parameter as input and returns onevalue as its result' ho)ever, that parameter and that result may each be of a constructed type,

    such as a tuple.

    The follo)in( table (ives a fe) eamples of constructed types. Pay special attention to the

    second column, )hich sho)s ho) OCaml epresses type information.

    Example expression Expression type Notes

    92 5 ' 0 int listLists may be of any len(th, but all elements

    must be of the same type.

    9 ,a listThe empty list can be represented by9. The

    type of this list is allo)ed to be un2no)n.

    (' hello ;1)int * string *int

    The type of a tuple depends on its len(th and

    the types in each position.

    (a%c 91 2 5)string * intlist Tuples can contain lists, and vice versa.

    (5.') 4loatA tuple )ith one element is the same as that

    one element.

    let do&%le x = 2."*. x

    4loat -< 4loatAll functions ta2e eactlyoneparameter, and

    parentheses are optional.

    let s&m (x y) = x 6 int * int -< int In this eample theoneparameter is a tuple.

  • 8/13/2019 A Concise Introduction to Objective Caml

    5/21

    y

    let hi () =

    printstringhello7n &nit -< &nit

    In this eample the oneparameter is the $unit,$

    and so is the result.

    (do&%le 9s&m)

    (4loat -< 4loat)*(int * int -