词条 | OCaml |
释义 |
| name = OCaml | logo = OCaml Logo.svg | logo caption = | screenshot = | screenshot caption = | paradigm = Multi-paradigm: functional, imperative, object-oriented | scope = | released = {{Start date and age|1996}} | designer = Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez | developer = INRIA | latest release version = 4.07.1 | latest release date = {{Start date and age|2018|10|4}}[1] | latest preview version = | latest preview date = | typing = Inferred, static, strong, structural | implementations = | influenced by = Caml, Standard ML, Pascal | influenced = ATS, Coq, Elm, F#, F*, Haxe, Opa, Rust, Scala | programming language = OCaml, C | platform = IA-32, x86-64, Power, SPARC, ARM 32-64 | operating system = Cross-platform: Unix, macOS, Windows | license = LGPL | file ext = .ml, .mli | website = {{URL|https://ocaml.org/}} | wikibooks = Objective Caml }} OCaml ({{IPAc-en|oʊ|ˈ|k|æ|m|əl}} {{respell|oh|KAM|əl}}) (formerly Objective Caml) is the main implementation of the Caml programming language created in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez, and others. It extends Caml with object-oriented features and is a member of the ML family. The OCaml toolchain 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, which makes it useful for many of the same applications as Python and Perl, and has robust modular and object-oriented programming constructs that make it applicable for large-scale software engineering. The acronym CAML originally stood for Categorical Abstract Machine Language, but OCaml omits this abstract machine.[2] 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# and Scala. PhilosophyML-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. Thus, programmers need not be highly familiar with the pure functional language 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 runtime problems associated with 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 of variables and the signature of functions usually need not be declared explicitly, as they do in languages like Java and C#, because they can be 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 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",[3] 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 exploits the immutability of sets to reuse parts of input sets in the output (see persistent data structure). FeaturesOCaml 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:
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.[4] 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.[5] OCaml threads in the same process execute by time sharing only. There are however several libraries for distributed computing such as Functory and ocamlnet/Plasma. Development environmentSince 2011, many new tools and libraries have been contributed to the OCaml development environment:
Code examples{{unreferenced section|date=May 2013}}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: Code can then be entered at the "#" prompt. For example, to calculate 1+2*3: OCaml infers the type of the expression to be "int" (a machine-precision integer) and gives the result "7". Hello WorldThe following program "hello.ml": can be compiled into a bytecode executable: or compiled into an optimized native-code executable: and executed: Summing a list of integersLists 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. Another way is to use standard fold function that works with lists. Since the anonymous function is simply the application of the + operator, this can be shortened to: Furthermore, one can omit the list argument by making use of a partial application: QuicksortOCaml lends itself to concisely expressing recursive algorithms. The following code example implements an algorithm similar to quicksort that sorts a list in increasing order. Birthday problemThe 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). Church numeralsThe following code defines a Church encoding of natural numbers, 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"}}. 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: # {{Unstyled inline syntax|lang=ocaml|monospace=1|#use "topfind";;}} # {{Unstyled inline syntax|lang=ocaml|monospace=1|#require "num";;}} # {{Unstyled inline syntax|lang=ocaml|monospace=1|open Num;;}} The factorial function may then be written using the arbitrary-precision numeric operators {{mono|{{=}}/}}, {{mono|*/}} and {{mono|-/}} : This function can compute much larger factorials, such as 120!: Triangle (graphics)The following program "simple.ml" renders a rotating triangle in 2D using OpenGL: The LablGL bindings to OpenGL are required. The program may then be compiled to bytecode with: or to nativecode with: or, more simply, using the ocamlfind build command and run: 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 sequenceThe following code calculates the Fibonacci sequence of a number n inputted. It uses tail recursion and pattern matching. Higher-order functionsFunctions 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. 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. Derived languagesMetaOCamlMetaOCaml[6] 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 {{OCaml|x -> x^n}} is needed often, but the value of {{OCaml|n}} is known only at runtime, a two-stage power function can be used in MetaOCaml: As soon as {{OCaml|n}} is known at runtime, a specialized and very fast power function can be created: The result is: The new function is automatically compiled. Other derived languages
Software written in OCaml
UsersSeveral dozen companies use OCaml to some degree.[12] Notable examples include:
See also
References1. ^{{cite web|url=https://ocaml.org/releases/|title=Releases – OCaml|website=ocaml.org}} 2. ^{{cite web|url= http://ocaml.org/learn/history.html|title= A History of OCaml|publisher= |access-date= 24 December 2016}} 3. ^[https://lwn.net/Articles/19378/ Linux Weekly News]. 4. ^{{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}} 5. ^{{cite web|url=http://mirror.ocamlcore.org/caml.inria.fr/pub/ml-archives/caml-list/2002/11/64c14acb90cb14bedb2cacb73338fb15.en.html|title=Archives of the Caml mailing list > Message from Xavier Leroy|publisher=|access-date=2 May 2015}} 6. ^{{cite web|url=http://okmij.org/ftp/ML/MetaOCaml.html|title=BER MetaOCaml|first=|last=oleg-at-okmij.org|website=okmij.org}} 7. ^{{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}} 8. ^{{cite web|url=https://flow.org/en/|title=Flow: A Static Type Checker for JavaScript|website=Flow}} 9. ^{{cite web|url=https://fbinfer.com/|title=Infer static analyzer|website=Infer}} 10. ^{{cite web|url=https://github.com/facebook/pyre-check|title=Performant type-checking for python. Contribute to facebook/pyre-check development by creating an account on GitHub|date=9 February 2019|publisher=|via=GitHub}} 11. ^{{cite web|url=https://github.com/WebAssembly/spec|title=WebAssembly specification, reference interpreter, and test suite.: WebAssembly/spec|date=10 February 2019|publisher=|via=GitHub}} 12. ^{{cite web|url=http://ocaml.org/learn/companies.html|title=Companies using OCaml|access-date=17 August 2014|publisher=OCaml.org}} 13. ^{{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|accessdate=21 May 2017}} 14. ^{{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|publisher=|access-date=2 May 2015}} External links{{wikibooks|OCaml}}
13 : Articles with example code|Articles with example OCaml code|Cross-platform free software|Extensible syntax programming languages|Free compilers and interpreters|Functional languages|ML programming language family|Object-oriented programming languages|OCaml programming language family|OCaml software|Pattern matching programming languages|Programming languages created in 1996|Statically typed programming languages |
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。