Objective Caml

Objective Caml

Infobox programming language
name = Objective Caml

paradigm = multi-paradigm: imperative, functional, object-oriented
developer = INRIA
latest_release_version = 3.10.2
latest_release_date = Release date and age|2008|02|29
operating_system = Cross-platform
genre = Programming language
influenced_by = Caml Light, Standard ML
influenced = Scala
dialects = F#, JoCaml, MetaOCaml, OcamlP3l
license = Q Public License (compiler)
LGPL (library)
website = [http://caml.inria.fr/ http://caml.inria.fr/]

Objective Caml (OCaml) is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996. OCaml is an open source project managed and principally maintained by INRIA.

OCaml extends the core Caml language with object-oriented constructs.

OCaml's toolset includes an interactive toplevel interpreter, a bytecode compiler, and an optimizing native code compiler. It has a large standard library that makes it useful for many of the same applications as Python or Perl, as well as robust modular and object-oriented programming constructs that make it applicable for large-scale software engineering.

OCaml is the successor to Caml Light. The acronym CAML originally stood for "Categorical Abstract Machine Language", although OCaml abandons this abstract machine.

Philosophy

ML-derived languages are best known for their static type systems and type-inferring compilers. OCaml unifies functional, imperative, and object-oriented programming under an ML-like type system.

OCaml's static type system eliminates a large class of programmer errors that may cause problems at runtime. However, it also forces the programmer to conform to the constraints of the type system, which can require careful thought and close attention. A type-inferring compiler greatly reduces the need for manual type annotations (for example, the data type of variables and the signature of functions usually do not need to be explicitly declared, as they do in Java). Nonetheless, effective use of OCaml's type system can require some sophistication on the part of the programmer.

OCaml is perhaps most distinguished from other languages with origins in academia by its emphasis on performance. Firstly, its static type system renders runtime type mismatches impossible, and thus obviates runtime type and safety checks that burden the performance of dynamically typed languages, while still guaranteeing runtime safety (except when array bounds checking is turned off, or when certain type-unsafe features like serialization are used; these are rare enough that avoiding them is practically possible).

Aside from type-checking overhead, functional programming languages are, in general, challenging to compile to efficient machine language code, due to issues such as the funarg problem. In addition to standard loop, register, and instruction optimizations, OCaml's optimizing compiler employs static program analysis techniques to optimize value boxing and closure allocation, helping to maximize the performance of the resulting code even if it makes extensive use of functional programming constructs.

Xavier Leroy has cautiously stated that "OCaml delivers at least 50% of the performance of a decent C compiler" [http://lwn.net/Articles/19378/ Linux Weekly News] .] , and benchmarks have shown that this is generally the case [http://shootout.alioth.debian.org/ The Computer Language Benchmarks Game] .] . Some functions in the OCaml standard library are implemented with faster algorithms than equivalent functions in the standard libraries of other languages. For example, the implementation of set union in the OCaml standard library is asymptotically faster than the equivalent function in the standard libraries of imperative languages (e.g. C++, Java) because the OCaml implementation exploits the immutability of sets in order to reuse parts of input sets in the output (persistence).

Features

OCaml features: a static
type system, type inference,
parametric polymorphism, tail recursion,
pattern matching,
first class lexical closures,
functors (parametric modules), exception handling, andincremental generational automatic garbage collection.

OCaml is particularly notable for extending ML-style type inference to an object system in a general purpose language. This permits structural subtyping, where object types are compatible if their method signatures are compatible, regardless of their declared inheritance; an unusual feature in statically-typed languages.

A foreign function interface for linking to C primitives is provided, including language support for efficient numerical arrays in formats compatible with both C and FORTRAN. OCaml also supports the creation of libraries of OCaml functions that can be linked to a "main" program in C, so that one could distribute an OCaml library to C programmers who have no knowledge nor installation of OCaml.

The OCaml distribution contains:
*An extensible parser and macro language named Camlp4, which permits the syntax of OCaml to be extended or even replaced
*Lexer and parser tools called ocamllex and ocamlyacc
*Debugger which supports stepping backwards to investigate errors
*Documentation generator
*Profiler — for measuring performance
*Numerous general purpose libraries

The native code compiler is available for many platforms, including Unix, Microsoft Windows, and Apple Mac OS X. Excellent portability is ensured through native code generation support for major architectures: IA-32, IA-64, AMD64, HP/PA; PowerPC, SPARC, Alpha, MIPS, and StrongARM.

OCaml bytecode and native code programs can be written in a multithreaded style, with preemptive context switching. However, because the garbage collector is not designed for concurrency, symmetric multiprocessing is not supported [http://caml.inria.fr/pub/ml-archives/caml-list/2002/11/64c14acb90cb14bedb2cacb73338fb15.en.html Xavier Leroy's "standard lecture" on threads] ] . OCaml threads in the same process execute by time sharing only.

Code examples

Snippets of OCaml code are most easily studied by entering them into the "top-level". This is an interactive OCaml session that prints the inferred types of resulting or defined expressions. The OCaml top-level is started by simply executing the "ocaml" program:

$ ocaml Objective Caml version 3.09.0 #

Code can then be entered at the "#" prompt. For example, to calculate 1+2*3:

# 1 + 2 * 3;; - : int = 7

OCaml infers the type of the expression to be "int" (a machine-precision integer) and gives the result "7".

Hello World

The following program "hello.ml":

print_endline "Hello world!";;

can be compiled to bytecode:

$ ocamlc hello.ml -o hello

and executed:

$ ./hello Hello world! $

Quicksort

Ocaml lends itself to the concise expression of recursive algorithms. The following code example implements the quicksort algorithm to sort a list into increasing order.

let rec quicksort = function
[] -> []
pivot :: rest -> let is_less x = x < pivot in let left, right = List.partition is_less rest in quicksort left @ [pivot] @ quicksort right

Birthday paradox

The following program calculates the smallest number of people in a room for whom the probability of completely unique birthdays is less than 50% (the so-called birthday paradox, where for 1 person the probability is obviously 100%, for 2 it is 364/365, etc.) (answer = 23).

let year_size = 365.;; let rec birthday_paradox prob people = let prob' = (year_size -. float people) /. year_size *. prob in if prob' < 0.5 then Printf.printf "answer = %d " (people+1) else birthday_paradox prob' (people+1) ;; birthday_paradox 1.0 1;;

Church numerals

The following code defines a Church encoding of natural numbers, with successor (succ) and addition (add). A Church numeral n is a higher-order function that accepts a function f and a value x and applies f to x exactly n times. To convert a Church numeral from a functional value to a string, we pass it a function which prepends the string "S" to its input and the constant string "0".

let zero f x = xlet succ n f x = f (n f x)let one = succ zerolet two = succ (succ zero)let add n1 n2 f x = n1 f (n2 f x)let to_string n = n (fun k -> "S" ^ k) "0"let _ = print (add (succ two) two)

Arbitrary-precision factorial function (libraries)

A variety of libraries are directly accessible from OCaml. For example, OCaml has a built-in library for arbitrary precision arithmetic. As the factorial function grows very rapidly, it quickly overflows machine-precision numbers (typically 32- or 64-bits). Thus, factorial is a suitable candidate for arbitrary-precision arithmetic.

In OCaml, the Num module provides arbitrary-precision arithmetic and can be loaded into a running top-level using:

# #load "nums.cma";; # open Num;;

The factorial function may then be written using the arbitrary-precision numeric operators =/, */ and -/ :

# let rec fact n = if n =/ Int 0 then Int 1 else n */ fact(n -/ Int 1);; val fact : Num.num -> Num.num =

This function can compute much larger factorials, such as 120!:

# string_of_num (fact (Int 120));; - : string = "6689502913449127057588118054090372586752746333138029810295671352301633 55724496298936687416527198498130815763789321409055253440858940812185989 8481114389650005964960521256960000000000000000000000000000"

Triangle (graphics)

The following program "simple.ml" renders a rotating triangle in 2D using OpenGL:

let _ = ignore( Glut.init Sys.argv ); Glut.initDisplayMode ~double_buffer:true (); ignore (Glut.createWindow ~title:"OpenGL Demo"); let angle t = 10. *. t *. t in let render () = GlClear.clear [ `color ] ; GlMat.load_identity (); GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. (); GlDraw.begins `triangles; List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.] ; GlDraw.ends (); Glut.swapBuffers () in GlMat.mode `modelview; Glut.displayFunc ~cb:render; Glut.idleFunc ~cb:(Some Glut.postRedisplay); Glut.mainLoop ()

The LablGL bindings to OpenGL are required. The program may then be compiled to bytecode with:

$ ocamlc -I +lablGL lablglut.cma lablgl.cma simple.ml -o simple

or to nativecode with:

$ ocamlopt -I +lablGL lablglut.cmxa lablgl.cmxa simple.ml -o simple

and run:

$ ./simple

Far more sophisticated, high-performance 2D and 3D graphical programs are easily developed in OCaml. Thanks to the use of OpenGL, the resulting programs are not only succinct and efficient but also cross-platform, compiling without any changes on all major platforms.

Derived languages

MetaOCaml

MetaOCaml [http://www.metaocaml.org/ MetaOCaml] .] is a multi-stage programming extension of OCaml enabling incremental compiling of new machine code during runtime. Under certain circumstances, significant speedups are possible using multi-stage programming, because more detailed information about the data to process is available at runtime than at the regular compile time, so the incremental compiler can optimize away many cases of condition checking etc.

As an example: if at compile time it is known that a certain power function x -> x^n is needed very frequently, but the value of n is known only at runtime, you can use a two-stage power function in MetaOCaml:

let rec power n x = if n = 0 then .<1>. else if even n then sqr (power (n/2) x) else .<.~x *. ~(power (n-1) x)>.;;

As soon as you know n at runtime, you can create a specialized and very fast power function:

. .~(power 5 ..)>.;;

The result is:

fun x_1 -> (x_1 * let y_3 = let y_2 = (x_1 * 1) in (y_2 * y_2) in (y_3 * y_3))

The new function is automatically compiled.

Other derived languages

* [http://www.cs.washington.edu/homes/miker/atomcaml/ AtomCaml] provides a synchronization primitive for atomic (transactional) execution of code.
*F# is a Microsoft .NET language based on OCaml.
* [http://www.fresh-ocaml.org/ Fresh OCaml] which facilitate the manipulation of names and binders,
* [http://www.yl.is.s.u-tokyo.ac.jp/~furuse/gcaml/ GCaml] adding extensional polymorphism to OCaml, thus allowing overloading and type-safe marshalling,
*JoCaml which integrates constructions for developing concurrent and distributed programs,
* [http://www.cduce.org/ocaml OCamlDuce] extends OCaml with features such as XML expressions and regular-expression types.
* [http://www.pps.jussieu.fr/~dicosmo/ocamlp3l/index.html OCamlP3l] is a parallel programming system based on OCaml and the P3L language

ee also

*Caml and Caml Light, languages from which OCaml evolved
*Standard ML, another popular dialect of ML
*Extensible ML, another object-oriented dialect of ML
*O'Haskell, an object-oriented extension to the functional language Haskell

External links

* [http://caml.inria.fr/ Caml language family official website]
** [http://caml.inria.fr/humps/caml_latest.html OCaml libraries]
* [http://www.ocaml-tutorial.org/ OCaml tutorial for C, C++, Java and Perl programmers]
* [http://www.ocf.berkeley.edu/~mbh/tutorial/index.html A basic OCaml tutorial]
* [http://www.soton.ac.uk/~fangohr/software/ocamltutorial/index.html A Tutorial with a practical approach.]
* [http://www.pps.jussieu.fr/~montela/ocamil/ OCamIL] , an OCaml compiler for Microsoft .NET
* [http://shootout.alioth.debian.org/ Comparison of the speed of various languages] including Ocaml
* [http://wwwfun.kurims.kyoto-u.ac.jp/soft/olabl/ LablGL and LablGTK] OpenGL+ bindings (LablGL) and GTK+ bindings (LablGTK)
* [http://sourceforge.net/softwaremap/trove_list.php?stquery=&sort=registration_date&sortdir=desc&offset=0&form_cat=454 Newest Ocaml Projects on Sourceforge]
* [http://www.codecodex.com/wiki/index.php?title=Category:Objective_Caml OCaml code wiki on CodeCodex]
* [http://www.metaocaml.org MetaOCaml] home page
* [http://planet.ocamlcore.org/ OCamlcore Planet]
* [http://forge.ocamlcore.org/ OCamlForge]

References


Wikimedia Foundation. 2010.

Игры ⚽ Поможем решить контрольную работу

Look at other dictionaries:

  • Objective Caml — Apparu en 1987 (CAML), 1996 (OCaml) Développeur INRIA Dernière version stable 3.11.1 (le 12  …   Wikipédia en Français

  • Objective CAML — OCaml Erscheinungsjahr: 1996 Entwickler: INRIA Aktuelle Version: 3.12.1  (2011 07 04) Betriebssystem: Plattformunabhängig …   Deutsch Wikipedia

  • Objective Caml — ● np. m. ►LANG Version objet , avec des modules, de Caml. C est la seule version officiellement développée désormais …   Dictionnaire d'informatique francophone

  • Objective Caml — …   Википедия

  • Caml Light — is a lightweight and portable implementation of the Caml programming language, a dialect of the ML programming language family.It is implemented in C and compiles programs to bytecode.Caml Light is not actively developed, having been replaced by… …   Wikipedia

  • Caml — (prononcé camel, signifie Categorical Abstract Machine Language) est un langage de programmation généraliste conçu pour la sécurité et la fiabilité des programmes. Il se prête à des styles de programmation fonctionnelle, impérative et orientée… …   Wikipédia en Français

  • Caml — Infobox programming language name = Caml paradigm = multi paradigm: functional, imperative; object oriented in OCaml year = 1985 typing = strong, static designer = Gérard Huet, Guy Cousineau, Ascánder Suárez, Pierre Weis, Michel Mauny (Heavy… …   Wikipedia

  • Caml — Meta Language (ML) beschreibt eine Familie funktionaler Programmiersprachen mit statischer Typisierung, Polymorphie, automatischer Speicherbereinigung und im Allgemeinen strenger Auswertung. ML ist allerdings keine rein funktionale Sprache wie… …   Deutsch Wikipedia

  • Caml — ● /ka mail/ np. m. ►LANG Categorical Abstract Machine Language. métalangage fonctionnel (voir langage fonctionnel) mis au point à l INRIA à partir de 1984, et dont l objectif était de remplacer Pascal (et le modèle impératif) dans l enseignement… …   Dictionnaire d'informatique francophone

  • O’Caml — Objective Caml Apparu en 1987 (CAML), 1996 (OCaml) Développeur INRIA Dernière version stable 3.11.1 (le 12  …   Wikipédia en Français

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”