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 types of variables and the signatures 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",[8] 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
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.[9][10] Milner and others were working on theorem provers, which were historically developed in languages such as Lisp. Milner repeatedly ran into the issue that the theorem provers would attempt to claim a proof was valid by putting non-proofs together.[10] As a result, he went on to develop the 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.[11] 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.[11] ML would eventually serve as a basis for the creation of OCaml.
In the early 1980s, there were some developments that prompted 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.[12]
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 and Michel Mauny carried on with development after he left in 1988.[12]
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.”[12]
Caml Light
Between 1990 and 1991, Xavier Leroy designed a new implementation of Caml based on a bytecode interpreter written in C. In addition to this, Damien Doligez wrote a memory management system, also known as a sequential garbage collector, for this implementation.[11] This new implementation, known as Caml Light, replaced the old Caml implementation and ran on small desktop machines.[12] 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.[11]
Caml Special Light
In 1995, Xavier Leroy released Caml Special Light, which was an improved version of Caml.[12] An optimizing native-code compiler was added to the bytecode compiler, which greatly increased performance to comparable levels with mainstream languages such as C++.[11][12] 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.[11]
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. In 2000, Jacques Garrigue extended Objective Caml with multiple new features such as polymorphic methods, variants, and labeled and optional arguments.[11][12]
Ongoing development
Language improvements have been incrementally added for the last two decades to support the growing commercial and academic codebases in OCaml.[11] The OCaml 4.0 release in 2012 added Generalized Algebraic Data Types (GADTs) and first-class modules to increase the flexibility of the language.[11] The OCaml 5.0.0 release in 2022[13] is a complete rewrite of the language runtime, removing the global GC lock and adding effect handlers via delimited continuations. These changes enable support for 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.[14] Subsequently, Gallium was succeeded by the Cambium team in 2019.[15][16] As of 2023, there are 23 core developers of the compiler distribution from a variety of organizations[17] and 41 developers for the broader OCaml tooling and packaging ecosystem.[18] In 2023, the OCaml compiler was recognised with ACM SIGPLAN's Programming Languages Software Award.
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.
Although OCaml does not have a macro system as an indivisible part of the language (metaprogramming), i.e. built-in support for preprocessing, the 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 level. The latter, which is called PPX, acronym for Pre-Processor eXtension, is the recommended one.
The native code compiler is available for many platforms, including Unix, Microsoft Windows, and ApplemacOS. Portability is achieved through native code generation support for major architectures:
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 multithreaded style, with preemptive context switching. OCaml threads in the same domain[20] execute by time sharing only. However, an OCaml program can contain several domains.
Snippets of OCaml code are most easily studied by entering them into the top-level REPL. This is an interactive OCaml session that prints the inferred types of resulting or defined expressions.[21] 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-precisioninteger) 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!$
The first argument to ocamlc, "hello.ml", specifies the source file to compile and the "-o hello" flag specifies the output file.[22]
Option
The option type constructor in OCaml, similar to the Maybe type in Haskell, augments a given data type to either return Some value of the given data type, or to return None.[23] This is used to express that a value might or might not be present.
#Some42;;-:intoption=Some42#None;;-:'aoption=None
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, or if not, returns an empty string:
Lists are one of the fundamental datatypes in OCaml. The following code example defines a recursive function sum that accepts one argument, integers, which is supposed to be a list of integers. Note the keyword rec 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's switch element, though it is far more general.
letrecsumintegers=(* Keyword rec means 'recursive'. *)matchintegerswith|[]->0(* Yield 0 if integers is the empty list []. *)|first::rest->first+sumrest;;(* 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 []. *)
#sum[1;2;3;4;5];;-:int=15
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:
letsumintegers=List.fold_left(+)0integers
Furthermore, one can omit the list argument by making use of a partial application:
letsum=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.
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).
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".
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";;#openNum;;
The factorial function may then be written using the arbitrary-precision numeric operators =/, */ and -/ :
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.
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.
#add298;;-: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.
MetaOCaml[24] 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 functionx->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:
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 ocaml.org.
Perang FarraposLukisan yang menggambarkan pasukan Rio Grande. Lukisan ini dibuat oleh Guilherme Litran (Museum Júlio de Castilhos, Porto Alegre).Tanggal20 September 1835 – 1 Maret 1845LokasiBrasil selatanHasil Perjanjian perdamaian. Republik Rio Grande kembali menjadi bagian dari Kekaisaran Brasil.Pihak terlibat Republik Rio Grande Republik Juliana Kekaisaran BrasilTokoh dan pemimpin Bento Gonçalves da Silva Antônio de Sousa Neto David Canabarro Giuseppe Garibaldi Lu
Інші назви GBT На честь Роберт Берд[1]Частина від Обсерваторія Грін-Банк[1] і Національна радіоастрономічна обсерваторіяРозташування Покахонтас[2][1]Координати 38°25′59″ пн. ш. 79°50′23″ зх. д. / 38.43312111113888818° пн. ш. 79.83983500002777589° зх...
Leibnizufer WappenStraße in Hannover Leibnizufer Basisdaten Stadt Hannover Stadtteil Calenberger Neustadt, Mitte Name erhalten 1951 Anschlussstraßen Friederikenplatz, Goethestraße Querstraßen Calenberger Straße, Clemensstraße, Schloßstraße Nutzung Straßengestaltung Duve-Brunnen, Nana Technische Daten Straßenlänge 565 m Karte Blick auf das sechsspurige Leibnizufer, links die Leine mit Leineschloss und Neuem Rathaus, rechts die Calenberger Neustadt Das Leibnizufer ist ein...
Star fort in Valletta, Malta For other uses, see Saint Elmo (disambiguation) and San Telmo (disambiguation). Fort Saint ElmoForti Sant'IermuPart of the fortifications of VallettaValletta, Malta Aerial view of Valletta, with Fort St. Elmo in the foregroundMap of Fort St. ElmoCoordinates35°54′07″N 14°31′08″E / 35.9020°N 14.5188°E / 35.9020; 14.5188TypeStar fort integrated into a city wallArea50,400 m2 (543,000 sq ft)Site informationOwnerGovernm...
Emile ChautardSutradara Frank Borzage, tengah, dengan para anggota pemeran (dari kiri) Charles Farrell, George E. Stone (berbaring), Émile Chautard, dan David Butler pada pengambilan gambar medan tempur 7th Heaven (1927)Lahir(1864-09-07)7 September 1864Paris, PrancisMeninggal24 April 1934(1934-04-24) (umur 69)Westwood, Los Angeles, California, Amerika SerikatPekerjaanSutradara, pemeran, penulis naskahTahun aktif1910-1934 Émile Chautard (7 September 1864 – 24 April ...
Yanmar StadionView of Yanmar Stadion in 2020Former namesMitsubishi Forkliftstadion (2005–2013)Almere City Stadion (2013–2015)Yanmar Stadion (2015–present)LocationCompetitieweg 201318 EA AlmereCoordinates52°23′40″N 5°14′26″E / 52.3944°N 5.2405°E / 52.3944; 5.2405OwnerAlmere City FCCapacity4,501[1]Field size105 by 68 metres (114.8 yd × 74.4 yd)SurfaceGrass[3]ConstructionOpened2005[1]Expanded2019–2020[2]T...
Koin mancus bergambar raja Ethelred II, 1003–1006. Mancus (kadang dieja mancosus atau semacamnya) adalah satuan mata uang pada Eropa abad pertengahan awal, yang dapat berupa koin emas 4,25 gram (sama dengan dinar di Dunia Islam,,[1] dan lebih ringan dibanding solidus (koin) di Bizantium), atau satuan senilai 30 penny perak. Dengan demikian, satu mancus kira-kira bernilai sekitar satu bulan upah pekerja terdidik seperti tukang atau serdadu.[2] Referensi ^ Grierson 2007, p.327...
Mexican politician Elvira OlivasBorn (1935-10-28) 28 October 1935 (age 88)State of Mexico, MexicoNationalityMexicanOccupationPoliticianPolitical party PRI María Elvira Olivas Hernández (born 28 October 1935) is a Mexican politician from the Institutional Revolutionary Party. In 2012 she served as Deputy of the LXI Legislature of the Mexican Congress representing the State of Mexico.[1] References ^ Perfil del legislador. Legislative Information System. Retrieved 10 Decembe...
Mountain Moving Coffeehouse for Womyn and ChildrenSuccessorKindred Hearts' CoffeehouseFormation1974DissolvedDecember 10, 2005TypeCoffeehouseLegal statusCollectivePurposeWomyn's music and cultureLocation1700 W. Farragut Chicago, Illinois United StatesCoordinates41°58′38.37″N 87°40′20.28″W / 41.9773250°N 87.6723000°W / 41.9773250; -87.6723000Region served Chicago Part of a series onLesbian feminism Women's liberation movement People Paula Gunn Allen Dorothy A...
American basketball player (born 1942) Fred HetzelHetzel as a sophomore at DavidsonPersonal informationBorn (1942-07-21) July 21, 1942 (age 81)Washington, D.C., U.S.Listed height6 ft 8 in (2.03 m)Listed weight220 lb (100 kg)Career informationHigh school Woodrow Wilson(Washington, D.C.) Landon School(Bethesda, Maryland) CollegeDavidson (1962–1965)NBA draft1965: 1st round, 1st overall pickSelected by the San Francisco WarriorsPlaying career1965–1971PositionPowe...
Tuvalu Keanggotaan Perserikatan Bangsa-BangsaKeanggotaanAnggota penuhSejak2000 (2000)Kursi DK PBBNon-permanen (tak pernah terpilih)Duta BesarAunese Simati Tuvalu menjadi anggota ke-189 dari Perserikatan Bangsa-Bangsa pada September 2000.[1][2] Pada saat ini Perwakilan Permanen negara tersebut untuk PBB adalah Dubes Aunese Simati. Tuvalu adalah salah satu 19 negara yang tak mengakui Republik Rakyat Tiongkok, salah satu dari lima anggota permanen Dewan Keamanan Perserikatan...
Japanese footballer Yuika Sugasawa菅澤 優衣香 Personal informationFull name Yuika SugasawaDate of birth (1990-10-05) October 5, 1990 (age 33)Place of birth Chiba, Chiba, JapanHeight 1.68 m (5 ft 6 in)Position(s) ForwardTeam informationCurrent team Urawa RedsNumber 9Youth career2006–2008 JFA Academy FukushimaSenior career*Years Team Apps (Gls)2008–2012 Albirex Niigata 60 (19)2013–2016 JEF United Chiba 79 (44)2017– Urawa Reds 94 (71)Total 233 (134)International ...
У Вікіпедії є статті про інші значення цього терміна: Колонія (значення). Мапа Бессарабської губернії Протягом декількох десятиліть у XIX столітті з метою залучення єврейського населення до землеробства та сільськогосподарського освоєння степів та нових земель царський...
Private not-for-profit game reserve in southern Botswana Mokolodi Nature ReserveMokolodi and surrounding area in the dry seasonLocationGaborone SouthCoordinates24°44′36″S 25°47′56″E / 24.743294°S 25.798903°E / -24.743294; 25.798903Established1994 by The Mokolodi Wildlife Foundation, Mokolodi Nature Reserve is a private not-for-profit game reserve in southern Botswana. Founded in 1994 by The Mokolodi Wildlife Foundation, it is situated on 30 square kilometre...
Protected area in South AustraliaWitjira National ParkSouth AustraliaIUCN category VI (protected area with sustainable use of natural resources)[1] Dalhousie Springs in Witjira National ParkWitjira National ParkNearest town or cityFinkeCoordinates26°20′20″S 135°40′30″E / 26.3388494009999°S 135.675051581°E / -26.3388494009999; 135.675051581[1]Established21 November 1985 (1985-11-21)[2]Area7,726.73 km2 (2,983.3 ...
Para otros usos de este término, véase José Palop Gómez. Andrés Palop Datos personalesNombre completo Andrés Palop CerveraApodo(s) La Pantera de l'AlcudiaSan PalopNacimiento La Alcudia, Valencia, España22 de octubre de 1973 (50 años)Nacionalidad(es) Altura 1,84 metrosCarrera deportivaDeporte FútbolClub profesionalDebut deportivo 1995(Valencia C. F. B)Posición PorteroGoles en clubes 1Retirada deportiva 2014(Bayer Leverkusen) &...
Peta letak Pulau Deli Pulau DeliPulau DeliPulau Deli (Indonesia)Pulau DeliGeografiLokasiAsia TenggaraKoordinat7°00′23″S 105°32′43″E / 7.006379°S 105.545162°E / -7.006379; 105.545162Koordinat: 7°00′23″S 105°32′43″E / 7.006379°S 105.545162°E / -7.006379; 105.545162PemerintahanNegaraIndonesiaProvinsiProvinsi BantenKabupatenKabupaten PandeglangInfo lainnyaZona waktuWIB (UTC+07:00) Pulau Deli, adalah sebuah pulau kecil yang te...
Kementerian Kesehatan, Tenaga Kerja, dan Sosial厚生労働省Kōsei-rōdō-shōInformasi lembagaDibentuk2001 (2001)Nomenklatur sebelumnyaKementerian Kesehatan dan Kesejahteraan (厚生省code: ja is deprecated , Kōsei-shō)Kementerian Tenaga Kerja (労働省code: ja is deprecated , Rōdō-shō)Wilayah hukum JepangKantor pusat1-2-2 Kasumigaseki, Chiyoda-ku, Tokyo, 100-8916 JepangMenteriNorihisa Tamura, Menteri Kesehatan, Tenaga Kerja, dan SosialGaku Hashimoto, Menteri Negara Keseha...
此條目没有列出任何参考或来源。 (2012年3月26日)維基百科所有的內容都應該可供查證。请协助補充可靠来源以改善这篇条目。无法查证的內容可能會因為異議提出而被移除。 费雪自然选择基本定理(英語:Fisher's fundamental theorem of natural selection),由羅納德·費雪爵士在1933年首次提出,是现代进化论中关于自然选择的一个基本定理,该定理显示平均适合度的增加等于适合度...
Marco Emilio BarbulaConsole della Repubblica romanaNome originaleMarcus Aemilius Barbula GensEmilia PadreLucio Emilio Barbula Consolato230 a.C. Marco Emilio Barbula [1] (in latino: Marcus Aemilius Barbula; ... – ...; fl. III secolo a.C.) è stato un politico romano. Biografia Figlio di Lucio Emilio Barbula, (console nel 281 a.C.), fu a sua volta eletto console della Repubblica romana nel 230 a.C. con Marco Giunio Pera. Con il collega condusse la guerra contro i Liguri. Come rip...