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).
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]
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 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:
Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2022. Kinoko no yama Kinoko no yama (きのこの山code: ja is deprecated ) adalah permen cokelat dari Jepang yang dibuat dalam bentuk jamur kecil. Kata kinoko berarti jamur dan yama berarti gunung. Induk dari jamur terbuat dari kue biskuit dan bagian atasnya …
Ansar Bait al-Maqdisأنصار بيت المقدس Bendera Ansar Bait al-MaqdisBerkas:Ansar Bayt al-Maqdis (شعارات جماعة أنصار بيت المقدس 3).pngLambang Ansar Bait al-MaqdisPemimpinWaleed Waked (POW)[1]Ibrahim Mohamed Freg †[2]Shadi el-Manaei[3]Waktu operasi2011–10 November 2014[4]MarkasJazirah SinaiWilayah operasi Mesir Jalur Gaza[5][6]IdeologiJihadisme salafiJumlah anggota1.000[7]…
County in Pennsylvania, United States Not to be confused with Centre Region Council of Governments. County in PennsylvaniaCentre CountyCountyThe Centre County Courthouse in Bellefonte FlagSealLogoLocation within the U.S. state of PennsylvaniaPennsylvania's location within the U.S.Coordinates: 40°55′N 77°49′W / 40.91°N 77.82°W / 40.91; -77.82Country United StatesState PennsylvaniaFoundedFebruary 13, 1800Named forCentre Furnace, the first industrial facili…
Часть серии статей о Холокосте Идеология и политика Расовая гигиена · Расовый антисемитизм · Нацистская расовая политика · Нюрнбергские расовые законы Шоа Лагеря смерти Белжец · Дахау · Майданек · Малый Тростенец · Маутхаузен · …
Republic Entertainment, Inc. Republic Pictures Tipo anterior Subsidiária Atividade Entretenimento Fundação 1935 (original) 2023 (refundação) Fundador(es) Herbert J. Yates Encerramento 1967 (original) Ativa (atualmente) Sede Studio City, Los Angeles, Califórnia Estados Unidos Empresa-mãe ViacomCBS Republic Pictures (também conhecida como Republic Entertainment, Inc.) é atualmente um selo de aquisições de distribuições de filmes da Paramount Global. No passado foi uma empre…
Konvoi Arktik pada Perang Dunia IIBagian dari Perang Dunia IIPemandangan dari kapal penjelajah HMS Sheffield saat kapal tersebut berlayar dalam tugas konvoi melalui perairan Samudra Arktik. Di latar belakang adalah kapal-kapal dagang dari konvoi tersebut.TanggalAgustus 1941 – Mei 1945LokasiLaut Norwegia dan Samudra ArktikHasil Kemenangan SekutuPihak terlibat Britania Raya Uni Soviet Kanada Amerika Serikat Norwegia JermanKorban 85 kapal dagang16 kapal perang…
قرية واترلو الإحداثيات 42°54′13″N 76°51′34″W / 42.903611111111°N 76.859388888889°W / 42.903611111111; -76.859388888889 [1] تاريخ التأسيس 9 أبريل 1824 تقسيم إداري البلد الولايات المتحدة[2] التقسيم الأعلى مقاطعة سينيكا عاصمة لـ مقاطعة سينيكا خصائص جغرافية المساحة 5.70789…
B.9 Nine-cylinder Salmson on display at the London Science Museum Type Radial engine Manufacturer British Salmson First run 1913 Number built 106 The Salmson B.9 was a French designed, nine-cylinder, water-cooled radial aero engine that was produced under license in Britain. The engine was produced between August 1914 and December 1918. The French version was designated 9B with a slightly increased capacity variant known as the R.9 or 9R.[1] A further variant known as the M.9 or 9M unusu…
Pour les articles homonymes, voir CMH. Centre Maurice-Halbwachs (CMH)Logo du Centre Maurice-HalbwachsHistoireFondation 2004CadreCode UMR 8097Type LaboratoireDomaine d'activité sociologieSiège Paris (48, boulevard Jourdan)Pays FranceCoordonnées 48° 49′ 20″ N, 2° 19′ 52″ EOrganisationChercheurs 50Chercheurs associés 50Doctorants 120Direction Serge PaugamOrganisations mères École normale supérieureÉcole des hautes études en sciences socialesAffiliati…
Church in New York City, United StatesChurch of Sts. Cyril & Methodius and St. RaphaelWest side of the church, 2011LocationHell's KitchenManhattan, New York CityCountryUnited StatesDenominationRoman CatholicWebsitecroatianchurchnewyork.orgHistoryFounded1886, 1913ArchitectureArchitect(s)George H. StreetonStyleGothic RevivalYears built1901–1903SpecificationsMaterialsStructural masonryFaçade: Manhattan schistRed brick with stone trimAdministrationArchdioceseNew York The Catholic Church of St…
Dmanissi დმანისი Partie occidentale de la commune Administration Pays Géorgie Subdivision Basse Kartlie Indicatif téléphonique +995 360 Démographie Population 3 600 hab. (2009[1]) Géographie Coordonnées 41° 19′ 00″ nord, 44° 21′ 00″ est Altitude 1 171 m Histoire Fondation début de l'Âge du bronze Première mention IXe siècle Statut village Localisation Géolocalisation sur la carte : Géorgie Dmanissi G…
Questa voce sull'argomento economisti statunitensi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Roger Myerson Premio Nobel per l'economia 2007 Roger Myerson (Boston, 29 marzo 1951) è un economista statunitense. Nel 2007 ha vinto il premio Nobel per l'economia (assegnatogli il 15 ottobre) insieme a Leonid Hurwicz e Eric Maskin per aver gettato le fondamenta della teoria del mechanism design[1]. Indice 1 Biografia 2 Pubblicazioni 2.1 Contributi …
Voce principale: Livorno Calcio. Associazione Sportiva Livorno CalcioStagione 2010-2011Sport calcio Squadra Livorno Allenatore Giuseppe Pillon (fino al 14 febbraio) Walter Novellino (dal 15 febbraio) Presidente Aldo Spinelli Serie B7º posto Coppa ItaliaQuarto turno Maggiori presenzeCampionato: De Lucia, Iori (39)Totale: De Lucia, Dionisi, Luci, Schiattarella (40) Miglior marcatoreCampionato: Dionisi e Tavano (10)Totale: Dionisi (11) StadioStadio Armando Picchi Abbonati2.700 2009-2010 2011-…
This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: 2002 West Virginia Senate election – news · newspapers · books · scholar · JSTOR (February 2024) 2002 West Virginia Senate elections ← 2000 November 5, 2002 2004 → ← These seats' last election (1998)These seats' next elec…
Penyuntingan Artikel oleh pengguna baru atau anonim untuk saat ini tidak diizinkan.Lihat kebijakan pelindungan dan log pelindungan untuk informasi selengkapnya. Jika Anda tidak dapat menyunting Artikel ini dan Anda ingin melakukannya, Anda dapat memohon permintaan penyuntingan, diskusikan perubahan yang ingin dilakukan di halaman pembicaraan, memohon untuk melepaskan pelindungan, masuk, atau buatlah sebuah akun. Artikel ini perlu dikembangkan dari artikel terkait di Wikipedia bahasa Inggris. …
Large knife or small sword wielded by Saxons and their contemporaries For the metal band, see Seax (band). Some Merovingian seaxes A seax (Old English pronunciation: [ˈsæɑks]; also sax, sæx, sex; invariant in plural, latinized sachsum) is a small sword, fighting knife or dagger typical of the Germanic peoples of the Migration Period and the Early Middle Ages, especially the Saxons. The name comes from an Old English word for knife.[1] In heraldry, the seax is a charge consist…
Chinese dessert wine This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Lychee wine – news · newspapers · books · scholar · JSTOR (February 2020) (Learn how and when to remove this message) Lychee wine Lychee wine (Chinese: 荔枝酒, lìzhījiǔ) is a full-bodied Chinese dessert wine[1] made of 100%&…
Serbian folk singer (1951–2019) Šaban ŠaulićШабан ШаулићŠaulić performing in Sofia in March 2016.Born(1951-09-06)6 September 1951Šabac, PR Serbia, FPR YugoslaviaDied17 February 2019(2019-02-17) (aged 67)Bielefeld, North Rhine-Westphalia, GermanyCause of deathTraffic collisionOccupationSingerYears active1969–2019Spouse Gordana Dragaš (m. 1974–2019)Children4ParentsHuso Šaulić (father)Ilduza Demirović (moth…