Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Niidae Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
OCaml
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Programming language}} {{Distinguish|occam (programming language)}} {{Use dmy dates|date=November 2022}} {{Infobox programming language | name = OCaml | logo = OCaml Logo.svg | logo caption = | screenshot = | screenshot caption = | paradigms = [[Programming paradigm#Multi-paradigm|Multi-paradigm]]: [[Functional programming|functional]], [[Imperative programming|imperative]], [[Modular programming|modular]],<ref>{{cite web|title=Modules|url=https://ocaml.org/learn/tutorials/modules.html|access-date=22 February 2020}}</ref> [[Object-oriented programming|object-oriented]] | family = [[ML (programming language)|ML]]: [[Caml]] | scope = | released = {{Start date and age|1996}}<ref>{{cite web |url=https://sympa.inria.fr/sympa/arc/caml-list/1996-05/msg00003.html |title=Objective Caml 1.00 |last=Leroy |first=Xavier |author-link=Xavier Leroy |year=1996 |publisher=caml-list mailing list}}</ref> | designers = [[Xavier Leroy]], Jérôme Vouillon, [[Damien Doligez]], Didier Rémy, Ascánder Suárez | developer = [[French Institute for Research in Computer Science and Automation|Inria]] | latest release version = {{wikidata|property|edit|reference|P548=Q2804309|P348}} | latest release date = {{start date and age|{{wikidata|qualifier|P548=Q2804309|P348|P577}}}} | latest preview version = | latest preview date = <!-- {{Start date and age|yyyy|mm|dd}} --> | typing = [[Type inference|Inferred]], [[Static typing|static]], [[Strong and weak typing|strong]], [[Structural typing|structural]] | programming language = OCaml, [[C (programming language)|C]] | platform = [[IA-32]], [[x86-64]], [[Power ISA|Power]], [[SPARC]], [[ARM architecture|ARM 32-64]], [[RISC-V]] | operating system = [[Cross-platform software|Cross-platform]]: [[Linux]], [[Unix]], [[macOS]], [[Microsoft Windows|Windows]] | license = [[GNU Lesser General Public License|LGPLv2.1]] | file ext = .ml, .mli | implementations = | influenced by = [[C (programming language)|C]], [[Caml]], [[Modula-3]], [[Pascal (programming language)|Pascal]], [[Standard ML]] | influenced = [[ATS (programming language)|ATS]], [[Rocq (software)|Rocq]] (previously known as ''Coq''), [[Elm (programming language)|Elm]], [[F Sharp (programming language)|F#]], [[F* (programming language)|F*]], [[Haxe]], [[Opa (programming language)|Opa]], [[Rust (programming language)|Rust]],<ref>{{Cite web |url=https://doc.rust-lang.org/reference/influences.html |title=Influences - The Rust Reference |website=The Rust Reference |access-date=2023-12-31}}</ref> [[Scala (programming language)|Scala]], [[Gleam (programming language)|Gleam]] | wikibooks = Objective Caml }} '''OCaml''' ({{IPAc-en|oʊ|ˈ|k|æ|m|əl}} {{respell|oh|KAM|əl}}, formerly '''Objective Caml''') is a [[General-purpose programming language|general-purpose]], [[High-level programming language|high-level]], [[Comparison of multi-paradigm programming languages|multi-paradigm]] [[programming language]] which extends the [[Caml]] dialect of [[ML (programming language)|ML]] with [[Object-oriented programming|object-oriented]] features. OCaml was created in 1996 by [[Xavier Leroy]], Jérôme Vouillon,<ref>{{Cite web |title=Jérôme Vouillon |url=https://www.irif.fr/~vouillon/ |access-date=2024-06-14 |website=www.irif.fr}}</ref> [[Damien Doligez]], Didier Rémy,<ref>{{Cite web |title=Didier Remy |url=https://pauillac.inria.fr/~remy/ |access-date=2024-06-14 |website=pauillac.inria.fr}}</ref> Ascánder Suárez, and others. The OCaml [[toolchain]] includes an interactive top-level [[Interpreter (computing)|interpreter]], a [[bytecode]] [[compiler]], an optimizing [[native code]] compiler, a reversible [[debugger]], and a [[package manager]] ([https://opam.ocaml.org/packages/ OPAM]) together with a composable build system for OCaml ([https://dune.build/ Dune]). OCaml was initially developed in the context of [[automated theorem proving]], and is used in [[static program analysis|static analysis]] and [[formal methods]] software. Beyond these areas, it has found use in [[systems programming]], [[web development]], and specific financial utilities, among other application domains. The acronym ''CAML'' originally stood for ''Categorical Abstract Machine Language'', but OCaml omits this [[abstract machine]].<ref>{{cite web|url= http://ocaml.org/learn/history.html|title= A History of OCaml|access-date= 24 December 2016}}</ref> OCaml is a [[free and open-source software]] project managed and principally maintained by the [[French Institute for Research in Computer Science and Automation]] (Inria). In the early 2000s, elements from OCaml were adopted by many languages, notably [[F Sharp (programming language)|F#]] and [[Scala (programming language)|Scala]]. ==Philosophy== [[ML (programming language)|ML]]-derived languages are best known for their static [[type system]]s and [[type inference|type-inferring]] compilers. OCaml unifies [[functional programming|functional]], [[imperative programming|imperative]], and [[object-oriented programming]] under an ML-like type system. Thus, programmers need not be highly familiar with the pure functional language [[Programming paradigm|paradigm]] to use OCaml. By requiring the programmer to work within the constraints of its static [[type system]], OCaml eliminates many of the type-related [[Run-time type information|runtime]] problems associated with [[Type system|dynamically typed]] languages. Also, OCaml's type-inferring compiler greatly reduces the need for the manual type annotations that are required in most statically typed languages. For example, the [[data type]]s of variables and the [[Type signature|signature]]s of functions usually need not be declared explicitly, as they do in languages like [[Java (programming language)|Java]] and [[C Sharp (programming language)|C#]], because they can be [[Type inference|inferred]] from the operators and other functions that are applied to the variables and other values in the code. Effective use of OCaml's type system can require some sophistication on the part of a programmer, but this discipline is rewarded with reliable, high-performance software. 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 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 (computer science)|boxing]] and [[Closure (computer science)|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",<ref name = "LWN">[https://lwn.net/Articles/19378/ Linux Weekly News].</ref> although 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 can exploit the [[immutability]] of sets to reuse parts of input sets in the output (see [[persistent data structure]]). == History == [[File:Award for OCaml at POPL 2024.jpg|thumb|The OCaml development team receiving an award at [[Symposium on Principles of Programming Languages]] (POPL) 2024]] === Development of ML (Meta Language) === Between the 1970s and 1980s, [[Robin Milner]], a British computer scientist and [[Turing Award]] winner, worked at the [[University of Edinburgh]]'s [[Laboratory for Foundations of Computer Science]].<ref>{{Cite web |title=A J Milner - A.M. Turing Award Laureate |url=https://amturing.acm.org/award_winners/milner_1569367.cfm |access-date=2022-10-06 |website=amturing.acm.org}}</ref><ref name=":0">{{Cite web |last=Clarkson |first=Michael |display-authors=etal |title=1.2. OCaml: Functional Programming in OCaml |url=https://courses.cs.cornell.edu/cs3110/2021sp/textbook/intro/ocaml.html |website=courses.cs.cornell.edu |access-date=2022-10-06}}</ref> Milner and others were working on [[Automated theorem proving|theorem provers]], which were historically developed in languages such as [[Lisp (programming language)|Lisp]]. Milner repeatedly ran into the issue that the theorem provers would attempt to claim a [[Proof (truth)|proof]] was valid by putting non-proofs together.<ref name=":0"/> As a result, he went on to develop the [[ML (programming language)|meta language]] for his [[Logic for Computable Functions]], a language that would only allow the writer to construct valid proofs with its polymorphic type system.<ref name=":1">{{Cite web |title=Prologue - Real World OCaml |url=https://dev.realworldocaml.org/prologue.html#a-brief-history |access-date=2022-10-06 |website=dev.realworldocaml.org}}</ref> ML was turned into a [[compiler]] to simplify using LCF on different machines, and, by the 1980s, was turned into a complete system of its own.<ref name=":1"/> ML would eventually serve as a basis for the creation of OCaml. In the early 1980s, there were some developments that prompted [[French Institute for Research in Computer Science and Automation|INRIA]]'s Formel team to become interested in the ML language. [[Luca Cardelli]], a research professor at [[University of Oxford]], used his ''functional abstract machine'' to develop a faster implementation of ML, and Robin Milner proposed a new definition of ML to avoid divergence between various implementations. Simultaneously, Pierre-Louis Curien, a senior researcher at [[Paris Diderot University]], developed a calculus of categorical combinators and linked it to [[lambda calculus]], which led to the definition of the ''[[categorical abstract machine]]'' (CAM). Guy Cousineau, a researcher at Paris Diderot University, recognized that this could be applied as a compiling method for ML.<ref name=":2">{{Cite web |title=A History of OCaml – OCaml |url=https://v2.ocaml.org/learn/history.html |access-date=2022-10-07 |website=v2.ocaml.org}}</ref> === First implementation === [[Caml]] was initially designed and developed by INRIA's Formel team headed by [[Gérard Huet]]. The first implementation of Caml was created in 1987 and was further developed until 1992. Though it was spearheaded by Ascánder Suárez, [[Pierre Weis (computer scientist)|Pierre Weis]] and [[Michel Mauny (computer science)|Michel Mauny]] carried on with development after he left in 1988.<ref name=":2"/> Guy Cousineau is quoted recalling that his experience with programming language implementation was initially very limited, and that there were multiple inadequacies for which he is responsible. Despite this, he believes that "Ascander, Pierre and Michel did quite a nice piece of work.”<ref name=":2"/> === Caml Light === Between 1990 and 1991, [[Xavier Leroy]] designed a new implementation of Caml based on a [[bytecode interpreter]] written in [[C (programming language)|C]]. In addition to this, [[Damien Doligez]] wrote a memory management system, also known as a sequential [[Garbage collection (computer science)|garbage collector]], for this implementation.<ref name=":1"/> This new implementation, known as [[Caml Light]], replaced the old Caml implementation and ran on small desktop machines.<ref name=":2"/> In the following years, libraries such as Michel Mauny's syntax manipulation tools appeared and helped promote the use of Caml in educational and research teams.<ref name=":1"/> === Caml Special Light === In 1995, Xavier Leroy released Caml Special Light, which was an improved version of Caml.<ref name=":2"/> An optimizing [[Native code|native-code]] compiler was added to the bytecode compiler, which greatly increased performance to comparable levels with mainstream languages such as [[C++]].<ref name=":1"/><ref name=":2"/> Also, Leroy designed a high-level module system inspired by the module system of Standard ML which provided powerful facilities for abstraction and parameterization and made larger-scale programs easier to build.<ref name=":1"/> === Objective Caml === Didier Rémy and Jérôme Vouillon designed an expressive [[type system]] for objects and classes, which was integrated within Caml Special Light. This led to the emergence of the Objective Caml language, first released in 1996 and subsequently renamed to OCaml in 2011. This object system notably supported many prevalent object-oriented idioms in a statically type-safe way, while those same idioms caused unsoundness or required runtime checks in languages such as C++ or [[Java (programming language)|Java]]. In 2000, Jacques Garrigue extended Objective Caml with multiple new features such as polymorphic methods, variants, and labeled and optional arguments.<ref name=":1"/><ref name=":2"/> === Ongoing development === Language improvements have been incrementally added for the last two decades to support the growing commercial and academic codebases in OCaml.<ref name=":1"/> The OCaml 4.0 release in 2012 added Generalized Algebraic Data Types (GADTs) and first-class modules to increase the flexibility of the language.<ref name=":1"/> The OCaml 5.0.0 release in 2022<ref>{{Cite web |title=Release of OCaml 5.0.0 OCaml Package |url=https://ocaml.org/news/ocaml-5.0 |access-date=2022-12-16 |website=OCaml |language=en}}</ref> is a complete rewrite of the language runtime, removing the [[Global interpreter lock|global GC lock]] and adding [[Effect system|effect handlers]] via [[delimited continuations]]. These changes enable support for [[Parallel programming model#Shared memory|shared-memory parallelism]] and [[color-blind concurrency]], respectively. OCaml's development continued within the Cristal team at INRIA until 2005, when it was succeeded by the Gallium team.<ref>{{Cite web |title=Projet Cristal |url=http://cristal.inria.fr/ |access-date=2022-10-07 |website=cristal.inria.fr}}</ref> Subsequently, Gallium was succeeded by the Cambium team in 2019.<ref>{{Cite web |title=Gallium team - Home |url=http://gallium.inria.fr/ |access-date=2022-10-07 |website=gallium.inria.fr}}</ref><ref>{{Cite web |title=Home |url=http://cambium.inria.fr/ |access-date=2022-10-07 |website=cambium.inria.fr |language=en}}</ref> As of 2023, there are 23 core developers of the compiler distribution from a variety of organizations<ref>{{cite web|url=https://ocaml.org/governance/compiler|title=OCaml compiler governance and membership|year=2023}}</ref> and 41 developers for the broader OCaml tooling and packaging ecosystem.<ref>{{cite web|url=https://ocaml.org/governance|title=OCaml governance and projects|year=2023}}</ref> In 2023, the OCaml compiler was recognised with [[SIGPLAN|ACM SIGPLAN's Programming Languages Software Award]]. ==Features== OCaml features a [[Semantic analysis (computer science)|static]] [[type system]], [[type inference]], [[parametric polymorphism]], [[tail recursion]], [[pattern matching]], first class lexical [[Closure (computer science)|closures]], [[Function object#Other meanings|functors (parametric modules)]], [[exception handling]], [[effect system|effect handling]], and incremental generational [[garbage collection (computer science)|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 (object-oriented programming)|inheritance]] (an unusual feature in statically typed languages). A [[foreign function interface]] for [[Linker (computing)|linking]] to [[C (programming language)|C]] primitives is provided, including language support for efficient numerical [[Array data structure|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. Although OCaml does not have a macro system as an indivisible part of the language ([[metaprogramming]]), i.e. built-in support for [[Preprocessor|preprocessing]], the [https://ocaml.org/docs/metaprogramming OCaml platform does officially support a library for writing such preprocessors]. These can be of two types: one that works at the source code level (as in C), and one that works on the [[Abstract syntax tree|Abstract Syntax Tree]] level. The latter, which is called PPX, acronym for Pre-Processor eXtension, is the recommended one. The OCaml distribution contains: * [[Lexical analysis]] and [[parsing]] tools called ''ocamllex'' and ''ocamlyacc'' * [[Debugger]] that supports stepping backwards to investigate errors * [[Documentation generator]] * [[Profiler (computer science)|Profiler]] – to measure performance * Many general-purpose [[Library (computing)|libraries]] The native code compiler is available for many platforms, including [[Unix]], [[Microsoft Windows]], and [[Apple Inc.|Apple]] [[macOS]]. Portability is achieved through native [[code generation (compiler)|code generation]] support for major architectures: * [[X86-64]] (AMD64), [[RISC-V]], and [[ARM64]] (in OCaml 5.0.0 and higher)<ref>{{cite web|url=https://github.com/ocaml/ocaml/tree/trunk/asmcomp|title=ocaml/asmcomp at trunk · ocaml/ocaml · GitHub|work=GitHub|access-date=2 May 2015}}</ref> * [[IBM Z]] (before OCaml 5.0.0, and back in OCaml 5.1.0) * [[Power ISA|Power]] (before OCaml 5.0.0, and due to reappear in OCaml 5.2.0) * [[IA-32]] and [[ARM architecture|ARM]] (before OCaml 5.0.0) * [[SPARC]] (before OCaml 4.06.0) * [[DEC Alpha]], [[HPPA]], [[IA64]] and [[MIPS architecture|MIPS]] (before OCaml 4.00.0) The [[bytecode]] [[compiler]] supports operation on any 32- or 64-bit architecture when native code generation is not available, requiring only a C compiler. OCaml bytecode and native code programs can be written in a [[Thread (computer science)|multithreaded]] style, with [[Preemption (computing)|preemptive]] context switching. OCaml [[Thread (computing)|threads]] in the same domain<ref>A domain is a unit of parallelism in OCaml, a domain usually corresponds to a CPU core</ref> execute by [[Time-sharing|time sharing]] only. However, an OCaml program can contain several domains. ==Code examples== {{one source|date=January 2024}} Snippets of OCaml code are most easily studied by entering them into the ''top-level [[read–eval–print loop|REPL]]''. This is an interactive OCaml session that prints the inferred types of resulting or defined expressions.<ref>{{Cite web|title=OCaml - The toplevel system or REPL (ocaml)|url=https://ocaml.org/manual/toplevel.html|access-date=2021-05-17|website=ocaml.org}}</ref> The OCaml top-level is started by simply executing the OCaml program: <syntaxhighlight lang="console"> $ ocaml Objective Caml version 3.09.0 # </syntaxhighlight> Code can then be entered at the "#" prompt. For example, to calculate 1+2*3: <syntaxhighlight lang="console"> # 1 + 2 * 3;; - : int = 7 </syntaxhighlight> OCaml infers the type of the expression to be "int" (a [[Word (computer architecture)|machine-precision]] [[Integer (computer science)|integer]]) and gives the result "7". ===Hello World=== The following program "hello.ml": <syntaxhighlight lang="OCaml"> print_endline "Hello World!" </syntaxhighlight> 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: <syntaxhighlight lang="console"> $ ./hello Hello World! $ </syntaxhighlight> The first argument to ocamlc, "hello.ml", specifies the source file to compile and the "-o hello" flag specifies the output file.<ref>{{Cite web|url=https://caml.inria.fr/pub/docs/manual-ocaml/comp.html|title = OCaml - Batch compilation (Ocamlc)}}</ref> === Option === The <code>option</code> type constructor in OCaml, similar to the <code>Maybe</code> type in [[Haskell]], augments a given data type to either return <code>Some</code> value of the given data type, or to return <code>None</code>.<ref>{{Cite web |title=3.7. Options — OCaml Programming: Correct + Efficient + Beautiful |url=https://cs3110.github.io/textbook/chapters/data/options.html |access-date=2022-10-07 |website=cs3110.github.io}}</ref> This is used to express that a value might or might not be present.<syntaxhighlight lang="ocaml"> # Some 42;; - : int option = Some 42 # None;; - : 'a option = None </syntaxhighlight>This is an example of a function that either extracts an int from an option, if there is one inside, and converts it into a [[String (computer science)|string]], or if not, returns an empty string:<syntaxhighlight lang="ocaml"> let extract o = match o with | Some i -> string_of_int i | None -> "";; </syntaxhighlight><syntaxhighlight lang="ocaml"> # extract (Some 42);; - : string = "42" # extract None;; - : string = "" </syntaxhighlight> ===Summing a list of integers=== Lists are one of the fundamental datatypes in OCaml. The following code example defines a [[Recursion (computer science)|recursive]] function ''sum'' that accepts one argument, ''integers'', which is supposed to be a list of integers. Note the keyword <code>rec</code> which denotes that the function is recursive. The function recursively iterates over the given list of integers and provides a sum of the elements. The ''match'' statement has similarities to [[C (programming language)|C]]'s [[Switch statement|switch]] element, though it is far more general. <syntaxhighlight lang="ocaml"> let rec sum integers = (* Keyword rec means 'recursive'. *) match integers with | [] -> 0 (* Yield 0 if integers is the empty list []. *) | first :: rest -> first + sum rest;; (* Recursive call if integers is a non- empty list; first is the first element of the list, and rest is a list of the rest of the elements, possibly []. *) </syntaxhighlight> <syntaxhighlight lang="OCaml"> # sum [1;2;3;4;5];; - : int = 15 </syntaxhighlight> Another way is to use standard [[fold function]] that works with lists. <syntaxhighlight lang="ocaml"> let sum integers = List.fold_left (fun accumulator x -> accumulator + x) 0 integers;; </syntaxhighlight> <syntaxhighlight lang="OCaml"> # sum [1;2;3;4;5];; - : int = 15 </syntaxhighlight> Since the [[anonymous function]] is simply the application of the + operator, this can be shortened to: <syntaxhighlight lang="ocaml"> let sum integers = List.fold_left (+) 0 integers </syntaxhighlight> Furthermore, one can omit the list argument by making use of a [[partial application]]: <syntaxhighlight lang="OCaml"> let sum = List.fold_left (+) 0 </syntaxhighlight> ===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. <syntaxhighlight lang="OCaml"> 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 </syntaxhighlight> Or using partial application of the >= operator. <syntaxhighlight lang="OCaml"> let rec qsort = function | [] -> [] | pivot :: rest -> let is_less = (>=) pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort right </syntaxhighlight> ===Birthday problem=== 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 [[birthday problem]], 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). <syntaxhighlight lang="OCaml"> 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 </syntaxhighlight> ===Church numerals=== The following code defines a [[Church encoding]] of [[natural number]]s, with successor (succ) and addition (add). A Church numeral {{OCaml|n}} is a [[higher-order function]] that accepts a function {{OCaml|f}} and a value {{OCaml|x}} and applies {{OCaml|f}} to {{OCaml|x}} exactly {{OCaml|n}} times. To convert a Church numeral from a functional value to a string, we pass it a function that prepends the string {{OCaml|"S"}} to its input and the constant string {{OCaml|"0"}}. <syntaxhighlight lang="OCaml"> 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) </syntaxhighlight> ===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: <syntaxhighlight lang=ocaml> # #use "topfind";; # #require "num";; # open Num;; </syntaxhighlight> The factorial function may then be written using the arbitrary-precision numeric operators {{mono|{{=}}/}}, {{mono|*/}} and {{mono|-/}} : <syntaxhighlight lang="OCaml"> # let rec fact n = if n =/ Int 0 then Int 1 else n */ fact(n -/ Int 1);; val fact : Num.num -> Num.num = <fun> </syntaxhighlight> This function can compute much larger factorials, such as 120!: <syntaxhighlight lang="OCaml"> # string_of_num (fact (Int 120));; - : string = "6689502913449127057588118054090372586752746333138029810295671352301633 55724496298936687416527198498130815763789321409055253440858940812185989 8481114389650005964960521256960000000000000000000000000000" </syntaxhighlight> ===Triangle (graphics)=== The following program renders a rotating triangle in 2D using [[OpenGL]]: <syntaxhighlight lang="OCaml"> 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 () </syntaxhighlight> 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 number|Fibonacci sequence]] of a number ''n'' inputted. It uses [[tail recursion]] and pattern matching. <syntaxhighlight lang = OCaml> 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 </syntaxhighlight> ===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. <syntaxhighlight lang = OCaml> 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);; </syntaxhighlight> <syntaxhighlight lang = OCaml highlight="1,3"> # add2 98;; - : int = 100 # add_str "Test";; - : string = "Test Test Test Test" </syntaxhighlight> 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. <syntaxhighlight lang = OCaml highlight="1,3,5"> # let fourtimes f = (twice twice) f;; val fourtimes : ('a -> 'a) -> 'a -> 'a = <fun> # let add4 = fourtimes inc;; val add4 : int -> int = <fun> # add4 98;; - : int = 102 </syntaxhighlight> ==Derived languages== ===MetaOCaml=== MetaOCaml<ref name = "Meta">{{cite web|url=http://okmij.org/ftp/ML/MetaOCaml.html|title=BER MetaOCaml|last=oleg-at-okmij.org|website=okmij.org}}</ref> is a [[multi-stage programming]] extension of OCaml enabling incremental compiling of new [[machine code]] during runtime. Under some circumstances, significant [[Speedup|speedups]] are possible using [[Multi-stage programming|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 [[Exponentiation|power function]] {{OCaml|x -> x^n}} is needed often, but the value of {{OCaml|n}} is known only at [[Runtime system|runtime]], a two-stage power function can be used in MetaOCaml: <syntaxhighlight lang="OCaml"> 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)>. </syntaxhighlight> As soon as {{OCaml|n}} is known at runtime, a specialized and very fast power function can be created: <syntaxhighlight lang="OCaml"> .<fun x -> .~(power 5 .<x>.)>. </syntaxhighlight> The result is: <syntaxhighlight lang="OCaml"> fun x_1 -> (x_1 * let y_3 = let y_2 = (x_1 * 1) in (y_2 * y_2) in (y_3 * y_3)) </syntaxhighlight> The new function is automatically compiled. ===Other derived languages=== * [[F Sharp (programming language)|F#]] is a [[.NET]] framework language based on OCaml. * [[JoCaml]] integrates constructions for developing [[Concurrent computing|concurrent]] and [[Distributed computing|distributed programs]]. * [[Reason (programming language)|Reason]] is an alternative OCaml [[syntax (programming languages)|syntax]] and [[toolchain]] for OCaml created at [[Facebook]], which can compile to both native code and [[JavaScript]]. ==Software written in OCaml== * Ahrefs, an [[Search engine optimization|SEO]] software product * [[Alt-Ergo]], a [[Satisfiability modulo theories|SMT solver]]. * [[Astrée (static analysis)|Astrée]], a [[Static program analysis|static analyzer]] * [[Be Sport]], a [[Social networking service|social network]] * [[Coccinelle (software)|Coccinelle]], a utility for [[program transformation|transforming]] the [[source code]] of [[C (programming language)|C]] programs. * [[Rocq (software)|Rocq]] (previously known as ''Coq''), a [[formal proof]] [[management system]]. * Easycrypt, a [[Programming tool|toolset]] for writing [[Computer-assisted proof|computer-aided proofs]].<ref>{{Citation |title=EasyCrypt/easycrypt |date=2024-07-05 |url=https://github.com/EasyCrypt/easycrypt |access-date=2024-07-05 |publisher=EasyCrypt}}</ref> * [[F*_(programming_language)|F*]], a high-level, multi-paradigm, functional and object-oriented programming language intended for [[Formal verification|program verification]]. * [[FFTW]], a [[library (computing)|library]] for computing [[discrete Fourier transform]]s. Several C routines have been generated by an OCaml program named {{OCaml|genfft}}. * The web version of [[Facebook Messenger]].<ref>{{cite web|title=Messenger.com Now 50% Converted to Reason · Reason|url=https://reasonml.github.io/blog/2017/09/08/messenger-50-reason.html|website=reasonml.github.io|access-date=2018-02-27}}</ref> * Flow, a [[static program analysis|static analyzer]] created at [[Facebook]] that infers and checks [[Type system#Static type checking|static types]] for [[JavaScript]].<ref>{{cite web|url=https://flow.org/en/|title=Flow: A Static Type Checker for JavaScript|website=Flow|access-date=10 February 2019|archive-date=8 April 2022|archive-url=https://web.archive.org/web/20220408204727/https://flow.org/en/|url-status=dead}}</ref> * [[Ocsigen]], a [[Client–server model|client server]] Web and mobile development [[Application framework|framework]] * [[Owl Scientific Computing]], a dedicated system for scientific and engineering computing. * [[Frama-C]], a framework for analyzing C programs. * [[GeneWeb]], free and open-source multi-platform genealogy software. * The [[Hack (programming language)|Hack]] programming language compiler, created at Facebook, extending [[PHP]] with static types. * The [[Haxe]] programming language compiler. * [[HOL Light]], a formal proof assistant. * Infer, a static analyzer created at Facebook for [[Java (programming language)|Java]], C, [[C++]], and [[Objective-C]], used to detect bugs in [[iOS]] and [[Android (operating system)|Android]] apps.<ref>{{cite web|url=https://fbinfer.com/|title=Infer static analyzer|website=Infer}}</ref> * [[Liquidsoap]], a [[scripting language]] for generating multimedia streams. * [[MirageOS]], a [[unikernel]] programming framework written in pure OCaml. * [[MLdonkey]], a [[peer-to-peer file sharing]] application based on the [[EDonkey network]]. * [[Opa (programming language)|Opa]], a free and open-source programming language for web development. * [[Reason_(programming_language) | Reason / ReScript]], a general-purpose, high-level, multi-paradigm, functional and object-oriented programming language. * The [[Rust (programming language)|Rust]] compiler was [[Bootstrapping_(compilers)|initially implemented]] in OCaml before becoming [[Self-hosting (compilers)|self-hosting]]. * [[Tezos]], a self-amending smart contract platform using XTZ as a native currency. * [[Unison (software)|Unison]], a [[file synchronization]] program to synchronize files between two directories. * The reference interpreter for [[WebAssembly]], a low-level [[bytecode]] intended for execution inside [[web browser]]s.<ref>{{cite web|url=https://github.com/WebAssembly/spec|title=WebAssembly/spec: WebAssembly specification, reference interpreter, and test suite.|date=5 December 2019|publisher=[[World Wide Web Consortium]]|access-date=2021-05-14|via=GitHub}}</ref> * [[Xen Cloud Platform]] (XCP), a [[turnkey]] [[virtualization]] solution for the [[Xen]] [[hypervisor]]. ==Users== At least several dozen companies use OCaml to some degree.<ref name="ocaml.org-companies">{{Cite web|url=https://ocaml.org/learn/companies.html|title=Companies using OCaml|access-date=2021-05-14|publisher=OCaml.org}}</ref> Notable examples include: * [[Bloomberg L.P.]], which created [https://bucklescript.github.io/ BuckleScript], an OCaml compiler backend targeting JavaScript.<ref>{{cite web|url=https://www.techatbloomberg.com/blog/bucklescript-1-0-release-arrived/|title=BuckleScript: The 1.0 release has arrived! {{!}} Tech at Bloomberg|date=8 September 2016|website=Tech at Bloomberg|ref=12|access-date=21 May 2017}}</ref> * [[Citrix Systems]], which uses OCaml in [[Citrix Systems#Networking and cloud|XenServer]] (rebranded as Citrix Hypervisor during 2018).<ref>{{cite conference|url=https://dl.acm.org/doi/10.1145/1863543.1863557|doi=10.1145/1863543.1863557|first1=David|last1=Scott|first2=Richard|last2=Sharp|first3=Thomas|last3=Gazagnaire|first4=Anil|last4=Madhavapeddy|title=Using functional programming within an industrial product group: perspectives and perceptions|publisher=[[Association for Computing Machinery]]|conference=[[International Conference on Functional Programming]]|year=2010}}</ref> * [[Facebook]], which developed Flow,<ref>{{cite web|url=https://github.com/facebook/flow|title=Flow on GitHub|website=[[GitHub]] |year=2023}}</ref> Hack, Infer, Pfff, and [[Reason (programming language)|ReasonML]] in OCaml. * [[Jane Street Capital]], a [[proprietary trading]] firm, which adopted OCaml as its preferred language in its early days<ref>{{cite web|url=http://cacm.acm.org/magazines/2011/11/138203-ocaml-for-the-masses/fulltext|title=OCaml for the Masses|author=Yaron Minsky|date=1 November 2011|access-date=2 May 2015}}</ref> and continues to use it as of 2023.<ref>{{cite web|url=http://cufp.org/2016/yaron-minsky-keynote.html|title= Keynote - Observations of a Functional Programmer|author=Yaron Minsky|publisher=[[Association for Computing Machinery|ACM]] Commercial Uses of Functional Programming|year=2016}}</ref><ref>{{cite podcast|title=Signals & Threads|year=2023|publisher=[[Jane Street Capital]]|url=https://signalsandthreads.com|host=Yaron Minsky}}</ref> * [[Docker (software)|Docker]], which uses OCaml in the desktop editions on [[macOS]] and [[Windows]].<ref>{{cite web|url=https://www.docker.com/blog/docker-unikernels-open-source/|title=Improving Docker with Unikernels: Introducing HyperKit, VPNKit and DataKit|author=[[Anil Madhavapeddy]]|year=2016|publisher=[[Docker, Inc.]]}}</ref><ref>{{cite web|url=https://github.com/moby/vpnkit|title=VPNKit on GitHub|website=[[GitHub]] |year=2023}}</ref> In the context of Academic teaching and research, OCaml has a remarkable presence in computer science teaching programmes, both in universities and colleges. A list of educational resources and these teaching programmes can be found [https://ocaml.org/academic-users/institutions ocaml.org]. ==References== {{Reflist}} ==External links== {{wikibooks|OCaml}} * {{Official website}} * [https://v2.ocaml.org/manual/ OCaml manual] * [https://opam.ocaml.org/ OCaml Package Manager] * [https://dev.realworldocaml.org/ Real World OCaml] {{ML programming}} {{Programming languages}} {{Authority control}} [[Category:High-level programming languages]] [[Category:Cross-platform free software]] [[Category:Extensible syntax programming languages]] [[Category:Free and open source interpreters]] [[Category:Functional languages]] [[Category:Object-oriented programming languages]] [[Category:ML programming language family]] [[Category:OCaml programming language family]] [[Category:OCaml software]] [[Category:Pattern matching programming languages]] [[Category:Programming languages created in 1996]] [[Category:Statically typed programming languages]] [[Category:Software using the GNU Lesser General Public License]] <!-- Hidden categories below --> [[Category:Articles with example OCaml code]]
Summary:
Please note that all contributions to Niidae Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Encyclopedia:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Templates used on this page:
Template:Authority control
(
edit
)
Template:Citation
(
edit
)
Template:Cite conference
(
edit
)
Template:Cite podcast
(
edit
)
Template:Cite web
(
edit
)
Template:Distinguish
(
edit
)
Template:IPAc-en
(
edit
)
Template:Infobox programming language
(
edit
)
Template:ML programming
(
edit
)
Template:Mono
(
edit
)
Template:OCaml
(
edit
)
Template:Official website
(
edit
)
Template:One source
(
edit
)
Template:Programming languages
(
edit
)
Template:Reflist
(
edit
)
Template:Respell
(
edit
)
Template:Short description
(
edit
)
Template:Use dmy dates
(
edit
)
Template:Wikibooks
(
edit
)
Search
Search
Editing
OCaml
Add topic