Programming Language Manuals
Collection
5 items • Updated
text stringlengths 10 16.2k |
|---|
# OCaml - The OCaml Manual
Source: https://ocaml.org/manual/5.2/manual001.html
☰ |
# The OCaml system release 5.2 |
### February, 2024 |
# Contents
[Home](index.html)[Foreword »](foreword.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------ |
# OCaml - The OCaml Manual
Source: https://ocaml.org/manual/5.2/foreword.html
☰ |
# The OCaml system release 5.2 |
### February, 2024 |
# Foreword
- [Conventions](foreword.html#conventions)
- [License](foreword.html#license)
- [Availability](foreword.html#availability)
This manual documents the release 5.2 of the OCaml system. It is organized as follows.
- Part [I](index.html#p%3Atutorials), “An introduction to OCaml”, gives an overview of the... |
## Conventions
OCaml runs on several operating systems. The parts of this manual that are specific to one operating system are presented as shown below:
> Unix: This is material specific to the Unix family of operating systems, including Linux and macOS.
> Windows: This is material specific to Microsoft Windows (Vist... |
## License
The OCaml system is copyright © 1996–2024 Institut National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership rights to the OCaml system.
The OCaml system is open source and can be freely redistributed. See the file LICENSE in the distribution for licensing information.
The OC... |
## Availability
The complete OCaml distribution can be accessed via the [ocaml.org website](https://ocaml.org/). This site contains a lot of additional information on OCaml.
[« Contents](manual001.html)[The core language »](coreexamples.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automat... |
# OCaml - The core language
Source: https://ocaml.org/manual/5.2/coreexamples.html
☰
- [The core language](coreexamples.html)
- [The module system](moduleexamples.html)
- [Objects in OCaml](objectexamples.html)
- [Labeled arguments](lablexamples.html)
- [Polymorphic variants](polyvariant.html)
- [Polymorphi... |
# Chapter 1 The core language
This part of the manual is a tutorial introduction to the OCaml language. A good familiarity with programming in a conventional languages (say, C or Java) is assumed, but no prior exposure to functional languages is required. The present chapter introduces the core language. Chapter [2](m... |
## 1 Basics
For this overview of OCaml, we use the interactive system, which is started by running ocaml from the Unix shell or Windows command prompt. This tutorial is presented as the transcript of a session with the interactive system: lines starting with # represent user input; the system responses are printed belo... |
## 2 Data types
In addition to integers and floating-point numbers, OCaml offers the usual basic data types:
- booleans
```ocaml
# (1 \< 2) = false;;
- : bool = false
# let one = if true then 1 else 2;;
val one : int = 1
```
- characters
```ocaml
# 'a';;
- : char = 'a'
# int_of_char '\\n';;
- : int = 10
```
- i... |
## 2 Data types
As with all other OCaml data structures, lists do not need to be explicitly allocated and deallocated from memory: all memory management is entirely automatic in OCaml. Similarly, there is no explicit handling of pointers: the OCaml compiler silently introduces pointers where necessary.
As with most OCa... |
## 2 Data types
The sort function above does not modify its input list: it builds and returns a new list containing the same elements as the input list, in ascending order. There is actually no way in OCaml to modify a list in-place once it is built: we say that lists are *immutable* data structures. Most OCaml data st... |
## 3 Functions as values
OCaml is a functional language: functions in the full mathematical sense are supported and can be passed around freely just as any other piece of data. For instance, here is a deriv function that takes any float function as argument and returns an approximation of its derivative function:
```oc... |
## 4 Records and variants
User-defined data structures include records and variants. Both are defined with the type declaration. Here, we declare a record type to represent rational numbers.
```ocaml
# type ratio = {num: int; denom: int};;
type ratio = { num : int; denom : int; }
# let add_ratio r1 r2 = {num = r1.num ... |
## 4 Records and variants
```ocaml
# let ratio num denom = {num; denom};;
val ratio : int -> int -> ratio = \<fun\>
```
At last, it is possible to update few fields of a record at once:
```ocaml
# let integer_product integer ratio = { ratio with num = integer \* ratio.num };;
val integer_product : int -> ratio -> ratio... |
## 4 Records and variants
To define arithmetic operations for the number type, we use pattern-matching on the two numbers involved:
```ocaml
# let add_num n1 n2 = match (n1, n2) with (Int i1, Int i2) -> (\* Check for overflow of integer addition \*) if sign_int i1 = sign_int i2 && sign_int (i1 + i2) \<\> sign_int i1 th... |
## 4 Records and variants
This definition reads as follows: a binary tree containing values of type 'a (an arbitrary type) is either empty, or is a node containing one value of type 'a and two subtrees also containing values of type 'a, that is, two 'a btree.
Operations on binary trees are naturally expressed as recurs... |
### 4.1 Record and variant disambiguation
( This subsection can be skipped on the first reading )
Astute readers may have wondered what happens when two or more record fields or constructors share the same name
```ocaml
# type first_record = { x:int; y:int; z:int } type middle_record = { x:int; z:int } type last_record... |
### 4.1 Record and variant disambiguation
In the first example, (r:first_record) is an explicit annotation telling OCaml that the type of r is first_record. With this annotation, Ocaml knows that r.x refers to the x field of the first record type. Similarly, the type annotation in the second example makes it clear to O... |
### 4.1 Record and variant disambiguation
Here, OCaml has inferred that the possible choices for the type of {x;z} are first_record and middle_record, since the type last_record has no field z. Ocaml then picks the type middle_record as the last defined type between the two possibilities.
Beware that this last resort d... |
## 5 Imperative features
Though all examples so far were written in purely applicative style, OCaml is also equipped with full imperative features. This includes the usual while and for loops, as well as mutable data structures such as arrays. Arrays are either created by listing semicolon-separated element values betw... |
## 5 Imperative features
OCaml has no built-in notion of variable – identifiers whose current value can be changed by assignment. (The let binding is not an assignment, it introduces a new identifier with a new scope.) However, the standard library provides references, which are mutable indirection cells, with operator... |
## 5 Imperative features
In some special cases, you may need to store a polymorphic function in a data structure, keeping its polymorphism. Doing this requires user-provided type annotations, since polymorphism is only introduced automatically for global definitions. However, you can explicitly give polymorphic types t... |
## 6 Exceptions
OCaml provides exceptions for signalling and handling exceptional conditions. Exceptions can also be used as a general-purpose non-local control structure, although this should not be overused since it can make the code harder to understand. Exceptions are declared with the exception construct, and sign... |
## 6 Exceptions
The with part does pattern matching on the exception value with the same syntax and behavior as match. Thus, several exceptions can be caught by one try…with construct:
```ocaml
# let rec first_named_value values names = try List.assoc (head values) names with \| Empty_list -> "no named value" \| Not_fo... |
## 6 Exceptions
but they cannot be nested inside other patterns. For instance, the pattern Some (exception A) is invalid.
When exceptions are used as a control structure, it can be useful to make them as local as possible by using a locally defined exception. For instance, with
```ocaml
# let fixpoint f x = let excepti... |
## 7 Lazy expressions
OCaml allows us to defer some computation until later when we need the result of that computation.
We use lazy (expr) to delay the evaluation of some expression expr. For example, we can defer the computation of 1+1 until we need the result of that expression, 2. Let us see how we initialize a laz... |
## 7 Lazy expressions
This is because Lazy.force memoizes the result of the forced expression. In other words, every subsequent call of Lazy.force on that expression returns the result of the first computation without recomputing the lazy expression. Let us force lazy_two once again.
```ocaml
# Lazy.force lazy_two;;
- ... |
## 8 Symbolic processing of expressions
We finish this introduction with a more complete example representative of the use of OCaml for symbolic processing: formal manipulations of arithmetic expressions containing variables. The following variant type describes the expressions we shall manipulate:
```ocaml
# type expr... |
## 8 Symbolic processing of expressions
Now for a real symbolic processing, we define the derivative of an expression with respect to a variable dv:
```ocaml
# let rec deriv exp dv = match exp with Const c -> Const 0.0 \| Var v -> if v = dv then Const 1.0 else Const 0.0 \| Sum(f, g) -> Sum(deriv f dv, deriv g dv) \| Di... |
## 9 Pretty-printing
As shown in the examples above, the internal representation (also called *abstract syntax*) of expressions quickly becomes hard to read and write as the expressions get larger. We need a printer and a parser to go back and forth between the abstract syntax and the *concrete syntax*, which in the ca... |
## 9 Pretty-printing
```ocaml
# let print_expr exp = (\* Local function definitions \*) let open_paren prec op_prec = if prec \> op_prec then print_string "(" in let close_paren prec op_prec = if prec \> op_prec then print_string ")" in let rec print prec exp = (\* prec is the current precedence \*) match exp with Cons... |
## 10 Printf formats
There is a printf function in the [Printf](../5.2/api/Printf.html) module (see chapter [2](moduleexamples.html#c%3Amoduleexamples)) that allows you to make formatted output more concisely. It follows the behavior of the printf function from the C standard library. The printf function takes a forma... |
## 10 Printf formats
Outputting an integer using a custom printer: 42 - : unit = ()
The advantage of those printers based on the %a specifier is that they can be composed together to create more complex printers step by step. We can define a combinator that can turn a printer for 'a type into a printer for 'a optional:... |
## 10 Printf formats
```ocaml
# let pp_expr ppf expr = let open_paren prec op_prec output = if prec \> op_prec then Printf.fprintf output "%s" "(" in let close_paren prec op_prec output = if prec \> op_prec then Printf.fprintf output "%s" ")" in let rec print prec ppf expr = match expr with \| Const c -> Printf.fprintf... |
## 11 Standalone OCaml programs
All examples given so far were executed under the interactive system. OCaml code can also be compiled separately and executed non-interactively using the batch compilers ocamlc and ocamlopt. The source code must be put in a file with extension .ml. It consists of a sequence of phrases, w... |
## 11 Standalone OCaml programs
More complex standalone OCaml programs are typically composed of multiple source files, and can link with precompiled libraries. Chapters [13](comp.html#c%3Acamlc) and [16](native.html#c%3Anativecomp) explain how to use the batch compilers ocamlc and ocamlopt. Recompilation of multi-fi... |
# OCaml - The module system
Source: https://ocaml.org/manual/5.2/moduleexamples.html
☰
- [The core language](coreexamples.html)
- [The module system](moduleexamples.html)
- [Objects in OCaml](objectexamples.html)
- [Labeled arguments](lablexamples.html)
- [Polymorphic variants](polyvariant.html)
- [Polymorp... |
# Chapter 2 The module system
This chapter introduces the module system of OCaml. |
## 1 Structures
A primary motivation for modules is to package together related definitions (such as the definitions of a data type and associated operations over that type) and enforce a consistent naming scheme for these definitions. This avoids running out of names or accidentally confusing names. Such a package is ... |
## 1 Structures
Outside the structure, its components can be referred to using the “dot notation”, that is, identifiers qualified by a structure name. For instance, Fifo.add is the function add defined inside the structure Fifo and Fifo.queue is the type queue defined in Fifo.
```ocaml
# Fifo.add "hello" Fifo.empty;;
-... |
## 1 Structures
```ocaml
# Fifo.(add "hello" empty);;
- : string Fifo.queue = {front = \["hello"\]; rear = \[\]}
```
In the second form, when the body of a local open is itself delimited by parentheses, braces or bracket, the parentheses of the local open can be omitted. For instance,
```ocaml
# Fifo.\[empty\] = Fifo.(... |
## 2 Signatures
Signatures are interfaces for structures. A signature specifies which components of a structure are accessible from the outside, and with which type. It can be used to hide some components of a structure (e.g. local function definitions) or export some components with a restricted type. For instance, th... |
## 2 Signatures
The restriction can also be performed during the definition of the structure, as in
module Fifo = (struct ... end : FIFO);;
An alternate syntax is provided for the above:
module Fifo : FIFO = struct ... end;;
Like for modules, it is possible to include a signature to copy its components inside t... |
## 3 Functors
Functors are “functions” from modules to modules. Functors let you create parameterized modules and then provide other modules as parameter(s) to get a specific implementation. For instance, a Set module implementing sets as sorted lists could be parameterized to work with any module that provides an elem... |
## 3 Functors
```ocaml
# module OrderedString = struct type t = string let compare x y = if x = y then Equal else if x \< y then Less else Greater end;;
```
module OrderedString : sig type t = string val compare : 'a -> 'a -> comparison end
```ocaml
# module StringSet = Set(OrderedString);;
```
module StringSet : sig t... |
## 4 Functors and type abstraction
As in the Fifo example, it would be good style to hide the actual implementation of the type set, so that users of the structure will not rely on sets being lists, and we can switch later to another, more efficient representation of sets without breaking their code. This can be achiev... |
## 4 Functors and type abstraction
module type SET = sig type element type set val empty : set val add : element -> set -> set val member : element -> set -> bool end
```ocaml
# module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);;
```
module WrongSet : functor (Elt : ORDERED_TYPE) -> SET
```ocaml
# module Wron... |
## 4 Functors and type abstraction
module AbstractSet2 : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set val empty : set val add : element -> set -> set val member : element -> set -> bool end
As in the case of simple structures, an alternate syntax is provided for defining functors and restricting th... |
## 4 Functors and type abstraction
Note that the two types AbstractStringSet.set and NoCaseStringSet.set are not compatible, and values of these two types do not match. This is the correct behavior: even though both set types contain elements of the same type (strings), they are built upon different orderings of that t... |
## 5 Modules and separate compilation
All examples of modules so far have been given in the context of the interactive system. However, modules are most useful for large, batch-compiled programs. For these programs, it is a practical necessity to split the source into several files, called compilation units, that can b... |
## 5 Modules and separate compilation
$ ocamlc -c Aux.mli # produces aux.cmi
$ ocamlc -c Aux.ml # produces aux.cmo
$ ocamlc -c Main.mli # produces main.cmi
$ ocamlc -c Main.ml # produces main.cmo
$ ocamlc -o theprogram A... |
## 5 Modules and separate compilation
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------ |
# OCaml - Objects in OCaml
Source: https://ocaml.org/manual/5.2/objectexamples.html
☰
- [The core language](coreexamples.html)
- [The module system](moduleexamples.html)
- [Objects in OCaml](objectexamples.html)
- [Labeled arguments](lablexamples.html)
- [Polymorphic variants](polyvariant.html)
- [Polymorph... |
# Chapter 3 Objects in OCaml
This chapter gives an overview of the object-oriented features of OCaml.
Note that the relationship between object, class and type in OCaml is different than in mainstream object-oriented languages such as Java and C++, so you shouldn’t assume that similar keywords mean the same thing. Obje... |
## 1 Classes and objects
The class point below defines one instance variable x and two methods get_x and move. The initial value of the instance variable is 0. The variable x is declared mutable, so the method move can change its value.
```ocaml
# class point = object val mutable x = 0 method get_x = x method move d = ... |
## 1 Classes and objects
```ocaml
# class point = fun x_init -> object val mutable x = x_init method get_x = x method move d = x \<- x + d end;;
```
class point : int -> object val mutable x : int method get_x : int method move : int -> unit end
Like in function definitions, the definition above can be abbreviated as:
... |
## 1 Classes and objects
```ocaml
# class adjusted_point x_init = let origin = (x_init / 10) \* 10 in object val mutable x = origin method get_x = x method get_offset = x - origin method move d = x \<- x + d end;;
```
class adjusted_point : int -> object val mutable x : int method get_offset : int method get_x : int me... |
## 2 Immediate objects
There is another, more direct way to create an object: create it without going through a class.
The syntax is exactly the same as for class expressions, but the result is a single object rather than a class. All the constructs described in the rest of this section also apply to immediate objects.... |
## 3 Reference to self
A method or an initializer can invoke methods on self (that is, the current object). For that, self must be explicitly bound, here to the variable s (s could be any identifier, even though we will often choose the name self.)
```ocaml
# class printable_point x_init = object (s) val mutable x = x_... |
## 3 Reference to self
You can ignore the first two lines of the error message. What matters is the last one: putting self into an external reference would make it impossible to extend it through inheritance. We will see in section [3.12](#s%3Ausing-coercions) a workaround to this problem. Note however that, since imm... |
## 4 Initializers
Let-bindings within class definitions are evaluated before the object is constructed. It is also possible to evaluate an expression immediately after the object has been built. Such code is written as an anonymous hidden method called an initializer. Therefore, it can access self and the instance vari... |
## 5 Virtual methods
It is possible to declare a method without actually defining it, using the keyword virtual. This method will be provided later in subclasses. A class containing virtual methods must be flagged virtual, and cannot be instantiated (that is, no object of this class can be created). It still defines ty... |
## 6 Private methods
Private methods are methods that do not appear in object interfaces. They can only be invoked from other methods of the same object.
```ocaml
# class restricted_point x_init = object (self) val mutable x = x_init method get_x = x method private move d = x \<- x + d method bump = self#move 1 end;;
`... |
## 6 Private methods
The annotation virtual here is only used to mention a method without providing its definition. Since we didn’t add the private annotation, this makes the method public, keeping the original definition.
An alternative definition is
```ocaml
# class point_again x = object (self : \< move : \_; ..> ) ... |
## 7 Class interfaces
Class interfaces are inferred from class definitions. They may also be defined directly and used to restrict the type of a class. Like class declarations, they also define a new type abbreviation.
```ocaml
# class type restricted_point_type = object method get_x : int method bump : unit end;;
```
... |
## 8 Inheritance
We illustrate inheritance by defining a class of colored points that inherits from the class of points. This class has all instance variables and all methods of class point, plus a new instance variable c and a new method color.
```ocaml
# class colored_point x (c : string) = object inherit point x val... |
## 9 Multiple inheritance
Multiple inheritance is allowed. Only the last definition of a method is kept: the redefinition in a subclass of a method that was visible in the parent class overrides the definition in the parent class. Previous definitions of a method can be reused by binding the related ancestor. Below, su... |
## 9 Multiple inheritance
Note that for clarity’s sake, the method print is explicitly marked as overriding another definition by annotating the method keyword with an exclamation mark !. If the method print were not overriding the print method of printable_point, the compiler would raise an error:
```ocaml
# object me... |
## 10 Parameterized classes
Reference cells can be implemented as objects. The naive definition fails to typecheck:
```ocaml
# class oref x_init = object val mutable x = x_init method get = x method set y = x \<- y end;;
Error: Some type variables are unbound in this type: class oref : 'a -> object val mutable x : 'a m... |
## 10 Parameterized classes
class \['a\] oref : 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
```ocaml
# let r = new oref 1 in r#set 2; (r#get);;
- : int = 2
```
The type parameter in the declaration may actually be constrained in the body of the class definition. In the class type, the ac... |
## 10 Parameterized classes
An alternate definition of circle, using a constraint clause in the class definition, is shown below. The type #point used below in the constraint clause is an abbreviation produced by the definition of class point. This abbreviation unifies with the type of any object belonging to a subclas... |
## 11 Polymorphic methods
While parameterized classes may be polymorphic in their contents, they are not enough to allow polymorphism of method use.
A classical example is defining an iterator.
```ocaml
# List.fold_left;;
- : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc = \<fun\>
# class \['a\] intlist (l : int lis... |
## 11 Polymorphic methods
class intlist : int list -> object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end
```ocaml
# let l = new intlist \[1; 2; 3\];;
val l : intlist = \<obj>
# l#fold (fun x y -> x+y) 0;;
- : int = 6
# l#fold (fun s x -> s ^ Int.to_string x ^ " ") "";;
- : string = "1 2 3 "
``... |
## 11 Polymorphic methods
Note here the (self : int #iterator) idiom, which ensures that this object implements the interface iterator.
Polymorphic methods are called in exactly the same way as normal methods, but you should be aware of some limitations of type inference. Namely, a polymorphic method can only be called... |
## 11 Polymorphic methods
```ocaml
# class type point0 = object method get_x : int end;;
```
class type point0 = object method get_x : int end
```ocaml
# class distance_point x = object inherit point x method distance : 'a. (#point0 as 'a) -> int = fun other -> abs (other#get_x - x) end;;
```
class distance_point : int... |
## 12 Using coercions
Subtyping is never implicit. There are, however, two ways to perform subtyping. The most general construction is fully explicit: both the domain and the codomain of the type coercion must be given.
We have seen that points and colored points have incompatible types. For instance, they cannot be mi... |
## 12 Using coercions
Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types. For instance, the class of colored points could have been defined directly, without inheriting from the class of points; the type of co... |
## 12 Using coercions
```ocaml
# class type c2 = object ('a) method m : 'a end;;
```
class type c2 = object ('a) method m : 'a end
```ocaml
# fun (x:c0) -> (x :> c2);;
- : c0 -> c2 = \<fun\>
```
While class types c1 and c2 are different, both object types c1 and c2 expand to the same object type (same method names and ... |
## 12 Using coercions
Note the difference between these two coercions: in the case of to_c2, the type #c2 = \< m : 'a; .. \> as 'a is polymorphically recursive (according to the explicit recursion in the class type of c2); hence the success of applying this coercion to an object of class c0. On the other hand, in the f... |
## 12 Using coercions
As a consequence, if the coercion is applied to self, as in the following example, the type of self is unified with the closed type c (a closed object type is an object type without ellipsis). This would constrain the type of self be closed and is thus rejected. Indeed, the type of self cannot be ... |
## 12 Using coercions
```ocaml
# let rec lookup_obj obj = function \[\] -> raise Not_found \| obj' :: l -> if (obj :> \< \>) = (obj' :> \< \>) then obj' else lookup_obj obj l ;;
val lookup_obj : \< .. \> -> (\< .. \> as 'a) list -> 'a = \<fun\>
# let lookup_c obj = lookup_obj obj !all_c;;
val lookup_c : \< .. \> -> \<... |
## 12 Using coercions
However, the abbreviation #c' cannot be defined directly in a similar way. It can only be defined by a class or a class-type definition. This is because a #-abbreviation carries an implicit anonymous variable .. that cannot be explicitly named. The closer you get to it is:
```ocaml
# type 'a c'\_c... |
## 13 Functional objects
It is possible to write a version of class point without assignments on the instance variables. The override construct {\< ... \>} returns a copy of “self” (that is, the current object), possibly changing the value of some instance variables.
```ocaml
# class functional_point y = object val x =... |
## 13 Functional objects
While objects of either class will behave the same, objects of their subclasses will be different. In a subclass of bad_functional_point, the method move will keep returning an object of the parent class. On the contrary, in a subclass of functional_point, the method move will return an object ... |
## 14 Cloning objects
Objects can also be cloned, whether they are functional or imperative. The library function Oo.copy makes a shallow copy of an object. That is, it returns a new object that has the same methods and instance variables as its argument. The instance variables are copied but their contents are shared.... |
## 14 Cloning objects
```ocaml
# let q = Oo.copy p;;
val q : point = \<obj>
# p = q, p = p;;
- : bool \* bool = (false, true)
```
Other generic comparisons such as (\<, \<=, ...) can also be used on objects. The relation \< defines an unspecified but strict ordering on objects. The ordering relationship between two ob... |
## 14 Cloning objects
class \['a\] backup_ref : 'a -> object ('b) val mutable copy : 'b option val mutable x : 'a method get : 'a method restore : 'b method save : unit method set : 'a -> unit end
```ocaml
# let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);;
val get : (\< get : 'b; restore : 'a; .. ... |
## 15 Recursive classes
Recursive classes can be used to define objects whose types are mutually recursive.
```ocaml
# class window = object val mutable top_widget = (None : widget option) method top_widget = top_widget end and widget (w : window) = object val window = w method window = window end;;
```
class window : ... |
## 16 Binary methods
A binary method is a method which takes an argument of the same type as self. The class comparable below is a template for classes with a binary method leq of type 'a -> bool where the type variable 'a is bound to the type of self. Therefore, #comparable expands to \< leq : 'a -> bool; .. \> as 'a.... |
## 16 Binary methods
Note that the type money is not a subtype of type comparable, as the self type appears in contravariant position in the type of method leq. Indeed, an object m of class money has a method leq that expects an argument of type money since it accesses its value method. Considering m of type comparable... |
## 16 Binary methods
More examples of binary methods can be found in sections [8.2.1](advexamples.html#ss%3Astring-as-class) and [8.2.3](advexamples.html#ss%3Aset-as-class).
Note the use of override for method times. Writing new money2 (k \*. repr) instead of {\< repr = k \*. repr \>} would not behave well with inher... |
## 17 Friends
The above class money reveals a problem that often occurs with binary methods. In order to interact with other objects of the same class, the representation of money objects must be revealed, using a method such as value. If we remove all binary methods (here plus and leq), the representation can easily b... |
## 17 Friends
Another example of friend functions may be found in section [8.2.3](advexamples.html#ss%3Aset-as-class). These examples occur when a group of objects (here objects of the same class) and functions should see each others internal representation, while their representation should be hidden from the outside... |
# OCaml - Labeled arguments
Source: https://ocaml.org/manual/5.2/lablexamples.html
☰
- [The core language](coreexamples.html)
- [The module system](moduleexamples.html)
- [Objects in OCaml](objectexamples.html)
- [Labeled arguments](lablexamples.html)
- [Polymorphic variants](polyvariant.html)
- [Polymorphi... |
This dataset contains the Ocaml programming language documentation, chunked using semantic parsing for pretraining language models.
Updated: 2025-09-08
from datasets import load_dataset
ds = load_dataset("json", data_files={"train": "train.jsonl"}, split="train")
text field per line