OCaml - Wikipedia [PDF]

OCaml originally named Objective Caml, is the main implementation of the programming language Caml, created by Xavier Le

7 downloads 18 Views 167KB Size

Recommend Stories


OCaml + XDuce
I want to sing like the birds sing, not worrying about who hears or what they think. Rumi

Rybczynski theorem - Wikipedia [PDF]
In the context of the Heckscher–Ohlin model of international trade, open trade between two regions often leads to changes in relative factor supplies between the regions. This can lead to an adjustment in the quantities and types of outputs between

Acute pericarditis - Wikipedia [PDF]
Acute pericarditis is a type of pericarditis usually lasting less than 6 weeks. It is by far the most common condition affecting the pericardium. Contents. [hide]. 1 Signs and symptoms; 2 Causes; 3 Pathophysiology; 4 Diagnosis; 5 Treatment; 6 Prognos

Photosynthesis - Wikipedia [PDF]
Although photosynthesis is performed differently by different species, the process always begins when energy from light is absorbed by proteins called reaction centres that contain green chlorophyll pigments. In plants, these proteins are held inside

Pulmonary consolidation - Wikipedia [PDF]
Jump to Radiology - A pulmonary consolidation is a region of (normally compressible) lung tissue that has filled with liquid, a condition marked by induration of a normally aerated lung. It is considered a radiologic sign. Consolidation occurs throug

Jemuwahan - Wikipedia [PDF]
... wa Ta'ala. Banjur lungguh sedhéla; Khutbah kapindho : Khatib miwiti khutbah kapindho kanthi maca hamdalah lan pujian marang Allah. Banjur nerusaké khutbah nganti rampung; Khatib banjur mudhun saka mimbar. Sabanjuré muadzin ngumandhangaké iqam

Acute pericarditis - Wikipedia [PDF]
Acute pericarditis is a type of pericarditis usually lasting less than 6 weeks. It is by far the most common condition affecting the pericardium. Contents. [hide]. 1 Signs and symptoms; 2 Causes; 3 Pathophysiology; 4 Diagnosis; 5 Treatment; 6 Prognos

Pulmonary consolidation - Wikipedia [PDF]
Jump to Radiology - A pulmonary consolidation is a region of (normally compressible) lung tissue that has filled with liquid, a condition marked by induration of a normally aerated lung. It is considered a radiologic sign. Consolidation occurs throug

Pulmonary consolidation - Wikipedia [PDF]
Jump to Radiology - A pulmonary consolidation is a region of (normally compressible) lung tissue that has filled with liquid, a condition marked by induration of a normally aerated lung. It is considered a radiologic sign. Consolidation occurs throug

The OCaml system release 3.12
You're not going to master the rest of your life in one day. Just relax. Master the day. Than just keep

Idea Transcript


OCaml OCaml (/o kæml / oh-KAM-l ), originally named Objective Caml, is the main implementation of the programming language Caml, created by Xavier Leroy, Jérôme Vouillon, Damien

OCaml

Doligez, Didier Rémy, Ascánder Suárez and others in 1996. A member of the ML language family, OCaml extends the core Caml language with object-oriented programming constructs. OCaml's toolset includes an interactive top-level interpreter, a bytecode compiler, an optimizing native code compiler, a reversible debugger, and a package manager (OPAM). It has a large standard library, making it useful for many of the same applications as Python or Perl, and has 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 omits

Paradigm

multi-paradigm: imperative, functional, objectoriented

Designed by

Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez

Developer

INRIA

First appeared

1996

Stable release

4.06.0 / November 3, 2017

Typing discipline

static, strong, inferred

this abstract machine.[1] OCaml is a free and open-source software project managed and principally maintained by French Institute for Research in Computer Science and Automation (INRIA). In the early 2000s, many new languages adopted elements from OCaml, most notably F# and Scala.

Contents Philosophy Features Development environment Code examples Hello World Summing a list of integers Quicksort Birthday paradox Church numerals Arbitrary-precision factorial function (libraries) Triangle (graphics) Fibonacci sequence

Implementation OCaml, C language Platform

IA-32, x86-64, Power, SPARC, ARM 32-64

OS

Cross-platform: Unix, macOS, Windows

License

LGPL

Filename extensions

.ml, .mli

Website

ocaml.org (http:// ocaml.org)

Higher-order functions Derived languages MetaOCaml Other derived languages Software written in OCaml Commercial users See also References External links

Dialects

Philosophy

F#, JoCaml, MetaOCaml, OcamlP3l, Reason

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-

Influenced by

like type system. Thus, programmers need not be highly familiar with the pure functional language paradigm to use OCaml.

Caml Light, Cool, Standard ML

OCaml's static type system can help eliminate problems at runtime. However, it also forces the programmer to conform to the constraints of the type system, which can require careful

Influenced

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 need not be declared explicitly, as they do in languages like Java or C#. Nonetheless, effective use of OCaml's type system can require some sophistication on the part of a programmer.

ATS, Elm, F#, F*, Haxe, Opa, Rust, Scala

OCaml is perhaps most distinguished from other languages with origins in academia by its emphasis on performance. Its static type system prevents runtime type mismatches and thus

Objective Caml at Wikibooks

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 some type-unsafe features like serialization are used. These are rare enough that avoiding them is quite possible in practice. 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. Along with standard loop, register, and instruction optimizations, OCaml's optimizing compiler employs static program analysis methods 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 stated that "OCaml delivers at least 50% of the performance of a decent C compiler",[2] but a direct comparison is impossible. 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 in theory 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 to reuse parts of input sets in the output (see persistent data structure).

Features OCaml features: a static type system, type inference, parametric polymorphism, tail recursion, pattern matching, first class lexical closures, functors (parametric modules), exception handling, and incremental generational automatic garbage collection. OCaml is 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 creating libraries of OCaml functions that can be linked to a main program in C, so that an OCaml library can be distributed to C programmers who have no knowledge or 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 that supports stepping backwards to investigate errors Documentation generator Profiler – to measure performance Many general-purpose libraries The native code compiler is available for many platforms, including Unix, Microsoft Windows, and Apple macOS. Portability is achieved through native code generation support for major architectures: IA-32, X86-64 (AMD64), Power, SPARC, ARM, and ARM64.[3] OCaml bytecode and native code programs can be written in a multithreaded style, with preemptive context switching. However, because the garbage collector of the INRIA OCaml system (which is the only currently available full implementation of the language) is not designed for concurrency, symmetric multiprocessing is unsupported.[4] OCaml threads in the same process execute by time sharing only. There are however several libraries for distributed computing such as Functory (http://functory.lri.fr/About.html) and ocamlnet/Plasma (http://projects.camlcity.org/projects/ocamlnet.html).

Development environment Since 2011, many new tools and libraries have been contributed to the OCaml development environment: OCaml Package Manager (OPAM), developed by OCamlPro, is now an easy way to install OCaml and many of its tools and libraries Optimizing compilers for OCaml: js_of_ocaml, developed by the Ocsigen team, is an optimizing compiler from OCaml to JavaScript, to create webapps in OCaml. ocamlcc is a compiler from OCaml to C, to complement the native code compiler for unsupported platforms. OCamlJava, developed by INRIA, is a compiler from OCaml to the Java virtual machine (JVM). OCaPic, developed by Lip6, is a compiler from OCaml to PIC microcontroller. Web sites: OCaml.org (https://ocaml.org/) is a website managed by the OCaml community. Try-OCaml (https://try.ocamlpro.com/), developed by OCamlPro, is a website containing a complete OCaml REPL in a webpage. Development tools TypeRex is a set of open-source tools and libraries for OCaml, developed and maintained by OCamlPro. Merlin is an auto-completion tool for editing OCaml code in Emacs and Vim.

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 into a bytecode executable: $ ocamlc hello.ml -o hello

or compiled into an optimized native-code executable: $ ocamlopt hello.ml -o hello

and executed: $ ./hello Hello World! $

Summing a list of integers Lists are one of the fundamental datatypes in OCaml. The following code example defines a recursive function sum that accepts one argument xs. (Note the keyword rec). The function recursively iterates over a given list and provides a sum of integer elements. The match statement has similarities to C's switch element, though it is far more general. let rec sum xs = match xs with | [] -> 0 (* yield 0 if xs has the form [] *) | x :: xs' -> x + sum xs';; (* recursive call if xs has the form x::xs' for suitable x and xs' *)

# sum [1;2;3;4;5];; - : int = 15

Another way is to use standard fold function that works with lists. let sum xs = List.fold_left (fun acc each_xs -> acc + each_xs) 0 xs;;

# sum [1;2;3;4;5];; - : int = 15

Since the anonymous function is simply the application of the + operator, this can be shortened to: let sum xs = List.fold_left (+) 0 xs

Furthermore, one can omit the list argument by making use of a partial application: let sum = List.fold_left (+) 0

Quicksort OCaml lends itself to concisely expressing recursive algorithms. The following code example implements an algorithm similar to quicksort that sorts a list in increasing order. let rec qsort = function | [] -> [] | pivot :: rest -> let is_less x = x < pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort 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 365/365 (or 100%), for 2 it is 364/365, for 3 it is 364/365 × 363/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\n" (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 that prepends the string "S" to its input and the constant string "0". let zero f x = x let succ n f x = f (n f x) let one = succ zero let 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 _ = to_string (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 (now superseded by the ZArith module) provides arbitrary-precision arithmetic and can be loaded into a running top-level using: # #use "topfind";; # #require "num";; # 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

or, more simply, using the ocamlfind build command $ ocamlfind opt simple.ml -package lablgl.glut -linkpkg -o simple

and run: $ ./simple

Far more sophisticated, high-performance 2D and 3D graphical programs can be developed in OCaml. Thanks to the use of OpenGL and OCaml, the resulting programs can be cross-platform, compiling without any changes on many major platforms.

Fibonacci sequence The following code calculates the Fibonacci sequence of a number n inputted. It uses tail recursion and pattern matching. let fib n = let rec fib_aux m a b = match m with | 0 -> a | _ -> fib_aux (m - 1) b (a + b) in fib_aux n 0 1

Higher-order functions Functions may take functions as input and return functions as result. For example, applying twice to a function f yields a function that applies f two times to its argument. let twice (f : 'a -> 'a) = fun (x : 'a) -> f (f x);; let inc (x : int) : int = x + 1;; let add2 = twice inc;; let inc_str (x : string) : string = x ^ " " ^ x;; let add_str = twice(inc_str);;

# add2 98;; - : int = 100 # add_str "Test";; - : string = "Test Test Test Test"

The function twice uses a type variable 'a to indicate that it can be applied to any function f mapping from a type 'a to itself, rather than only to int->int functions. In particular, twice can even be applied to itself. # let fourtimes f = (twice twice) f;; val fourtimes : ('a -> 'a) -> 'a -> 'a = # let add4 = fourtimes inc;; val add4 : int -> int = # add4 98;; - : int = 102

Derived languages MetaOCaml MetaOCaml [5] is a multi-stage programming extension of OCaml enabling incremental compiling of new machine code during runtime. Under some circumstances, significant speedups are possible using multistage 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 some power function x -> x^n is needed often, but the value of n is known only at runtime, a two-stage power function can be used in MetaOCaml: let rec power n x = if n = 0 then .. else if even n then sqr (power (n/2) x) else ..

As soon as n is known at runtime, a specialized and very fast power function can be created: . .~(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 AtomCaml provides a synchronization primitive for atomic (transactional) execution of code. Emily is a subset of OCaml that uses a design rule verifier to enforce object-capability model security principles. F# is a .NET Framework language based on OCaml. Fresh OCaml facilitates manipulating names and binders. GCaml adds extensional polymorphism to OCaml, thus allowing overloading and type-safe marshalling. JoCaml integrates constructions for developing concurrent and distributed programs. OCamlDuce extends OCaml with features such as XML expressions and regular-expression types. OCamlP3l is a parallel programming system based on OCaml and the P3L language.

Software written in OCaml MirageOS, a unikernel programming framework written in pure OCaml. Hack, a programming language extending PHP with static typing, created by Facebook in 2014. The compiler is written in OCaml. Flow, a static analyzer for JavaScript created at Facebook that infers and verifies static types for JavaScript programs. [6] Infer, a static analyzer for Java, C, and Objective-C created at Facebook, which is used to detect bugs in iOS and Android apps. [7] 0Install, a multi-platform package manager. Xen Cloud Platform (XCP), an open source toolstack for the Xen Virtual Machine Hypervisor. FFTW, a software library for computing discrete Fourier transforms. Several C routines have been generated by an OCaml program named genfft. Unison, a file synchronization program to synchronize files between two directories. Mldonkey, a peer to peer client based on the EDonkey network. GeneWeb, multi-platform genealogy software, free open source. Haxe compiler, a compiler for the language Haxe, free open source. Frama-C, a framework to analyze C programs. Coq, a formal proof management system. HOL Light, a formal proof assistant. Ocsigen, web development framework. Opa, a programming language for web development, free open source. WebAssembly, an experimental, low-level scripting language for in-browser client-side scripting. Its WIP interpreter and parser in the specification repository on Github[8] is written mostly in OCaml. Web version of Facebook Messenger[9]

Commercial users Several dozen companies use OCaml to some degree.[10] Notable examples include: Jane Street Capital, a proprietary trading firm, which adopted OCaml as its preferred language in its early days. [11] Citrix Systems, which uses OCaml in XenServer, a component of one of its products. Facebook, which developed Hack, Flow, Infer, and Pfff. Bloomberg L.P., which created BuckleScript (https://bucklescript.github.io/), an OCaml compiler backend targeting Javascript. [12]

See 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 ReasonML, a new interface to OCaml initiated by Facebook [13]

References 1. "A History of OCaml" (http://ocaml.org/learn/history.html). Retrieved 24 December 2016. 2. Linux Weekly News (https://lwn.net/Articles/19378/). 3. "ocaml/asmcomp at trunk · ocaml/ocaml · GitHub" (https://github.com/ocaml/ocaml/tree/trunk/asmcomp). GitHub. Retrieved 2 May 2015. 4. "Archives of the Caml mailing list > Message from Xavier Leroy" (http://mirror.ocamlcore.org/caml.inria.fr/pub/ml-archives/caml-list/2002/11/64c14acb90cb14bedb2cacb73338fb15.en.html). Retrieved 2 May 2015. 5. BER MetaOCaml (http://okmij.org/ftp/ML/MetaOCaml.html) 6. Flow static analyzer (http://flowtype.org) 7. Infer static analyzer (http://fbinfer.com) 8. WebAssembly specification repository, Github (https://github.com/WebAssembly/spec) 9. "Messenger.com Now 50% Converted to Reason · Reason" (https://reasonml.github.io/blog/2017/09/08/messenger-50-reason.html). reasonml.github.io. Retrieved 2018-02-27. 10. "Companies using OCaml" (http://ocaml.org/learn/companies.html). OCaml.org. Retrieved 17 August 2014. 11. Yaron Minsky (1 November 2011). "OCaml for the Masses" (http://cacm.acm.org/magazines/2011/11/138203-ocaml-for-the-masses/fulltext). Retrieved 2 May 2015. 12. "BuckleScript: The 1.0 release has arrived! | Tech at Bloomberg" (https://www.techatbloomberg.com/blog/bucklescript-1-0-release-arrived/). Tech at Bloomberg. 8 September 2016. Retrieved 21 May 2017. 13. ReasonML (https://reasonml.github.io/)

External links Official website (http://ocaml.org) OCaml Package Manager (https://opam.ocaml.org/) Retrieved from "https://en.wikipedia.org/w/index.php?title=OCaml&oldid=828899599"

This page was last edited on 5 March 2018, at 12:37. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.

Smile Life

When life gives you a hundred reasons to cry, show life that you have a thousand reasons to smile

Get in touch

© Copyright 2015 - 2024 PDFFOX.COM - All rights reserved.