# The OCaml system release 5.1: Documentation and user's manual

Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy, Kc Sivaramakrishnan, Jérôme Vouillon

## ► To cite this version:

Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy, et al.. The OCaml system release 5.1: Documentation and user's manual. [Intern report] Inria. 2023. hal-00930213v10

HAL Id: hal-00930213

https://inria.hal.science/hal-00930213v10

Submitted on 24 Nov 2023

HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d'enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.

<figure><img src="image_1.png" /></figure>

Distributed under a Creative Commons Attribution - ShareAlike 4.0 International License
# The OCaml system release 5.4: Documentation and user's manual

Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy,

Kc Sivaramakrishnan, Jérôme Vouillon

<figure><img src="image_1.png" /></figure>

## To cite this version:

Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy, et al.. The OCaml system release 5.4: Documentation and user's manual. [Intern report] Inria. 2025, pp.1107. hal-00930213v12

HAL Id: hal-00930213

https://inria.hal.science/hal-00930213v12

Submitted on 12 Jan 2026

HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d'enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.

<figure><img src="image_2.png" /></figure>

Distributed under a Creative Commons Attribution - ShareAlike 4.0 International License
# The OCaml system
release 5.1

## Documentation and user's manual

Xavier Leroy,

Damien Doligez, Alain Frisch, Jacques Garrigue,

Didier Rémy, KC Sivaramakrishnan and Jérôme Vouillon

September 14, 2023
The OCaml system
release 5.4

Documentation and user's manual

Xavier Leroy,

Damien Doligez, Alain Frisch, Jacques Garrigue,

Didier Rémy, KC Sivaramakrishnan and Jérôme Vouillon

October 9, 2025
# Contents

<table><tr><td>I</td><td>An introduction to OCaml</td><td>13</td></tr><tr><td>1</td><td>The core language</td><td>15</td></tr><tr><td>1.1</td><td>Basics</td><td>15</td></tr><tr><td>1.2</td><td>Data types</td><td>16</td></tr><tr><td>1.3</td><td>Functions as values</td><td>18</td></tr><tr><td>1.4</td><td>Records and variants</td><td>19</td></tr><tr><td>1.5</td><td>Imperative features</td><td>23</td></tr><tr><td>1.6</td><td>Exceptions</td><td>25</td></tr><tr><td>1.7</td><td>Lazy expressions</td><td>27</td></tr><tr><td>1.8</td><td>Symbolic processing of expressions</td><td>28</td></tr><tr><td>1.9</td><td>Pretty-printing</td><td>30</td></tr><tr><td>1.10</td><td>Printf formats</td><td>31</td></tr><tr><td>1.11</td><td>Standalone OCaml programs</td><td>33</td></tr><tr><td>2</td><td>The module system</td><td>35</td></tr><tr><td>2.1</td><td>Structures</td><td>35</td></tr><tr><td>2.2</td><td>Signatures</td><td>37</td></tr><tr><td>2.3</td><td>Functors</td><td>39</td></tr><tr><td>2.4</td><td>Functors and type abstraction</td><td>40</td></tr><tr><td>2.5</td><td>Modules and separate compilation</td><td>43</td></tr><tr><td>3</td><td>Objects in OCaml</td><td>45</td></tr><tr><td>3.1</td><td>Classes and objects</td><td>45</td></tr><tr><td>3.2</td><td>Immediate objects</td><td>48</td></tr><tr><td>3.3</td><td>Reference to self</td><td>49</td></tr><tr><td>3.4</td><td>Initializers</td><td>50</td></tr><tr><td>3.5</td><td>Virtual methods</td><td>51</td></tr><tr><td>3.6</td><td>Private methods</td><td>52</td></tr><tr><td>3.7</td><td>Class interfaces</td><td>54</td></tr><tr><td>3.8</td><td>Inheritance</td><td>55</td></tr><tr><td>3.9</td><td>Multiple inheritance</td><td>56</td></tr><tr><td>3.10</td><td>Parameterized classes</td><td>57</td></tr><tr><td>3.11</td><td>Polymorphic methods</td><td>60</td></tr><tr><td>3.12</td><td>Using coercions</td><td>63</td></tr><tr><td>3.13</td><td>Functional objects</td><td>67</td></tr></table>
# Contents

<table><tr><td>I</td><td>An introduction to OCaml</td><td>13</td></tr><tr><td>1</td><td>The core language</td><td>15</td></tr><tr><td>1.1</td><td>Basics</td><td>15</td></tr><tr><td>1.2</td><td>Data types</td><td>16</td></tr><tr><td>1.3</td><td>Functions as values</td><td>18</td></tr><tr><td>1.4</td><td>Records and variants</td><td>19</td></tr><tr><td>1.5</td><td>Imperative features</td><td>23</td></tr><tr><td>1.6</td><td>Exceptions</td><td>25</td></tr><tr><td>1.7</td><td>Lazy expressions</td><td>27</td></tr><tr><td>1.8</td><td>Symbolic processing of expressions</td><td>28</td></tr><tr><td>1.9</td><td>Pretty-printing</td><td>30</td></tr><tr><td>1.10</td><td>Printf formats</td><td>31</td></tr><tr><td>1.11</td><td>Standalone OCaml programs</td><td>33</td></tr><tr><td>2</td><td>The module system</td><td>35</td></tr><tr><td>2.1</td><td>Structures</td><td>35</td></tr><tr><td>2.2</td><td>Signatures</td><td>37</td></tr><tr><td>2.3</td><td>Functors</td><td>39</td></tr><tr><td>2.4</td><td>Functors and type abstraction</td><td>40</td></tr><tr><td>2.5</td><td>Modules and separate compilation</td><td>43</td></tr><tr><td>3</td><td>Objects in OCaml</td><td>45</td></tr><tr><td>3.1</td><td>Classes and objects</td><td>45</td></tr><tr><td>3.2</td><td>Immediate objects</td><td>48</td></tr><tr><td>3.3</td><td>Reference to self</td><td>49</td></tr><tr><td>3.4</td><td>Initializers</td><td>50</td></tr><tr><td>3.5</td><td>Virtual methods</td><td>51</td></tr><tr><td>3.6</td><td>Private methods</td><td>52</td></tr><tr><td>3.7</td><td>Class interfaces</td><td>54</td></tr><tr><td>3.8</td><td>Inheritance</td><td>55</td></tr><tr><td>3.9</td><td>Multiple inheritance</td><td>56</td></tr><tr><td>3.10</td><td>Parameterized classes</td><td>57</td></tr><tr><td>3.11</td><td>Polymorphic methods</td><td>60</td></tr><tr><td>3.12</td><td>Using coercions</td><td>63</td></tr><tr><td>3.13</td><td>Functional objects</td><td>67</td></tr></table>
<table>
  <tbody>
    <tr>
      <td>3.14</td>
      <td>Cloning objects</td>
      <td>68</td>
    </tr>
    <tr>
      <td>3.15</td>
      <td>Recursive classes</td>
      <td>71</td>
    </tr>
    <tr>
      <td>3.16</td>
      <td>Binary methods</td>
      <td>71</td>
    </tr>
    <tr>
      <td>3.17</td>
      <td>Friends</td>
      <td>73</td>
    </tr>
    <tr>
      <td><b>4</b></td>
      <td><b>Labeled arguments</b></td>
      <td><b>77</b></td>
    </tr>
    <tr>
      <td>4.1</td>
      <td>Optional arguments</td>
      <td>78</td>
    </tr>
    <tr>
      <td>4.2</td>
      <td>Labels and type inference</td>
      <td>79</td>
    </tr>
    <tr>
      <td>4.3</td>
      <td>Suggestions for labeling</td>
      <td>81</td>
    </tr>
    <tr>
      <td><b>5</b></td>
      <td><b>Polymorphic variants</b></td>
      <td><b>83</b></td>
    </tr>
    <tr>
      <td>5.1</td>
      <td>Basic use</td>
      <td>83</td>
    </tr>
    <tr>
      <td>5.2</td>
      <td>Advanced use</td>
      <td>84</td>
    </tr>
    <tr>
      <td>5.3</td>
      <td>Weaknesses of polymorphic variants</td>
      <td>86</td>
    </tr>
    <tr>
      <td><b>6</b></td>
      <td><b>Polymorphism and its limitations</b></td>
      <td><b>87</b></td>
    </tr>
    <tr>
      <td>6.1</td>
      <td>Weak polymorphism and mutation</td>
      <td>87</td>
    </tr>
    <tr>
      <td>6.2</td>
      <td>Polymorphic recursion</td>
      <td>92</td>
    </tr>
    <tr>
      <td>6.3</td>
      <td>Higher-rank polymorphic functions</td>
      <td>95</td>
    </tr>
    <tr>
      <td><b>7</b></td>
      <td><b>Generalized algebraic datatypes</b></td>
      <td><b>97</b></td>
    </tr>
    <tr>
      <td>7.1</td>
      <td>Recursive functions</td>
      <td>97</td>
    </tr>
    <tr>
      <td>7.2</td>
      <td>Type inference</td>
      <td>98</td>
    </tr>
    <tr>
      <td>7.3</td>
      <td>Refutation cases</td>
      <td>99</td>
    </tr>
    <tr>
      <td>7.4</td>
      <td>Advanced examples</td>
      <td>99</td>
    </tr>
    <tr>
      <td>7.5</td>
      <td>Existential type names in error messages</td>
      <td>101</td>
    </tr>
    <tr>
      <td>7.6</td>
      <td>Explicit naming of existentials</td>
      <td>102</td>
    </tr>
    <tr>
      <td>7.7</td>
      <td>Equations on non-local abstract types</td>
      <td>102</td>
    </tr>
    <tr>
      <td><b>8</b></td>
      <td><b>Advanced examples with classes and modules</b></td>
      <td><b>103</b></td>
    </tr>
    <tr>
      <td>8.1</td>
      <td>Extended example: bank accounts</td>
      <td>103</td>
    </tr>
    <tr>
      <td>8.2</td>
      <td>Simple modules as classes</td>
      <td>109</td>
    </tr>
    <tr>
      <td>8.3</td>
      <td>The subject/observer pattern</td>
      <td>115</td>
    </tr>
    <tr>
      <td><b>9</b></td>
      <td><b>Parallel programming</b></td>
      <td><b>119</b></td>
    </tr>
    <tr>
      <td>9.1</td>
      <td>Domains</td>
      <td>119</td>
    </tr>
    <tr>
      <td>9.2</td>
      <td>Domainslib: A library for nested-parallel programming</td>
      <td>121</td>
    </tr>
    <tr>
      <td>9.3</td>
      <td>Parallel garbage collection</td>
      <td>126</td>
    </tr>
    <tr>
      <td>9.4</td>
      <td>Memory model: The easy bits</td>
      <td>127</td>
    </tr>
    <tr>
      <td>9.5</td>
      <td>Blocking synchronisation</td>
      <td>127</td>
    </tr>
    <tr>
      <td>9.6</td>
      <td>Interaction with C bindings</td>
      <td>130</td>
    </tr>
    <tr>
      <td>9.7</td>
      <td>Atomics</td>
      <td>130</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td>3.14</td>
      <td>Cloning objects</td>
      <td>68</td>
    </tr>
    <tr>
      <td>3.15</td>
      <td>Recursive classes</td>
      <td>71</td>
    </tr>
    <tr>
      <td>3.16</td>
      <td>Binary methods</td>
      <td>71</td>
    </tr>
    <tr>
      <td>3.17</td>
      <td>Friends</td>
      <td>73</td>
    </tr>
    <tr>
      <td><b>4</b></td>
      <td><b>Labeled arguments</b></td>
      <td><b>77</b></td>
    </tr>
    <tr>
      <td>4.1</td>
      <td>Optional arguments</td>
      <td>78</td>
    </tr>
    <tr>
      <td>4.2</td>
      <td>Labels and type inference</td>
      <td>79</td>
    </tr>
    <tr>
      <td>4.3</td>
      <td>Suggestions for labeling</td>
      <td>81</td>
    </tr>
    <tr>
      <td><b>5</b></td>
      <td><b>Polymorphic variants</b></td>
      <td><b>83</b></td>
    </tr>
    <tr>
      <td>5.1</td>
      <td>Basic use</td>
      <td>83</td>
    </tr>
    <tr>
      <td>5.2</td>
      <td>Advanced use</td>
      <td>84</td>
    </tr>
    <tr>
      <td>5.3</td>
      <td>Weaknesses of polymorphic variants</td>
      <td>86</td>
    </tr>
    <tr>
      <td><b>6</b></td>
      <td><b>Polymorphism and its limitations</b></td>
      <td><b>87</b></td>
    </tr>
    <tr>
      <td>6.1</td>
      <td>Weak polymorphism and mutation</td>
      <td>87</td>
    </tr>
    <tr>
      <td>6.2</td>
      <td>Polymorphic recursion</td>
      <td>92</td>
    </tr>
    <tr>
      <td>6.3</td>
      <td>Higher-rank polymorphic functions</td>
      <td>95</td>
    </tr>
    <tr>
      <td><b>7</b></td>
      <td><b>Generalized algebraic datatypes</b></td>
      <td><b>97</b></td>
    </tr>
    <tr>
      <td>7.1</td>
      <td>Recursive functions</td>
      <td>97</td>
    </tr>
    <tr>
      <td>7.2</td>
      <td>Type inference</td>
      <td>98</td>
    </tr>
    <tr>
      <td>7.3</td>
      <td>Refutation cases</td>
      <td>99</td>
    </tr>
    <tr>
      <td>7.4</td>
      <td>Advanced examples</td>
      <td>99</td>
    </tr>
    <tr>
      <td>7.5</td>
      <td>Existential type names in error messages</td>
      <td>101</td>
    </tr>
    <tr>
      <td>7.6</td>
      <td>Explicit naming of existentials</td>
      <td>101</td>
    </tr>
    <tr>
      <td>7.7</td>
      <td>Equations on non-local abstract types</td>
      <td>102</td>
    </tr>
    <tr>
      <td><b>8</b></td>
      <td><b>Advanced examples with classes and modules</b></td>
      <td><b>103</b></td>
    </tr>
    <tr>
      <td>8.1</td>
      <td>Extended example: bank accounts</td>
      <td>103</td>
    </tr>
    <tr>
      <td>8.2</td>
      <td>Simple modules as classes</td>
      <td>109</td>
    </tr>
    <tr>
      <td>8.3</td>
      <td>The subject/observer pattern</td>
      <td>115</td>
    </tr>
    <tr>
      <td><b>9</b></td>
      <td><b>Parallel programming</b></td>
      <td><b>119</b></td>
    </tr>
    <tr>
      <td>9.1</td>
      <td>Domains</td>
      <td>119</td>
    </tr>
    <tr>
      <td>9.2</td>
      <td>Domainslib: A library for nested-parallel programming</td>
      <td>121</td>
    </tr>
    <tr>
      <td>9.3</td>
      <td>Parallel garbage collection</td>
      <td>126</td>
    </tr>
    <tr>
      <td>9.4</td>
      <td>Memory model: The easy bits</td>
      <td>127</td>
    </tr>
    <tr>
      <td>9.5</td>
      <td>Blocking synchronisation</td>
      <td>127</td>
    </tr>
    <tr>
      <td>9.6</td>
      <td>Interaction with C bindings</td>
      <td>130</td>
    </tr>
    <tr>
      <td>9.7</td>
      <td>Atomics</td>
      <td>130</td>
    </tr>
  </tbody>
</table>
<table><tr><td><b>10 Memory model: The hard bits</b></td><td><b>133</b></td></tr><tr><td>10.1 Why weakly consistent memory?</td><td>133</td></tr><tr><td>10.2 Data race freedom implies sequential consistency</td><td>136</td></tr><tr><td>10.3 Reasoning with DRF-SC</td><td>137</td></tr><tr><td>10.4 Local data race freedom</td><td>139</td></tr><tr><td>10.5 An operational view of the memory model</td><td>141</td></tr><tr><td>10.6 Non-compliant operations</td><td>145</td></tr></table>

## II The OCaml language 147

<table><tr><td><b>11 The OCaml language</b></td><td><b>149</b></td></tr><tr><td>11.1 Lexical conventions</td><td>149</td></tr><tr><td>11.2 Values</td><td>155</td></tr><tr><td>11.3 Names</td><td>157</td></tr><tr><td>11.4 Type expressions</td><td>160</td></tr><tr><td>11.5 Constants</td><td>163</td></tr><tr><td>11.6 Patterns</td><td>164</td></tr><tr><td>11.7 Expressions</td><td>171</td></tr><tr><td>11.8 Type and exception definitions</td><td>193</td></tr><tr><td>11.9 Classes</td><td>196</td></tr><tr><td>11.10 Module types (module specifications)</td><td>203</td></tr><tr><td>11.11 Module expressions (module implementations)</td><td>207</td></tr><tr><td>11.12 Compilation units</td><td>211</td></tr></table>

<table><tr><td><b>12 Language extensions</b></td><td><b>213</b></td></tr><tr><td>12.1 Recursive definitions of values</td><td>213</td></tr><tr><td>12.2 Recursive modules</td><td>214</td></tr><tr><td>12.3 Private types</td><td>216</td></tr><tr><td>12.4 Locally abstract types</td><td>218</td></tr><tr><td>12.5 First-class modules</td><td>219</td></tr><tr><td>12.6 Recovering the type of a module</td><td>222</td></tr><tr><td>12.7 Substituting inside a signature</td><td>222</td></tr><tr><td>12.8 Type-level module aliases</td><td>225</td></tr><tr><td>12.9 Overriding in open statements</td><td>227</td></tr><tr><td>12.10 Generalized algebraic datatypes</td><td>227</td></tr><tr><td>12.11 Syntax for Bigarray access</td><td>228</td></tr><tr><td>12.12 Attributes</td><td>228</td></tr><tr><td>12.13 Extension nodes</td><td>235</td></tr><tr><td>12.14 Extensible variant types</td><td>237</td></tr><tr><td>12.15 Generative functors</td><td>239</td></tr><tr><td>12.16 Extension-only syntax</td><td>239</td></tr><tr><td>12.17 Inline records</td><td>241</td></tr><tr><td>12.18 Documentation comments</td><td>241</td></tr><tr><td>12.19 Extended indexing operators</td><td>244</td></tr></table>
<table><tr><td><b>10 Memory model: The hard bits</b></td><td><b>135</b></td></tr><tr><td>10.1 Why weakly consistent memory?</td><td>135</td></tr><tr><td>10.2 Data race freedom implies sequential consistency</td><td>138</td></tr><tr><td>10.3 Reasoning with DRF-SC</td><td>139</td></tr><tr><td>10.4 Local data race freedom</td><td>141</td></tr><tr><td>10.5 An operational view of the memory model</td><td>143</td></tr><tr><td>10.6 Non-compliant operations</td><td>147</td></tr></table>

## II The OCaml language 149

<table><tr><td><b>11 The OCaml language</b></td><td><b>151</b></td></tr><tr><td>11.1 Lexical conventions</td><td>151</td></tr><tr><td>11.2 Values</td><td>158</td></tr><tr><td>11.3 Names</td><td>159</td></tr><tr><td>11.4 Type expressions</td><td>162</td></tr><tr><td>11.5 Constants</td><td>165</td></tr><tr><td>11.6 Patterns</td><td>166</td></tr><tr><td>11.7 Expressions</td><td>173</td></tr><tr><td>11.8 Type and exception definitions</td><td>195</td></tr><tr><td>11.9 Classes</td><td>198</td></tr><tr><td>11.10 Module types (module specifications)</td><td>205</td></tr><tr><td>11.11 Module expressions (module implementations)</td><td>210</td></tr><tr><td>11.12 Compilation units</td><td>213</td></tr></table>

<table><tr><td><b>12 Language extensions</b></td><td><b>215</b></td></tr><tr><td>12.1 Recursive definitions of values</td><td>215</td></tr><tr><td>12.2 Recursive modules</td><td>216</td></tr><tr><td>12.3 Private types</td><td>218</td></tr><tr><td>12.4 Locally abstract types</td><td>220</td></tr><tr><td>12.5 First-class modules</td><td>221</td></tr><tr><td>12.6 Recovering the type of a module</td><td>224</td></tr><tr><td>12.7 Substituting inside a signature</td><td>224</td></tr><tr><td>12.8 Type-level module aliases</td><td>228</td></tr><tr><td>12.9 Overriding in open statements</td><td>229</td></tr><tr><td>12.10 Generalized algebraic datatypes</td><td>230</td></tr><tr><td>12.11 Syntax for Bigarray access</td><td>231</td></tr><tr><td>12.12 Attributes</td><td>231</td></tr><tr><td>12.13 Extension nodes</td><td>238</td></tr><tr><td>12.14 Extensible variant types</td><td>240</td></tr><tr><td>12.15 Generative functors</td><td>243</td></tr><tr><td>12.16 Extension-only syntax</td><td>243</td></tr><tr><td>12.17 Inline records</td><td>244</td></tr><tr><td>12.18 Documentation comments</td><td>245</td></tr><tr><td>12.19 Extended indexing operators</td><td>248</td></tr></table>
<table>
  <tbody>
    <tr>
      <td>12.20 Empty variant types</td>
      <td>246</td>
    </tr>
    <tr>
      <td>12.21 Alerts</td>
      <td>246</td>
    </tr>
    <tr>
      <td>12.22 Generalized open statements</td>
      <td>248</td>
    </tr>
    <tr>
      <td>12.23 Binding operators</td>
      <td>250</td>
    </tr>
    <tr>
      <td>12.24 Effect handlers</td>
      <td>254</td>
    </tr>
    <tr>
      <td><strong>III The OCaml tools</strong></td>
      <td><strong>269</strong></td>
    </tr>
    <tr>
      <td><strong>13 Batch compilation (ocamlc)</strong></td>
      <td><strong>271</strong></td>
    </tr>
    <tr>
      <td>13.1 Overview of the compiler</td>
      <td>271</td>
    </tr>
    <tr>
      <td>13.2 Options</td>
      <td>272</td>
    </tr>
    <tr>
      <td>13.3 Modules and the file system</td>
      <td>287</td>
    </tr>
    <tr>
      <td>13.4 Common errors</td>
      <td>287</td>
    </tr>
    <tr>
      <td>13.5 Warning reference</td>
      <td>290</td>
    </tr>
    <tr>
      <td><strong>14 The toplevel system or REPL (ocaml)</strong></td>
      <td><strong>295</strong></td>
    </tr>
    <tr>
      <td>14.1 Options</td>
      <td>296</td>
    </tr>
    <tr>
      <td>14.2 T LEVEL directives</td>
      <td>305</td>
    </tr>
    <tr>
      <td>14.3 The toplevel and the module system</td>
      <td>308</td>
    </tr>
    <tr>
      <td>14.4 Common errors</td>
      <td>308</td>
    </tr>
    <tr>
      <td>14.5 Building custom toplevel systems: ocamlmktop</td>
      <td>309</td>
    </tr>
    <tr>
      <td>14.6 The native toplevel: ocamlnat (experimental)</td>
      <td>310</td>
    </tr>
    <tr>
      <td><strong>15 The runtime system (ocamlrun)</strong></td>
      <td><strong>311</strong></td>
    </tr>
    <tr>
      <td>15.1 Overview</td>
      <td>311</td>
    </tr>
    <tr>
      <td>15.2 Options</td>
      <td>312</td>
    </tr>
    <tr>
      <td>15.3 Dynamic loading of shared libraries</td>
      <td>315</td>
    </tr>
    <tr>
      <td>15.4 Common errors</td>
      <td>315</td>
    </tr>
    <tr>
      <td><strong>16 Native-code compilation (ocamlopt)</strong></td>
      <td><strong>317</strong></td>
    </tr>
    <tr>
      <td>16.1 Overview of the compiler</td>
      <td>317</td>
    </tr>
    <tr>
      <td>16.2 Options</td>
      <td>318</td>
    </tr>
    <tr>
      <td>16.3 Common errors</td>
      <td>333</td>
    </tr>
    <tr>
      <td>16.4 Running executables produced by ocamlopt</td>
      <td>333</td>
    </tr>
    <tr>
      <td>16.5 Compatibility with the bytecode compiler</td>
      <td>334</td>
    </tr>
    <tr>
      <td><strong>17 Parser and parser generators (ocamllex, ocamlyacc)</strong></td>
      <td><strong>335</strong></td>
    </tr>
    <tr>
      <td>17.1 Overview of ocamllex</td>
      <td>335</td>
    </tr>
    <tr>
      <td>17.2 Syntax of lexer definitions</td>
      <td>336</td>
    </tr>
    <tr>
      <td>17.3 Overview of ocamlyacc</td>
      <td>341</td>
    </tr>
    <tr>
      <td>17.4 Syntax of grammar definitions</td>
      <td>341</td>
    </tr>
    <tr>
      <td>17.5 Options</td>
      <td>344</td>
    </tr>
    <tr>
      <td>17.6 A complete example</td>
      <td>345</td>
    </tr>
    <tr>
      <td>17.7 Common errors</td>
      <td>346</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td><strong>18 Dependency generator (ocamldep)</strong></td>
      <td><strong>349</strong></td>
    </tr>
    <tr>
      <td>18.1 Options</td>
      <td>349</td>
    </tr>
    <tr>
      <td>18.2 A typical Makefile</td>
      <td>351</td>
    </tr>
    <tr>
      <td><strong>19 The documentation generator (ocamldoc)</strong></td>
      <td><strong>355</strong></td>
    </tr>
    <tr>
      <td>19.1 Usage</td>
      <td>355</td>
    </tr>
    <tr>
      <td>19.2 Syntax of documentation comments</td>
      <td>362</td>
    </tr>
    <tr>
      <td>19.3 Custom generators</td>
      <td>372</td>
    </tr>
    <tr>
      <td>19.4 Adding command line options</td>
      <td>375</td>
    </tr>
    <tr>
      <td><strong>20 The debugger (ocamldebug)</strong></td>
      <td><strong>377</strong></td>
    </tr>
    <tr>
      <td>20.1 Compiling for debugging</td>
      <td>377</td>
    </tr>
    <tr>
      <td>20.2 Invocation</td>
      <td>377</td>
    </tr>
    <tr>
      <td>20.3 Commands</td>
      <td>378</td>
    </tr>
    <tr>
      <td>20.4 Executing a program</td>
      <td>379</td>
    </tr>
    <tr>
      <td>20.5 Breakpoints</td>
      <td>382</td>
    </tr>
    <tr>
      <td>20.6 The call stack</td>
      <td>383</td>
    </tr>
    <tr>
      <td>20.7 Examining variable values</td>
      <td>383</td>
    </tr>
    <tr>
      <td>20.8 Controlling the debugger</td>
      <td>384</td>
    </tr>
    <tr>
      <td>20.9 Miscellaneous commands</td>
      <td>388</td>
    </tr>
    <tr>
      <td>20.10 Running the debugger under Emacs</td>
      <td>388</td>
    </tr>
    <tr>
      <td><strong>21 Profiling (ocamlprof)</strong></td>
      <td><strong>391</strong></td>
    </tr>
    <tr>
      <td>21.1 Compiling for profiling</td>
      <td>391</td>
    </tr>
    <tr>
      <td>21.2 Profiling an execution</td>
      <td>392</td>
    </tr>
    <tr>
      <td>21.3 Printing profiling information</td>
      <td>392</td>
    </tr>
    <tr>
      <td>21.4 Time profiling</td>
      <td>393</td>
    </tr>
    <tr>
      <td><strong>22 Interfacing C with OCaml</strong></td>
      <td><strong>395</strong></td>
    </tr>
    <tr>
      <td>22.1 Overview and compilation information</td>
      <td>395</td>
    </tr>
    <tr>
      <td>22.2 The value type</td>
      <td>401</td>
    </tr>
    <tr>
      <td>22.3 Representation of OCaml data types</td>
      <td>403</td>
    </tr>
    <tr>
      <td>22.4 Operations on values</td>
      <td>406</td>
    </tr>
    <tr>
      <td>22.5 Living in harmony with the garbage collector</td>
      <td>410</td>
    </tr>
    <tr>
      <td>22.6 A complete example</td>
      <td>416</td>
    </tr>
    <tr>
      <td>22.7 Advanced topic: callbacks from C to OCaml</td>
      <td>419</td>
    </tr>
    <tr>
      <td>22.8 Advanced example with callbacks</td>
      <td>425</td>
    </tr>
    <tr>
      <td>22.9 Advanced topic: custom blocks</td>
      <td>427</td>
    </tr>
    <tr>
      <td>22.10 Advanced topic: Bigarrays and the OCaml-C interface</td>
      <td>431</td>
    </tr>
    <tr>
      <td>22.11 Advanced topic: cheaper C call</td>
      <td>433</td>
    </tr>
    <tr>
      <td>22.12 Advanced topic: multithreading</td>
      <td>436</td>
    </tr>
    <tr>
      <td>22.13 Advanced topic: interfacing with Windows Unicode APIs</td>
      <td>438</td>
    </tr>
    <tr>
      <td>22.14 Building mixed C/OCaml libraries: ocamlmklib</td>
      <td>440</td>
    </tr>
    <tr>
      <td>22.15 Cautionary words: the internal runtime API</td>
      <td>442</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td>17.7 Common errors</td>
      <td>358</td>
    </tr>
    <tr>
      <td><strong>18 Dependency generator (ocamldep)</strong></td>
      <td><strong>361</strong></td>
    </tr>
    <tr>
      <td>18.1 Options</td>
      <td>361</td>
    </tr>
    <tr>
      <td>18.2 A typical Makefile</td>
      <td>364</td>
    </tr>
    <tr>
      <td><strong>19 The documentation generator (ocamldoc)</strong></td>
      <td><strong>367</strong></td>
    </tr>
    <tr>
      <td>19.1 Usage</td>
      <td>367</td>
    </tr>
    <tr>
      <td>19.2 Syntax of documentation comments</td>
      <td>374</td>
    </tr>
    <tr>
      <td>19.3 Custom generators</td>
      <td>384</td>
    </tr>
    <tr>
      <td>19.4 Adding command line options</td>
      <td>387</td>
    </tr>
    <tr>
      <td><strong>20 The debugger (ocamldebug)</strong></td>
      <td><strong>389</strong></td>
    </tr>
    <tr>
      <td>20.1 Compiling for debugging</td>
      <td>389</td>
    </tr>
    <tr>
      <td>20.2 Invocation</td>
      <td>389</td>
    </tr>
    <tr>
      <td>20.3 Commands</td>
      <td>390</td>
    </tr>
    <tr>
      <td>20.4 Executing a program</td>
      <td>391</td>
    </tr>
    <tr>
      <td>20.5 Breakpoints</td>
      <td>394</td>
    </tr>
    <tr>
      <td>20.6 The call stack</td>
      <td>395</td>
    </tr>
    <tr>
      <td>20.7 Examining variable values</td>
      <td>395</td>
    </tr>
    <tr>
      <td>20.8 Controlling the debugger</td>
      <td>396</td>
    </tr>
    <tr>
      <td>20.9 Miscellaneous commands</td>
      <td>400</td>
    </tr>
    <tr>
      <td>20.10 Running the debugger under Emacs</td>
      <td>400</td>
    </tr>
    <tr>
      <td><strong>21 Profiling (ocamlprof, perf)</strong></td>
      <td><strong>403</strong></td>
    </tr>
    <tr>
      <td>21.1 Profiling execution counts with ocamlprof</td>
      <td>403</td>
    </tr>
    <tr>
      <td>21.2 Time profiling with Linux perf</td>
      <td>405</td>
    </tr>
    <tr>
      <td>21.3 Time profiling with macOS Instruments</td>
      <td>410</td>
    </tr>
    <tr>
      <td>21.4 Glossary</td>
      <td>411</td>
    </tr>
    <tr>
      <td><strong>22 Interfacing C with OCaml</strong></td>
      <td><strong>413</strong></td>
    </tr>
    <tr>
      <td>22.1 Overview and compilation information</td>
      <td>413</td>
    </tr>
    <tr>
      <td>22.2 The value type</td>
      <td>419</td>
    </tr>
    <tr>
      <td>22.3 Representation of OCaml data types</td>
      <td>421</td>
    </tr>
    <tr>
      <td>22.4 Operations on values</td>
      <td>424</td>
    </tr>
    <tr>
      <td>22.5 Living in harmony with the garbage collector</td>
      <td>428</td>
    </tr>
    <tr>
      <td>22.6 A complete example</td>
      <td>434</td>
    </tr>
    <tr>
      <td>22.7 Advanced topic: callbacks from C to OCaml</td>
      <td>437</td>
    </tr>
    <tr>
      <td>22.8 Advanced example with callbacks</td>
      <td>445</td>
    </tr>
    <tr>
      <td>22.9 Advanced topic: custom blocks</td>
      <td>447</td>
    </tr>
    <tr>
      <td>22.10 Advanced topic: Bigarrays and the OCaml-C interface</td>
      <td>452</td>
    </tr>
    <tr>
      <td>22.11 Advanced topic: cheaper C call</td>
      <td>454</td>
    </tr>
    <tr>
      <td>22.12 Advanced topic: multithreading</td>
      <td>456</td>
    </tr>
    <tr>
      <td>22.13 Advanced topic: interfacing with Windows Unicode APIs</td>
      <td>459</td>
    </tr>
    <tr>
      <td>22.14 Building mixed C/OCaml libraries: ocamlmklib</td>
      <td>461</td>
    </tr>
    <tr>
      <td>22.15 Cautionary words: the internal runtime API</td>
      <td>463</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td><strong>23 Optimisation with Lambda</strong></td>
      <td><strong>445</strong></td>
    </tr>
    <tr>
      <td>23.1 Overview</td>
      <td>445</td>
    </tr>
    <tr>
      <td>23.2 Command-line flags</td>
      <td>445</td>
    </tr>
    <tr>
      <td>23.3 Inlining</td>
      <td>448</td>
    </tr>
    <tr>
      <td>23.4 Specialisation</td>
      <td>453</td>
    </tr>
    <tr>
      <td>23.5 Default settings of parameters</td>
      <td>456</td>
    </tr>
    <tr>
      <td>23.6 Manual control of inlining and specialisation</td>
      <td>457</td>
    </tr>
    <tr>
      <td>23.7 Simplification</td>
      <td>458</td>
    </tr>
    <tr>
      <td>23.8 Other code motion transformations</td>
      <td>459</td>
    </tr>
    <tr>
      <td>23.9 Unboxing transformations</td>
      <td>460</td>
    </tr>
    <tr>
      <td>23.10 Removal of unused code and values</td>
      <td>464</td>
    </tr>
    <tr>
      <td>23.11 Other code transformations</td>
      <td>464</td>
    </tr>
    <tr>
      <td>23.12 Treatment of effects</td>
      <td>465</td>
    </tr>
    <tr>
      <td>23.13 Compilation of statically-allocated modules</td>
      <td>466</td>
    </tr>
    <tr>
      <td>23.14 Inhibition of optimisation</td>
      <td>466</td>
    </tr>
    <tr>
      <td>23.15 Use of unsafe operations</td>
      <td>466</td>
    </tr>
    <tr>
      <td>23.16 Glossary</td>
      <td>467</td>
    </tr>
    <tr>
      <td><strong>24 Fuzzing with afl-fuzz</strong></td>
      <td><strong>469</strong></td>
    </tr>
    <tr>
      <td>24.1 Overview</td>
      <td>469</td>
    </tr>
    <tr>
      <td>24.2 Generating instrumentation</td>
      <td>469</td>
    </tr>
    <tr>
      <td>24.3 Example</td>
      <td>469</td>
    </tr>
    <tr>
      <td><strong>25 Runtime tracing with runtime events</strong></td>
      <td><strong>471</strong></td>
    </tr>
    <tr>
      <td>25.1 Overview</td>
      <td>471</td>
    </tr>
    <tr>
      <td>25.2 Architecture</td>
      <td>472</td>
    </tr>
    <tr>
      <td>25.3 Usage</td>
      <td>473</td>
    </tr>
    <tr>
      <td><strong>26 The "Tail Modulo Constructor" program transformation</strong></td>
      <td><strong>477</strong></td>
    </tr>
    <tr>
      <td>26.1 Disambiguation</td>
      <td>480</td>
    </tr>
    <tr>
      <td>26.2 Danger: getting out of tail-mod-cons</td>
      <td>481</td>
    </tr>
    <tr>
      <td>26.3 Details on the transformation</td>
      <td>484</td>
    </tr>
    <tr>
      <td>26.4 Current limitations</td>
      <td>486</td>
    </tr>
    <tr>
      <td><strong>IV The OCaml library</strong></td>
      <td><strong>489</strong></td>
    </tr>
    <tr>
      <td><strong>27 The core library</strong></td>
      <td><strong>491</strong></td>
    </tr>
    <tr>
      <td>27.1 Built-in types and predefined exceptions</td>
      <td>491</td>
    </tr>
    <tr>
      <td>27.2 Module Stdlib: The OCaml Standard library.</td>
      <td>494</td>
    </tr>
    <tr>
      <td><strong>28 The standard library</strong></td>
      <td><strong>523</strong></td>
    </tr>
    <tr>
      <td>28.1 Module Arg: Parsing of command line arguments.</td>
      <td>525</td>
    </tr>
    <tr>
      <td>28.2 Module Array: Array operations.</td>
      <td>530</td>
    </tr>
    <tr>
      <td>28.3 Module ArrayLabels: Array operations.</td>
      <td>537</td>
    </tr>
    <tr>
      <td>28.4 Module Atomic: Atomic references.</td>
      <td>545</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td>23 Optimisation with Lambda</td>
      <td>465</td>
    </tr>
    <tr>
      <td>23.1 Overview</td>
      <td>465</td>
    </tr>
    <tr>
      <td>23.2 Command-line flags</td>
      <td>465</td>
    </tr>
    <tr>
      <td>23.3 Inlining</td>
      <td>468</td>
    </tr>
    <tr>
      <td>23.4 Specialisation</td>
      <td>473</td>
    </tr>
    <tr>
      <td>23.5 Default settings of parameters</td>
      <td>476</td>
    </tr>
    <tr>
      <td>23.6 Manual control of inlining and specialisation</td>
      <td>477</td>
    </tr>
    <tr>
      <td>23.7 Simplification</td>
      <td>478</td>
    </tr>
    <tr>
      <td>23.8 Other code motion transformations</td>
      <td>479</td>
    </tr>
    <tr>
      <td>23.9 Unboxing transformations</td>
      <td>480</td>
    </tr>
    <tr>
      <td>23.10 Removal of unused code and values</td>
      <td>484</td>
    </tr>
    <tr>
      <td>23.11 Other code transformations</td>
      <td>484</td>
    </tr>
    <tr>
      <td>23.12 Treatment of effects</td>
      <td>485</td>
    </tr>
    <tr>
      <td>23.13 Compilation of statically-allocated modules</td>
      <td>486</td>
    </tr>
    <tr>
      <td>23.14 Inhibition of optimisation</td>
      <td>486</td>
    </tr>
    <tr>
      <td>23.15 Use of unsafe operations</td>
      <td>486</td>
    </tr>
    <tr>
      <td>23.16 Glossary</td>
      <td>487</td>
    </tr>
    <tr>
      <td>24 Fuzzing with afl-fuzz</td>
      <td>489</td>
    </tr>
    <tr>
      <td>24.1 Overview</td>
      <td>489</td>
    </tr>
    <tr>
      <td>24.2 Generating instrumentation</td>
      <td>489</td>
    </tr>
    <tr>
      <td>24.3 Example</td>
      <td>489</td>
    </tr>
    <tr>
      <td>25 Runtime tracing with runtime events</td>
      <td>491</td>
    </tr>
    <tr>
      <td>25.1 Overview</td>
      <td>491</td>
    </tr>
    <tr>
      <td>25.2 Architecture</td>
      <td>492</td>
    </tr>
    <tr>
      <td>25.3 Usage</td>
      <td>493</td>
    </tr>
    <tr>
      <td>25.4 Custom events</td>
      <td>497</td>
    </tr>
    <tr>
      <td>26 The "Tail Modulo Constructor" program transformation</td>
      <td>501</td>
    </tr>
    <tr>
      <td>26.1 Disambiguation</td>
      <td>504</td>
    </tr>
    <tr>
      <td>26.2 Danger: getting out of tail-mod-cons</td>
      <td>505</td>
    </tr>
    <tr>
      <td>26.3 Details on the transformation</td>
      <td>508</td>
    </tr>
    <tr>
      <td>26.4 Current limitations</td>
      <td>510</td>
    </tr>
    <tr>
      <td>27 Runtime detection of data races with ThreadSanitizer</td>
      <td>513</td>
    </tr>
    <tr>
      <td>27.1 Overview and usage</td>
      <td>513</td>
    </tr>
    <tr>
      <td>27.2 Performance implications</td>
      <td>515</td>
    </tr>
    <tr>
      <td>27.3 False negatives and false positives</td>
      <td>515</td>
    </tr>
    <tr>
      <td>27.4 Runtime options</td>
      <td>516</td>
    </tr>
    <tr>
      <td>27.5 Guidelines for linking</td>
      <td>516</td>
    </tr>
    <tr>
      <td>27.6 Changes in the delivery of signals</td>
      <td>517</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td>28.5</td>
      <td>Module Bigarray</td>
      <td>Large, multi-dimensional, numerical arrays.</td>
      <td>547</td>
    </tr>
    <tr>
      <td>28.6</td>
      <td>Module Bool</td>
      <td>Boolean values.</td>
      <td>569</td>
    </tr>
    <tr>
      <td>28.7</td>
      <td>Module Buffer</td>
      <td>Extensible buffers.</td>
      <td>571</td>
    </tr>
    <tr>
      <td>28.8</td>
      <td>Module Bytes</td>
      <td>Byte sequence operations.</td>
      <td>576</td>
    </tr>
    <tr>
      <td>28.9</td>
      <td>Module BytesLabels</td>
      <td>Byte sequence operations.</td>
      <td>590</td>
    </tr>
    <tr>
      <td>28.10</td>
      <td>Module Callback</td>
      <td>Registering OCaml values with the C runtime.</td>
      <td>603</td>
    </tr>
    <tr>
      <td>28.11</td>
      <td>Module Char</td>
      <td>Character operations.</td>
      <td>604</td>
    </tr>
    <tr>
      <td>28.12</td>
      <td>Module Complex</td>
      <td>Complex numbers.</td>
      <td>605</td>
    </tr>
    <tr>
      <td>28.13</td>
      <td>Module Condition</td>
      <td>Condition variables.</td>
      <td>607</td>
    </tr>
    <tr>
      <td>28.14</td>
      <td>Module Domain</td>
      <td></td>
      <td>609</td>
    </tr>
    <tr>
      <td>28.15</td>
      <td>Module Digest</td>
      <td>MD5 message digest.</td>
      <td>612</td>
    </tr>
    <tr>
      <td>28.16</td>
      <td>Module Effect</td>
      <td></td>
      <td>613</td>
    </tr>
    <tr>
      <td>28.17</td>
      <td>Module Either</td>
      <td>Either type.</td>
      <td>616</td>
    </tr>
    <tr>
      <td>28.18</td>
      <td>Module Ephemeron</td>
      <td>Ephemeron and weak hash tables.</td>
      <td>617</td>
    </tr>
    <tr>
      <td>28.19</td>
      <td>Module Filename</td>
      <td>Operations on file names.</td>
      <td>624</td>
    </tr>
    <tr>
      <td>28.20</td>
      <td>Module Float</td>
      <td>Floating-point arithmetic.</td>
      <td>628</td>
    </tr>
    <tr>
      <td>28.21</td>
      <td>Module Format</td>
      <td>Pretty-printing.</td>
      <td>649</td>
    </tr>
    <tr>
      <td>28.22</td>
      <td>Module Fun</td>
      <td>Function manipulation.</td>
      <td>676</td>
    </tr>
    <tr>
      <td>28.23</td>
      <td>Module Gc</td>
      <td>Memory management control and statistics; finalised values.</td>
      <td>677</td>
    </tr>
    <tr>
      <td>28.24</td>
      <td>Module Hashtbl</td>
      <td>Hash tables and hash functions.</td>
      <td>686</td>
    </tr>
    <tr>
      <td>28.25</td>
      <td>Module In_channel</td>
      <td>Input channels.</td>
      <td>698</td>
    </tr>
    <tr>
      <td>28.26</td>
      <td>Module Int</td>
      <td>Integer values.</td>
      <td>702</td>
    </tr>
    <tr>
      <td>28.27</td>
      <td>Module Int32</td>
      <td>32-bit integers.</td>
      <td>705</td>
    </tr>
    <tr>
      <td>28.28</td>
      <td>Module Int64</td>
      <td>64-bit integers.</td>
      <td>709</td>
    </tr>
    <tr>
      <td>28.29</td>
      <td>Module Lazy</td>
      <td>Deferred computations.</td>
      <td>714</td>
    </tr>
    <tr>
      <td>28.30</td>
      <td>Module Lexing</td>
      <td>The run-time library for lexers generated by ocamlex.</td>
      <td>716</td>
    </tr>
    <tr>
      <td>28.31</td>
      <td>Module List</td>
      <td>List operations.</td>
      <td>719</td>
    </tr>
    <tr>
      <td>28.32</td>
      <td>Module ListLabels</td>
      <td>List operations.</td>
      <td>727</td>
    </tr>
    <tr>
      <td>28.33</td>
      <td>Module Map</td>
      <td>Association tables over ordered types.</td>
      <td>736</td>
    </tr>
    <tr>
      <td>28.34</td>
      <td>Module Marshal</td>
      <td>Marshaling of data structures.</td>
      <td>743</td>
    </tr>
    <tr>
      <td>28.35</td>
      <td>Module MoreLabels</td>
      <td>Extra labeled libraries.</td>
      <td>747</td>
    </tr>
    <tr>
      <td>28.36</td>
      <td>Module Mutex</td>
      <td>Locks for mutual exclusion.</td>
      <td>774</td>
    </tr>
    <tr>
      <td>28.37</td>
      <td>Module Nativeint</td>
      <td>Processor-native integers.</td>
      <td>775</td>
    </tr>
    <tr>
      <td>28.38</td>
      <td>Module Oo</td>
      <td>Operations on objects</td>
      <td>779</td>
    </tr>
    <tr>
      <td>28.39</td>
      <td>Module Option</td>
      <td>Option values.</td>
      <td>780</td>
    </tr>
    <tr>
      <td>28.40</td>
      <td>Module Out_channel</td>
      <td>Output channels.</td>
      <td>781</td>
    </tr>
    <tr>
      <td>28.41</td>
      <td>Module Parsing</td>
      <td>The run-time library for parsers generated by ocamlyacc.</td>
      <td>785</td>
    </tr>
    <tr>
      <td>28.42</td>
      <td>Module Printexc</td>
      <td>Facilities for printing exceptions and inspecting current call stack.</td>
      <td>786</td>
    </tr>
    <tr>
      <td>28.43</td>
      <td>Module Printf</td>
      <td>Formatted output functions.</td>
      <td>793</td>
    </tr>
    <tr>
      <td>28.44</td>
      <td>Module Queue</td>
      <td>First-in first-out queues.</td>
      <td>797</td>
    </tr>
    <tr>
      <td>28.45</td>
      <td>Module Random</td>
      <td>Pseudo-random number generators (PRNG).</td>
      <td>801</td>
    </tr>
    <tr>
      <td>28.46</td>
      <td>Module Result</td>
      <td>Result values.</td>
      <td>804</td>
    </tr>
    <tr>
      <td>28.47</td>
      <td>Module Scanf</td>
      <td>Formatted input functions.</td>
      <td>806</td>
    </tr>
    <tr>
      <td>28.48</td>
      <td>Module Seq</td>
      <td>Sequences.</td>
      <td>816</td>
    </tr>
    <tr>
      <td>28.49</td>
      <td>Module Set</td>
      <td>Sets over ordered types.</td>
      <td>829</td>
    </tr>
  </tbody>
</table>
IV The OCaml library 519

28 The core library 521

28.1 Built-in types and predefined exceptions 521

28.2 Module Stdlib : The OCaml Standard library. 524

29 The standard library 553

29.1 Module Arg : Parsing of command line arguments. 555

29.2 Module Array : Array operations. 560

29.3 Module ArrayLabels : Array operations. 568

29.4 Module Atomic : Atomic references. 576

29.5 Module Bigarray : Large, multi-dimensional, numerical arrays. 580

29.6 Module Bool : Boolean values. 602

29.7 Module Buffer : Extensible buffers. 604

29.8 Module Bytes : Byte sequence operations. 609

29.9 Module BytesLabels : Byte sequence operations. 623

29.10 Module Callback : Registering OCaml values with the C runtime. 636

29.11 Module Char : Character operations. 637

29.12 Module Complex : Complex numbers. 641

29.13 Module Condition : Condition variables. 643

29.14 Module Domain : Domains. 645

29.15 Module Digest : Message digest. 648

29.16 Module Dynarray : Dynamic arrays. 652

29.17 Module Iarray 664

29.18 Module Effect : Effects. 669

29.19 Module Either : Either type. 671

29.20 Module Ephemeron : Ephemeron s and weak hash tables. 673

29.21 Module Filename : Operations on file names. 680

29.22 Module Float : Floating-point arithmetic. 684

29.23 Module Format : Pretty-printing. 707

29.24 Module Fun : Function manipulation. 735

29.25 Module Gc : Memory management control and statistics; finalised values. 740

29.26 Module Hashtbl : Hash tables and hash functions. 750

29.27 Module In_channel : Input channels. 762

29.28 Module Int : Integer values. 767

29.29 Module Int32 : 32-bit integers. 770

29.30 Module Int64 : 64-bit integers. 774

29.31 Module Lazy : Deferred computations. 779

29.32 Module Lexing : The run-time library for lexers generated by ocamllex. 781

29.33 Module List : List operations. 784

29.34 Module ListLabels : List operations. 793

29.35 Module Map : Association tables over ordered types. 802

29.36 Module Marshal : Marshaling of data structures. 810

29.37 Module MoreLabels : Extra labeled libraries. 813

29.38 Module Mutex : Locks for mutual exclusion. 840
<table>
  <tbody>
    <tr>
      <td>28.50</td>
      <td>Module Semaphore: Semaphores</td>
      <td>836</td>
    </tr>
    <tr>
      <td>28.51</td>
      <td>Module Stack: Last-in first-out stacks.</td>
      <td>838</td>
    </tr>
    <tr>
      <td>28.52</td>
      <td>Module StdLabels: Standard labeled libraries.</td>
      <td>840</td>
    </tr>
    <tr>
      <td>28.53</td>
      <td>Module String: Strings.</td>
      <td>840</td>
    </tr>
    <tr>
      <td>28.54</td>
      <td>Module StringLabels: Strings.</td>
      <td>849</td>
    </tr>
    <tr>
      <td>28.55</td>
      <td>Module Sys: System interface.</td>
      <td>858</td>
    </tr>
    <tr>
      <td>28.56</td>
      <td>Module Type: Type introspection.</td>
      <td>866</td>
    </tr>
    <tr>
      <td>28.57</td>
      <td>Module Uchar: Unicode characters.</td>
      <td>868</td>
    </tr>
    <tr>
      <td>28.58</td>
      <td>Module Unit: Unit values.</td>
      <td>871</td>
    </tr>
    <tr>
      <td>28.59</td>
      <td>Module Weak: Arrays of weak pointers and hash sets of weak pointers.</td>
      <td>871</td>
    </tr>
    <tr>
      <td>28.60</td>
      <td>Ocaml_operators: Precedence level and associativity of operators.</td>
      <td>875</td>
    </tr>
    <tr>
      <td>29</td>
      <td>The compiler front-end</td>
      <td>877</td>
    </tr>
    <tr>
      <td>29.1</td>
      <td>Module Ast_mapper: The interface of a -ppx rewriter</td>
      <td>877</td>
    </tr>
    <tr>
      <td>29.2</td>
      <td>Module Asttypes: Auxiliary AST types used by parsetree and typedtree.</td>
      <td>881</td>
    </tr>
    <tr>
      <td>29.3</td>
      <td>Module Location: Source code locations (ranges of positions), used in parsetree.</td>
      <td>882</td>
    </tr>
    <tr>
      <td>29.4</td>
      <td>Module Longident: Long identifiers, used in parsetree.</td>
      <td>889</td>
    </tr>
    <tr>
      <td>29.5</td>
      <td>Module Parse: Entry points in the parser</td>
      <td>890</td>
    </tr>
    <tr>
      <td>29.6</td>
      <td>Module Parsetree: Abstract syntax tree produced by parsing</td>
      <td>891</td>
    </tr>
    <tr>
      <td>29.7</td>
      <td>Module Pprintast: Pretty-printers for Parsetree[29.6]</td>
      <td>916</td>
    </tr>
    <tr>
      <td>30</td>
      <td>The unix library: Unix system calls</td>
      <td>919</td>
    </tr>
    <tr>
      <td>30.1</td>
      <td>Module Unix: Interface to the Unix system.</td>
      <td>919</td>
    </tr>
    <tr>
      <td>30.2</td>
      <td>Module UnixLabels: labeled version of the interface</td>
      <td>962</td>
    </tr>
    <tr>
      <td>31</td>
      <td>The str library: regular expressions and string processing</td>
      <td>965</td>
    </tr>
    <tr>
      <td>31.1</td>
      <td>Module Str: Regular expressions and high-level string processing</td>
      <td>965</td>
    </tr>
    <tr>
      <td>32</td>
      <td>The runtime_events library</td>
      <td>973</td>
    </tr>
    <tr>
      <td>32.1</td>
      <td>Module Runtime_events: Runtime events - ring buffer-based runtime tracing</td>
      <td>973</td>
    </tr>
    <tr>
      <td>33</td>
      <td>The threads library</td>
      <td>981</td>
    </tr>
    <tr>
      <td>33.1</td>
      <td>Module Thread: Lightweight threads for Posix 1003.1c and Win32.</td>
      <td>981</td>
    </tr>
    <tr>
      <td>33.2</td>
      <td>Module Event: First-class synchronous communication.</td>
      <td>984</td>
    </tr>
    <tr>
      <td>34</td>
      <td>The dynlink library: dynamic loading and linking of object files</td>
      <td>987</td>
    </tr>
    <tr>
      <td>34.1</td>
      <td>Module Dynlink: Dynamic loading of .cmo, .cma and .cmxs files.</td>
      <td>987</td>
    </tr>
    <tr>
      <td>35</td>
      <td>Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)</td>
      <td>991</td>
    </tr>
    <tr>
      <td>35.1</td>
      <td>The Graphics Library</td>
      <td>991</td>
    </tr>
    <tr>
      <td>35.2</td>
      <td>The Bigarray Library</td>
      <td>991</td>
    </tr>
    <tr>
      <td>35.3</td>
      <td>The Num Library</td>
      <td>992</td>
    </tr>
    <tr>
      <td>35.4</td>
      <td>The Labltk Library and OCamlBrowser.</td>
      <td>992</td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <td>29.39</td>
      <td>Module Nativeint: Processor-native integers.</td>
      <td>841</td>
    </tr>
    <tr>
      <td>29.40</td>
      <td>Module Oo: Operations on objects</td>
      <td>845</td>
    </tr>
    <tr>
      <td>29.41</td>
      <td>Module Option: Option values.</td>
      <td>846</td>
    </tr>
    <tr>
      <td>29.42</td>
      <td>Module Out_channel: Output channels.</td>
      <td>847</td>
    </tr>
    <tr>
      <td>29.43</td>
      <td>Module Pair: Operations on pairs.</td>
      <td>852</td>
    </tr>
    <tr>
      <td>29.44</td>
      <td>Module Parsing: The run-time library for parsers generated by ocamlyacc.</td>
      <td>853</td>
    </tr>
    <tr>
      <td>29.45</td>
      <td>Module Pqueue: Priority queues.</td>
      <td>854</td>
    </tr>
    <tr>
      <td>29.46</td>
      <td>Module Printexc: Facilities for printing exceptions and inspecting current call stack.</td>
      <td>860</td>
    </tr>
    <tr>
      <td>29.47</td>
      <td>Module Printf: Formatted output functions.</td>
      <td>867</td>
    </tr>
    <tr>
      <td>29.48</td>
      <td>Module Queue: First-in first-out queues.</td>
      <td>871</td>
    </tr>
    <tr>
      <td>29.49</td>
      <td>Module Random: Pseudo-random number generators (PRNG).</td>
      <td>875</td>
    </tr>
    <tr>
      <td>29.50</td>
      <td>Module Repr: Functions defined on the low-level representations of values.</td>
      <td>880</td>
    </tr>
    <tr>
      <td>29.51</td>
      <td>Module Result: Result values.</td>
      <td>881</td>
    </tr>
    <tr>
      <td>29.52</td>
      <td>Module Scanf: Formatted input functions.</td>
      <td>884</td>
    </tr>
    <tr>
      <td>29.53</td>
      <td>Module Seq: Sequences.</td>
      <td>893</td>
    </tr>
    <tr>
      <td>29.54</td>
      <td>Module Set: Sets over ordered types.</td>
      <td>906</td>
    </tr>
    <tr>
      <td>29.55</td>
      <td>Module Semaphore: Semaphores</td>
      <td>913</td>
    </tr>
    <tr>
      <td>29.56</td>
      <td>Module Stack: Last-in first-out stacks.</td>
      <td>915</td>
    </tr>
    <tr>
      <td>29.57</td>
      <td>Module StdLabels: Standard labeled libraries.</td>
      <td>917</td>
    </tr>
    <tr>
      <td>29.58</td>
      <td>Module String: Strings.</td>
      <td>917</td>
    </tr>
    <tr>
      <td>29.59</td>
      <td>Module StringLabels: Strings.</td>
      <td>927</td>
    </tr>
    <tr>
      <td>29.60</td>
      <td>Module Sys: System interface.</td>
      <td>936</td>
    </tr>
    <tr>
      <td>29.61</td>
      <td>Module Type: Type introspection.</td>
      <td>946</td>
    </tr>
    <tr>
      <td>29.62</td>
      <td>Module Uchar: Unicode characters.</td>
      <td>948</td>
    </tr>
    <tr>
      <td>29.63</td>
      <td>Module Unit: Unit values.</td>
      <td>951</td>
    </tr>
    <tr>
      <td>29.64</td>
      <td>Module Weak: Arrays of weak pointers and hash sets of weak pointers.</td>
      <td>952</td>
    </tr>
    <tr>
      <td>29.65</td>
      <td>Module Ocaml_operators: Precedence level and associativity of operators.</td>
      <td>955</td>
    </tr>
    <tr>
      <td>30</td>
      <td>The compiler front-end</td>
      <td>957</td>
    </tr>
    <tr>
      <td>30.1</td>
      <td>Module Ast_mapper: The interface of a -ppx rewriter</td>
      <td>957</td>
    </tr>
    <tr>
      <td>30.2</td>
      <td>Module Asttypes: Auxiliary AST types used by parsetree and typedtree.</td>
      <td>961</td>
    </tr>
    <tr>
      <td>30.3</td>
      <td>Module Location: Source code locations (ranges of positions), used in parsetree.</td>
      <td>963</td>
    </tr>
    <tr>
      <td>30.4</td>
      <td>Module Longident: Long identifiers, used in parsetree.</td>
      <td>970</td>
    </tr>
    <tr>
      <td>30.5</td>
      <td>Module Parse: Entry points in the parser</td>
      <td>971</td>
    </tr>
    <tr>
      <td>30.6</td>
      <td>Module Parsetree: Abstract syntax tree produced by parsing</td>
      <td>973</td>
    </tr>
    <tr>
      <td>30.7</td>
      <td>Module Pprintast: Pretty-printers for Parsetree[30.6]</td>
      <td>998</td>
    </tr>
    <tr>
      <td>31</td>
      <td>The unix library: Unix system calls</td>
      <td>1001</td>
    </tr>
    <tr>
      <td>31.1</td>
      <td>Module Unix: Interface to the Unix system.</td>
      <td>1001</td>
    </tr>
    <tr>
      <td>31.2</td>
      <td>Module UnixLabels: labeled version of the interface.</td>
      <td>1045</td>
    </tr>
    <tr>
      <td>32</td>
      <td>The str library: regular expressions and string processing</td>
      <td>1049</td>
    </tr>
    <tr>
      <td>32.1</td>
      <td>Module Str: Regular expressions and high-level string processing</td>
      <td>1049</td>
    </tr>
    <tr>
      <td>33</td>
      <td>The runtime_events library</td>
      <td>1057</td>
    </tr>
    <tr>
      <td>33.1</td>
      <td>Module Runtime_events: Runtime events - ring buffer-based runtime tracing</td>
      <td>1057</td>
    </tr>
  </tbody>
</table>
V Indexes 993

Index to the library 995

Index of keywords 1015
<table><tr><td>34 The threads library</td><td>1071</td></tr><tr><td>34.1 Module Thread: Lightweight threads for Posix 1003.1c and Win32.</td><td>1071</td></tr><tr><td>34.2 Module Event: First-class synchronous communication.</td><td>1074</td></tr><tr><td>35 The dynlink library: dynamic loading and linking of object files</td><td>1077</td></tr><tr><td>35.1 Module Dynlink: Dynamic loading of .cmo, .cma and .cmxs files.</td><td>1077</td></tr><tr><td>36 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)</td><td>1081</td></tr><tr><td>36.1 The Graphics Library</td><td>1081</td></tr><tr><td>36.2 The Bigarray Library</td><td>1081</td></tr><tr><td>36.3 The Num Library</td><td>1082</td></tr><tr><td>36.4 The Labltk Library and OCamlBrowser</td><td>1082</td></tr><tr><td>V Indexes</td><td>1083</td></tr><tr><td>Index to the library</td><td>1085</td></tr><tr><td>Index of keywords</td><td>1107</td></tr></table>
# Foreword

This manual documents the release 5.1 of the OCaml system. It is organized as follows.

* Part I, "An introduction to OCaml", gives an overview of the language.

* Part II, "The OCaml language", is the reference description of the language.

* Part III, "The OCaml tools", documents the compilers, toplevel system, and programming utilities.

* Part IV, "The OCaml library", describes the modules provided in the standard library.

* Part V, "Indexes", contains an index of all identifiers defined in the standard library, and an index of keywords.

# 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 (Vista, 7, 8, 10, 11).

# License

The OCaml system is copyright © 1996–2023 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 OCaml documentation and user's manual is copyright © 2023 Institut National de Recherche en Informatique et en Automatique (INRIA).

The OCaml documentation and user's manual is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0), https://creativecommons.org/licenses/by-sa/4.0/.
# Foreword

This manual documents the release 5.4 of the OCaml system. It is organized as follows.

* Part I, "An introduction to OCaml", gives an overview of the language.

* Part II, "The OCaml language", is the reference description of the language.

* Part III, "The OCaml tools", documents the compilers, toplevel system, and programming utilities.

* Part IV, "The OCaml library", describes the modules provided in the standard library.

* Part V, "Indexes", contains an index of all identifiers defined in the standard library, and an index of keywords.

# 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 (Vista, 7, 8, 10, 11).

# License

The OCaml system is copyright © 1996–2025 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 OCaml documentation and user's manual is copyright © 2025 Institut National de Recherche en Informatique et en Automatique (INRIA).

The OCaml documentation and user's manual is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0), https://creativecommons.org/licenses/by-sa/4.0/.
The sample code in the user's manual and in the reference documentation of the standard library is licensed under a Creative Commons CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License, https://creativecommons.org/publicdomain/zero/1.0/.

Availability

The complete OCaml distribution can be accessed via the website https://ocaml.org/. This site contains a lot of additional information on OCaml.
The sample code in the user's manual and in the reference documentation of the standard library is licensed under a Creative Commons CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License, https://creativecommons.org/publicdomain/zero/1.0/.

Availability

The complete OCaml distribution can be accessed via the website https://ocaml.org/. This site contains a lot of additional information on OCaml.
# Part I

## An introduction to OCaml
# Part I

## An introduction to OCaml
<figure><img src="image_2.png" /></figure>
<figure><img src="image_3.png" /></figure>
# 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 deals with the module system, chapter 3 with the object-oriented features, chapter 4 with labeled arguments, chapter 5 with polymorphic variants, chapter 6 with the limitations of polymorphism, and chapter 8 gives some advanced examples.

### 1.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 below, without a leading `#`.

Under the interactive system, the user types OCaml phrases terminated by `;` in response to the `#` prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation. Phrases are either simple expressions, or `let` definitions of identifiers (either values or functions).

```
# 1 + 2 * 3;;
- : int = 7

# let pi = 4.0 *. atan 1.0;;
val pi : float = 3.14159265358979312

# let square x = x *. x;;
val square : float -> float = <fun>

# square (sin pi) +. square (cos pi);;
- : float = 1.
```

The OCaml system computes both the value and the type for each phrase. Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: `+` and `*` operate on integers, but `+.` and `*.` operate on floats.
# 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 deals with the module system, chapter 3 with the object-oriented features, chapter 4 with labeled arguments, chapter 5 with polymorphic variants, chapter 6 with the limitations of polymorphism, and chapter 8 gives some advanced examples.

### 1.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 below, without a leading `#`.

Under the interactive system, the user types OCaml phrases terminated by `;` in response to the `#` prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation. Phrases are either simple expressions, or `let` definitions of identifiers (either values or functions).

```
# 1 + 2 * 3;;
- : int = 7

# let pi = 4.0 *. atan 1.0;;
val pi : float = 3.14159265358979312

# let square x = x *. x;;
val square : float -> float = <fun>

# square (sin pi) +. square (cos pi);;
- : float = 1.
```

The OCaml system computes both the value and the type for each phrase. Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: `+` and `*` operate on integers, but `+.` and `*.` operate on floats.
# 1.0 * 2;;

Error: This expression has type float but an expression was expected of type
        int

Recursive functions are defined with the `let rec` binding:

# let rec fib n =
    if n < 2 then n else fib (n - 1) + fib (n - 2);;
val fib : int -> int = <fun>

# fib 10;;
- : int = 55

## 1.2 Data types

In addition to integers and floating-point numbers, OCaml offers the usual basic data types:

* booleans

# (1 < 2) = false;;
- : bool = false

# let one = if true then 1 else 2;;
val one : int = 1

* characters

# 'a';;
- : char = 'a'

# int_of_char '\n';;
- : int = 10

* immutable character strings

# "Hello" ^ " " ^ "world";;
- : string = "Hello world"

# {|This is a quoted string, here, neither \ nor " are special characters|};;
- : string =
  "This is a quoted string, here, neither \\ nor " are special characters"

# {|"\"|}=""\\\\"";;
- : bool = true

# {delimiter|the end of this|}quoted string is here|delimiter}
= "the end of this|}quoted string is here";;
- : bool = true
# 1.0 * 2;;

Error: The constant 1.0 has type float but an expression was expected of type
        int

Recursive functions are defined with the `let rec` binding:

# let rec fib n =
    if n < 2 then n else fib (n - 1) + fib (n - 2);;
val fib : int -> int = <fun>

# fib 10;;
- : int = 55

## 1.2 Data types

In addition to integers and floating-point numbers, OCaml offers the usual basic data types:

* booleans

# (1 < 2) = false;;
- : bool = false

# let one = if true then 1 else 2;;
val one : int = 1

* characters

# 'a';;
- : char = 'a'

# int_of_char '\n';;
- : int = 10

* immutable character strings

# "Hello" ^ " " ^ "world";;
- : string = "Hello world"

# {|This is a quoted string, here, neither \ nor " are special characters|};;
- : string =
  "This is a quoted string, here, neither \\ nor " are special characters"

# {|"\"|}=""\\\\"";;
- : bool = true

# {delimiter|the end of this|}quoted string is here|delimiter}
= "the end of this|}quoted string is here";;
- : bool = true
data structures are immutable, but a few (most notably arrays) are *mutable*, meaning that they can be modified in-place at any time.

The OCaml notation for the type of a function with multiple arguments is `arg1_type -> arg2_type -> ... -> return_type`. For example, the type inferred for `insert`, `'a -> 'a list -> 'a list`, means that `insert` takes two arguments, an element of any type `'a` and a list with elements of the same type `'a` and returns a list of the same type.

## 1.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:

```ocaml
# let deriv f dx = fun x -> (f (x +. dx) -. f x) /-. dx;;
val deriv : (float -> float) -> float -> float -> float = <fun>

# let sin' = deriv sin 1e-6;;
val sin' : float -> float = <fun>

# sin' pi;;
- : float = -1.00000000013961143
```

Even function composition is definable:

```ocaml
# let compose f g = fun x -> f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>

# let cos2 = compose square cos;;
val cos2 : float -> float = <fun>
```

Functions that take other functions as arguments are called "functionals", or "higher-order functions". Functionals are especially useful to provide iterators or similar generic operations over a data structure. For instance, the standard OCaml library provides a `List.map` functional that applies a given function to each element of a list, and returns the list of the results:

```ocaml
# List.map (fun n -> n * 2 + 1) [0;1;2;3;4];;
- : int list = [1; 3; 5; 7; 9]
```

This functional, along with a number of other list and array functionals, is predefined because it is often useful, but there is nothing magic with it: it can easily be defined as follows.

```ocaml
# let rec map f l =
  match l with
  [] -> []
  | hd :: tl -> f hd :: map f tl;;
val map : ('a -> 'b) -> 'a list -> 'b list = <fun>
```
data structures are immutable, but a few (most notably arrays) are *mutable*, meaning that they can be modified in-place at any time.

The OCaml notation for the type of a function with multiple arguments is `arg1_type -> arg2_type -> ... -> return_type`. For example, the type inferred for `insert`, `'a -> 'a list -> 'a list`, means that `insert` takes two arguments, an element of any type `'a` and a list with elements of the same type `'a` and returns a list of the same type.

## 1.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:

```ocaml
# let deriv f dx = fun x -> (f (x +. dx) -. f x) /-. dx;;
val deriv : (float -> float) -> float -> float -> float = <fun>

# let sin' = deriv sin 1e-6;;
val sin' : float -> float = <fun>

# sin' pi;;
- : float = -1.00000000013961143
```

Even function composition is definable:

```ocaml
# let compose f g = fun x -> f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>

# let cos2 = compose square cos;;
val cos2 : float -> float = <fun>
```

Functions that take other functions as arguments are called "functionals", or "higher-order functions". Functionals are especially useful to provide iterators or similar generic operations over a data structure. For instance, the standard OCaml library provides a `List.map` functional that applies a given function to each element of a list, and returns the list of the results:

```ocaml
# List.map (fun n -> n * 2 + 1) [0;1;2;3;4];;
- : int list = [1; 3; 5; 7; 9]
```

This functional, along with a number of other list and array functionals, is predefined because it is often useful, but there is nothing magic with it: it can easily be defined as follows.

```ocaml
# let rec map f l =
  match l with
  [] -> []
  | hd :: tl -> f hd :: map f tl;;
val map : ('a -> 'b) -> 'a list -> 'b list = <fun>
```
## 1.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.

```hkl
# type ratio = {num: int; denom: int};;

type ratio = { num : int; denom : int; }

# let add_ratio r1 r2 =
  {num = r1.num * r2.denom + r2.num * r1.denom;
   denom = r1.denom * r2.denom};;

val add_ratio : ratio -> ratio -> ratio = <fun>

# add_ratio {num=1; denom=3} {num=2; denom=5};;
- : ratio = {num = 11; denom = 15}
```

Record fields can also be accessed through pattern-matching:

```hkl
# let integer_part r =
  match r with
    {num=num; denom=denom} -> num / denom;;

val integer_part : ratio -> int = <fun>
```

Since there is only one case in this pattern matching, it is safe to expand directly the argument `r` in a record pattern:

```hkl
# let integer_part {num=num; denom=denom} = num / denom;;

val integer_part : ratio -> int = <fun>
```

Unneeded fields can be omitted:

```hkl
# let get_denom {denom=denom} = denom;;

val get_denom : ratio -> int = <fun>
```

Optionally, missing fields can be made explicit by ending the list of fields with a trailing wildcard `_::`:

```hkl
# let get_num {num=num; _ } = num;;

val get_num : ratio -> int = <fun>
```

When both sides of the `=` sign are the same, it is possible to avoid repeating the field name by eliding the `=field` part:

```hkl
# let integer_part {num; denom} = num / denom;;

val integer_part : ratio -> int = <fun>
```

This short notation for fields also works when constructing records:

```hkl
# 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:

```hkl
# let integer_product integer ratio = { ratio with num = integer * ratio.num };
```
## 1.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.

```hkl
# type ratio = {num: int; denom: int};;

type ratio = { num : int; denom : int; }

# let add_ratio r1 r2 =
  {num = r1.num * r2.denom + r2.num * r1.denom;
   denom = r1.denom * r2.denom};;

val add_ratio : ratio -> ratio -> ratio = <fun>

# add_ratio {num=1; denom=3} {num=2; denom=5};;
- : ratio = {num = 11; denom = 15}
```

Record fields can also be accessed through pattern-matching:

```hkl
# let integer_part r =
  match r with
    {num=num; denom=denom} -> num / denom;;

val integer_part : ratio -> int = <fun>
```

Since there is only one case in this pattern matching, it is safe to expand directly the argument `r` in a record pattern:

```hkl
# let integer_part {num=num; denom=denom} = num / denom;;

val integer_part : ratio -> int = <fun>
```

Unneeded fields can be omitted:

```hkl
# let get_denom {denom=denom} = denom;;

val get_denom : ratio -> int = <fun>
```

Optionally, missing fields can be made explicit by ending the list of fields with a trailing wildcard `_::`:

```hkl
# let get_num {num=num; _ } = num;;

val get_num : ratio -> int = <fun>
```

When both sides of the `=` sign are the same, it is possible to avoid repeating the field name by eliding the `=field` part:

```hkl
# let integer_part {num; denom} = num / denom;;

val integer_part : ratio -> int = <fun>
```

This short notation for fields also works when constructing records:

```hkl
# 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:

```hkl
# let integer_product integer ratio = { ratio with num = integer * ratio.num };
```
```val integer_product : int -> ratio -> ratio = <fun>
```

With this functional update notation, the record on the left-hand side of `with` is copied except for the fields on the right-hand side which are updated.

The declaration of a variant type lists all possible forms for values of that type. Each case is identified by a name, called a constructor, which serves both for constructing values of the variant type and inspecting them by pattern-matching. Constructor names are capitalized to distinguish them from variable names (which must start with a lowercase letter). For instance, here is a variant type for doing mixed arithmetic (integers and floats):

```# type number = Int of int | Float of float | Error;;
type number = Int of int | Float of float | Error
```

This declaration expresses that a value of type `number` is either an integer, a floating-point number, or the constant `Error` representing the result of an invalid operation (e.g. a division by zero).

Enumerated types are a special case of variant types, where all alternatives are constants:

```# type sign = Positive | Negative;;
type sign = Positive | Negative

# let sign_int n = if n >= 0 then Positive else Negative;;
val sign_int : int -> sign = <fun>
```

To define arithmetic operations for the `number` type, we use pattern-matching on the two numbers involved:

```# 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
        then Float(float i1 +. float i2)
        else Int(i1 + i2)
    | (Int i1, Float f2) -> Float(float i1 +. f2)
    | (Float f1, Int i2) -> Float(f1 +. float i2)
    | (Float f1, Float f2) -> Float(f1 +. f2)
    | (Error,_) -> Error
    | (_, Error) -> Error;;

val add_num : number -> number -> number = <fun>
```

```# add_num (Int 123) (Float 3.14159);;
- : number = Float 126.14159
```

Another interesting example of variant type is the built-in `'a option'` type which represents either a value of type `'a` or an absence of value:

```# type 'a option = Some of 'a | None;;
type 'a option = Some of 'a | None
```

This type is particularly useful when defining function that can fail in common situations, for instance
```val integer_product : int -> ratio -> ratio = <fun>
```

With this functional update notation, the record on the left-hand side of `with` is copied except for the fields on the right-hand side which are updated.

The declaration of a variant type lists all possible forms for values of that type. Each case is identified by a name, called a constructor, which serves both for constructing values of the variant type and inspecting them by pattern-matching. Constructor names are capitalized to distinguish them from variable names (which must start with a lowercase letter). For instance, here is a variant type for doing mixed arithmetic (integers and floats):

```# type number = Int of int | Float of float | Error;;
type number = Int of int | Float of float | Error
```

This declaration expresses that a value of type `number` is either an integer, a floating-point number, or the constant `Error` representing the result of an invalid operation (e.g. a division by zero).

Enumerated types are a special case of variant types, where all alternatives are constants:

```# type sign = Positive | Negative;;
type sign = Positive | Negative

# let sign_int n = if n >= 0 then Positive else Negative;;
val sign_int : int -> sign = <fun>
```

To define arithmetic operations for the `number` type, we use pattern-matching on the two numbers involved:

```# 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
        then Float(float i1 +. float i2)
        else Int(i1 + i2)
    | (Int i1, Float f2) -> Float(float i1 +. f2)
    | (Float f1, Int i2) -> Float(f1 +. float i2)
    | (Float f1, Float f2) -> Float(f1 +. f2)
    | (Error,_) -> Error
    | (_, Error) -> Error;;

val add_num : number -> number -> number = <fun>

# add_num (Int 123) (Float 3.14159);;
- : number = Float 126.14159
```

Another interesting example of variant type is the built-in `'a option'` type which represents either a value of type `'a` or an absence of value:

```# type 'a option = Some of 'a | None;;
type 'a option = Some of 'a | None
```

This type is particularly useful when defining function that can fail in common situations, for instance
```h
# let safe_square_root x = if x >= 0. then Someovern(ssqrt x) else None;;
val safe_square_root : float -> float option = <fun>
```

The most common usage of variant types is to describe recursive data structures. Consider for example the type of binary trees:

```h
# type 'a btree = Empty | Node of 'a * 'a btree * 'a btree;;
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
```

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 recursive functions following the same structure as the type definition itself. For instance, here are functions performing lookup and insertion in ordered binary trees (elements increase from left to right):

```h
# let rec member x btree =
    match btree with
    Empty -> false
  | Node(y, left, right) ->
      if x = y then true else
      if x < y then member x left else member x right;;
val member : 'a -> 'a btree -> bool = <fun>
```

```h
# let rec insert x btree =
    match btree with
    Empty -> Node(x, Empty, Empty)
  | Node(y, left, right) ->
      if x <= y then Node(y, insert x left, right)
      else Node(y, left, insert x right);;
val insert : 'a -> 'a btree -> 'a btree = <fun>
```

### 1.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

```h
# type first_record = { x:int; y:int; z:int }
type middle_record = { x:int; z:int }
type last_record = { x:int };;
```

```h
# type first = A | B | C

type lastep = A;;
```

The answer is that when confronted with multiple options, OCaml tries to use locally available information to disambiguate between the various fields and constructors. First, if the type of the record or variant is known, OCaml can pick unambiguously the corresponding field or constructor. For instance:
```h
# let safe_square_root x = if x >= 0. then Someovern(ssqrt x) else None;;
val safe_square_root : float -> float option = <fun>
```

The most common usage of variant types is to describe recursive data structures. Consider for example the type of binary trees:

```h
# type 'a btree = Empty | Node of 'a * 'a btree * 'a btree;;
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
```

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 recursive functions following the same structure as the type definition itself. For instance, here are functions performing lookup and insertion in ordered binary trees (elements increase from left to right):

```h
# let rec member x btree =
    match btree with
    Empty -> false
  | Node(y, left, right) ->
      if x = y then true else
      if x < y then member x left else member x right;;
val member : 'a -> 'a btree -> bool = <fun>
```

```h
# let rec insert x btree =
    match btree with
    Empty -> Node(x, Empty, Empty)
  | Node(y, left, right) ->
      if x <= y then Node(y, insert x left, right)
      else Node(y, left, insert x right);;
val insert : 'a -> 'a btree -> 'a btree = <fun>
```

### 1.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

```h
# type first_record = { x:int; y:int; z:int }
type middle_record = { x:int; z:int }
type last_record = { x:int };;
```

```h
# type first = A | B | C

type lastep = A;;
```

The answer is that when confronted with multiple options, OCaml tries to use locally available information to disambiguate between the various fields and constructors. First, if the type of the record or variant is known, OCaml can pick unambiguously the corresponding field or constructor. For instance:
```h
# let look_at_x_then_z (r:first_record) =
  let x = r.x in
  x + r.z;;
val look_at_x_then_z : first_record -> int = <fun>

# let permute (x:first) = match x with
  | A -> (B:firstep)
  | B -> A
  | C -> C;;
val permute : firstep -> firstep = <fun>
```

```h
# type wrapped = First of first_record
let f (First r) = r, r.x;;

type wrapped = First of first_record
val f : wrapped -> first_record * int = <fun>
```

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 OCaml that the constructors `A`, `B` and `C` come from the first variant type. Contrarily, in the last example, OCaml has inferred by itself that the type of `r` can only be `first_record` and there are no needs for explicit type annotations.

Those explicit type annotations can in fact be used anywhere. Most of the time they are unnecessary, but they are useful to guide disambiguation, to debug unexpected type errors, or combined with some of the more advanced features of OCaml described in later chapters.

Secondly, for records, OCaml can also deduce the right record type by looking at the whole set of fields used in a expression or pattern:

```h
# let project_and_rotate {x; y; _} = { x= - y; y = x; z = 0} ;;
val project_and_rotate : first_record -> first_record = <fun>
```

Since the fields `x` and `y` can only appear simultaneously in the first record type, OCaml infers that the type of `project_and_rotate` is `first_record -> first_record`.

In last resort, if there is not enough information to disambiguate between different fields or constructors, OCaml picks the last defined type amongst all locally valid choices:

```h
# let look_at_xz {x; z} = x;;
val look_at_xz : middle_record -> int = <fun>
```

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 disambiguation is local: once OCaml has chosen a disambiguation, it sticks to this choice, even if it leads to an ulterior type error:

```h
# let look_at_x_then_y r =
  let x = r.x in (* OCaml deduces [r: last_record] *)
  x + r.y;;
```
```hkl
# let look_at_x_then_z (r:first_record) =
  let x = r.x in
  x + r.z;;
val look_at_x_then_z : first_record -> int = <fun>

# let permute (x:first) = match x with
  | A -> (B:firstep)
  | B -> A
  | C -> C;;
val permute : firstep -> firstep = <fun>
```

```hkl
# type wrapped = First of first_record
let f (First r) = r, r.x;;
type wrapped = First of first_record
val f : wrapped -> first_record * int = <fun>
```

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 OCaml that the constructors `A`, `B` and `C` come from the first variant type. Contrarily, in the last example, OCaml has inferred by itself that the type of `r` can only be `first_record` and there are no needs for explicit type annotations.

Those explicit type annotations can in fact be used anywhere. Most of the time they are unnecessary, but they are useful to guide disambiguation, to debug unexpected type errors, or combined with some of the more advanced features of OCaml described in later chapters.

Secondly, for records, OCaml can also deduce the right record type by looking at the whole set of fields used in a expression or pattern:

```hkl
# let project_and_rotate {x; y; _} = { x= - y; y = x; z = 0} ;;
val project_and_rotate : first_record -> first_record = <fun>
```

Since the fields `x` and `y` can only appear simultaneously in the first record type, OCaml infers that the type of `project_and_rotate` is `first_record -> first_record`.

In last resort, if there is not enough information to disambiguate between different fields or constructors, OCaml picks the last defined type amongst all locally valid choices:

```hkl
# let look_at_xz {x; z} = x;;
val look_at_xz : middle_record -> int = <fun>
```

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 disambiguation is local: once OCaml has chosen a disambiguation, it sticks to this choice, even if it leads to an ulterior type error:

```hkl
# let look_at_x_then_y r =
  let x = r.x in (* OCaml deduces [r: last_record] *)
  x + r.y;;
```
```
Error: This expression has type last_record
There is no field y within type last_record
```

```h
# let is_a_or_b x = match x with
| A -> true (* OCaml infers [x: last] *)
| B -> true;;
```

```
Error: This variant pattern is expected to have type last le variant
There is no constructor B within type last le variant
```

Moreover, being the last defined type is a quite unstable position that may change surreptitiously after adding or moving around a type definition, or after opening a module (see chapter 2). Consequently, adding explicit type annotations to guide disambiguation is more robust than relying on the last defined type disambiguation.

## 1.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 between `[` and `]` brackets, or allocated and initialized with the `Array.make` function, then filled up later by assignments. For instance, the function below sums two vectors (represented as float arrays) componentwise.

```h
# let addVect v1 v2 =
    let len = min (Array.length v1) (Array.length v2) in
    let res = Array.make len 0.0 in
    for i = 0 to len - 1 do
        res.(i) <- v1.(i) +. v2.(i)
    done;
    res;;
val addVect : float array -> float array -> float array = <fun>
```

```h
# add vect [ 1.0; 2.0 ] [ 3.0; 4.0 ];;
- : float array = [14.; 6.]
```

Record fields can also be modified by assignment, provided they are declared `mutable` in the definition of the record type:

```h
# type mutable_point = { mutable x: float; mutable y: float };;
type mutable_point = { mutable x : float; mutable y : float; }
```

```h
# let translate p dx dy =
    p.x <- p.x +. dx; p.y <- p.y +. dy;;
val translate : mutable_point -> float -> float -> unit = <fun>
```

```h
# let mypoint = { x = 0.0; y = 0.0 };;
val mypoint : mutable_point = {x = 0.; y = 0.}
```
```
Error: This expression has type last_record
There is no field y within type last_record
```

```h
# let is_a_or_b x = match x with
| A -> true (* OCaml infers [x: last_variant] *)
| B -> true;;
```

```
Error: This variant pattern is expected to have type last
There is no constructor B within type last_variant
```

Moreover, being the last defined type is a quite unstable position that may change surreptitiously after adding or moving around a type definition, or after opening a module (see chapter 2). Consequently, adding explicit type annotations to guide disambiguation is more robust than relying on the last defined type disambiguation.

## 1.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 between `[` and `]` brackets, or allocated and initialized with the `Array.make` function, then filled up later by assignments. For instance, the function below sums two vectors (represented as float arrays) componentwise.

```h
# let addVect v1 v2 =
    let len = min (Array.length v1) (Array.length v2) in
    let res = Array.make len 0.0 in
    for i = 0 to len - 1 do
        res.(i) <- v1.(i) +. v2.(i)
    done;
    res;;

val addVect : float array -> float array -> float array = <fun>
```

```h
# add vect [ 1.0; 2.0 ] [ 3.0; 4.0 ];;
- : float array = [ |4.; 6. | ]
```

Record fields can also be modified by assignment, provided they are declared `mutable` in the definition of the record type:

```h
# type mutable_point = { mutable x: float; mutable y: float };;
type mutable_point = { mutable x : float; mutable y : float; }
```

```h
# let translate p dx dy =
    p.x <- p.x +. dx; p.y <- p.y +. dy;;

val translate : mutable_point -> float -> float -> unit = <fun>
```

```h
# let mypoint = { x = 0.0; y = 0.0 };;
val mypoint : mutable_point = {x = 0.; y = 0.}
```
```ocaml
# translate mypoint 1.0 2.0;;
- : unit = ()
```

```ocaml
# mypoint;;
- : mutable_point = {x = 1.; y = 2.}
```

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 operators `!` to fetch the current contents of the reference and `:=` to assign the contents. Variables can then be emulated by `let`-binding a reference. For instance, here is an in-place insertion sort over arrays:

```ocaml
# let insertion_sort a =
    for i = 1 to Array.length a - 1 do
        let val_i = a.(i) in
        let j = ref i in
        while !j > 0 && val_i < a.(!j - 1) do
            a.(!j) <- a.(!j - 1);
            j := !j - 1
        done;
        a.(!j) <- val_i
    done;;
val insertion_sort : 'a array -> unit = <fun>
```

References are also useful to write functions that maintain a current state between two calls to the function. For instance, the following pseudo-random number generator keeps the last returned number in a reference:

```ocaml
# let current_random = ref 0;;
val current_random : int ref = {contents = 0}
```

```ocaml
# let random () =
    current_random := !current_random * 25713 + 1345;
    !current_random;;
val random : unit -> int = <fun>
```

Again, there is nothing magical with references: they are implemented as a single-field mutable record, as follows.

```ocaml
# type 'a ref = { mutable contents: 'a };;

type 'a ref = { mutable contents : 'a; }
```

```ocaml
# let ( ! ) r = r_contents;;
val ( ! ) : 'a ref -> 'a = <fun>
```

```ocaml
# let ( := ) r newval = r_contents <- newval;;
val ( := ) : 'a ref -> 'a -> unit = <fun>
```
# translate mypoint 1.0 2.0;;
- : unit = ()

# mypoint;;
- : mutable_point = {x = 1.; y = 2.}

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 operators `!` to fetch the current contents of the reference and `:=` to assign the contents. Variables can then be emulated by `let`-binding a reference. For instance, here is an in-place insertion sort over arrays:

# let insertion_sort a =
    for i = 1 to Array.length a - 1 do
        let val_i = a.(i) in
        let j = ref i in
        while !j > 0 && val_i < a.(!j - 1) do
            a.(!j) <- a.(!j - 1);
            j := !j - 1
        done;
        a.(!j) <- val_i
    done;

val insertion_sort : 'a array -> unit = <fun>

References are also useful to write functions that maintain a current state between two calls to the function. For instance, the following pseudo-random number generator keeps the last returned number in a reference:

# let current_random = ref 0;;
val current_random : int ref = {contents = 0}

# let random () =
    current_random := !current_random * 25713 + 1345;
    !current_random;;
val random : unit -> int = <fun>

Again, there is nothing magical with references: they are implemented as a single-field mutable record, as follows.

# type 'a ref = { mutable contents: 'a };;

type 'a ref = { mutable contents : 'a; }

# let ( ! ) r = r_contents;;
val ( ! ) : 'a ref -> 'a = <fun>

# let ( := ) r newval = r_contents <- newval;;
val ( := ) : 'a ref -> 'a -> unit = <fun>
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
to record fields.

```h
# type idref = { mutable id: 'a. 'a -> 'a };;

type idref = { mutable id : 'a. 'a -> 'a; }

# let r = {id = fun x -> x};;

val r : idref = {id = <fun>}

# let g s = (s.id 1, s.id true);;

val g : idref -> int * bool = <fun>

# r.id <- (fun x -> print_string "called id\n"; x);;
- : unit = ()

# g r;;

called id
called id
- : int * bool = (1, true)
```

## 1.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 signalled with the `raise` operator. For instance, the function below for taking the head of a list uses an exception to signal the case where an empty list is given.

```h
# exception Empty_list;;

exception Empty_list

# let head l =
match l with
  [] -> raise Empty_list
  | hd :: tl -> hd;;

val head : 'a list -> 'a = <fun>

# head [1; 2];;
- : int = 1

# head [];;
Exception: Empty_list
```

Exceptions are used throughout the standard library to signal cases where the library functions cannot complete normally. For instance, the `List.assoc` function, which returns the data associated with a given key in a list of (key, data) pairs, raises the predefined exception `Not_found` when the key does not appear in the list:
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
to record fields.

```h
# type idref = { mutable id: 'a. 'a -> 'a };;

type idref = { mutable id : 'a. 'a -> 'a; }

# let r = {id = fun x -> x};;

val r : idref = {id = <fun>}

# let g s = (s.id 1, s.id true);;

val g : idref -> int * bool = <fun>

# r.id <- (fun x -> print_string "called id\n"; x);;
- : unit = ()

# g r;;

called id
called id
- : int * bool = (1, true)
```

1.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 signalled with the **raise** operator. For instance, the function below for taking the head of a list
uses an exception to signal the case where an empty list is given.

```h
# exception Empty_list;;

exception Empty_list

# let head l =
match l with
  [] -> raise Empty_list
  | hd :: tl -> hd;;

val head : 'a list -> 'a = <fun>

# head [1; 2];;
- : int = 1

# head [];;
Exception: Empty_list
```

Exceptions are used throughout the standard library to signal cases where the library functions
cannot complete normally. For instance, the `List.assoc` function, which returns the data associated
with a given key in a list of (key, data) pairs, raises the predefined exception `Not_found` when the
key does not appear in the list:
```h
# List.assoc 1 [(0, "zero"); (1, "one")];;
- : string = "one"
```

```h
# List.assoc 2 [(0, "zero"); (1, "one")];;
Exception: Not_found.
```

Exceptions can be trapped with the `try...with` construct:

```h
# let name_of_binary interf digit =
  try
    List.assoc digit [0, "zero"; 1, "one"]
  with Not_found ->
    "not a binary digit";;
val name_of_binary interf : int -> string = <fun>
```

```h
# name_of_binary interf 0;;
- : string = "zero"
```

```h
# name_of_binary interf (-1);;
- : string = "not a binary digit"
```

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:

```h
# let rec first_named_value values names =
  try
    List.assoc (head values) names
  with
    | Empty_list -> "no named value"
    | Not_found -> first_named_value (List.tl values) names;;
val first_named_value : 'a list -> ('a * string) list -> string = <fun>
```

```h
# first_named_value [0; 10] [1, "one"; 10, "ten"];;
- : string = "ten"
```

Also, finalization can be performed by trapping all exceptions, performing the finalization, then re-raising the exception:

```h
# let temporarily_set_reference ref newval funct =
  let oldval = !ref in
  try
    ref := newval;
    let res = funct () in
    ref := oldval;
    res
  with x ->
    ref := oldval;
    raise x;;
val temporarily_set_reference : 'a ref -> 'a -> (unit -> 'b) -> 'b = <fun>
```
```h
# List.assoc 1 [(0, "zero"); (1, "one")];;
- : string = "one"
```

```h
# List.assoc 2 [(0, "zero"); (1, "one")];;
Exception: Not_found.
```

Exceptions can be trapped with the `try...with` construct:

```h
# let name_of_binarydigit digit =
  try
    List.assoc digit [0, "zero"; 1, "one"]
  with Not_found ->
    "not a binary digit";;
val name_of_binarydigit : int -> string = <fun>
```

```h
# name_of_binarydigit 0;;
- : string = "zero"
```

```h
# name_of_binarydigit (-1);;
- : string = "not a binary digit"
```

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:

```h
# let rec first_named_value values names =
  try
    List.assoc (head values) names
  with
    | Empty_list -> "no named value"
    | Not_found -> first_named_value (List.tl values) names;;
val first_named_value : 'a list -> ('a * string) list -> string = <fun>
```

```h
# first_named_value [0; 10] [1, "one"; 10, "ten"];;
- : string = "ten"
```

Also, finalization can be performed by trapping all exceptions, performing the finalization, then re-raising the exception:

```h
# let temporarily_set_reference ref newval funct =
  let oldval = !ref in
  try
    ref := newval;
    let res = funct () in
    ref := oldval;
    res
  with x ->
    ref := oldval;
    raise x;;
val temporarily_set_reference : 'a ref -> 'a -> (unit -> 'b) -> 'b = <fun>
```
An alternative to `try...with` is to catch the exception while pattern matching:

```hkl
# let assoc_may_map f x l =
    match List.assoc x l with
    | exception Not_found -> None
    | y -> f y;;

val assoc_may_map : ('a -> 'b option) -> 'c -> ('c * 'a) list -> 'b option =
    <fun>
```

Note that this construction is only useful if the exception is raised between `match...with`. Exception patterns can be combined with ordinary patterns at the toplevel,

```hkl
# let flat assoc_opt x l =
    match List.assoc x l with
    | None | exception Not_found -> None
    | Some _ as v -> v;;

val flat assoc_opt : 'a -> ('a * 'b option) list -> 'b option = <fun>
```

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

```hkl
# let fixpoint f x =
    let exception Done in
    let x = ref x in
    try while true do
        let y = f !x in
        if !x = y then raise Done else x := y
    done; assert false
    with Done -> !x;;

val fixpoint : ('a -> 'a) -> 'a -> 'a = <fun>
```

the function `f` cannot raise a `Done` exception, which removes an entire class of misbehaving functions.

## 1.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 lazy expression.

```hkl
# let lazy_two = lazy (print_endline "lazy_two evaluation"; 1 + 1);;
val lazy_two : int lazy_t = <lazy>
```

We added `print_endline "lazy_two evaluation"` to see when the lazy expression is being evaluated.

The value of `lazy_two` is displayed as `<lazy>`, which means the expression has not been evaluated yet, and its final value is unknown.
An alternative to `try...with` is to catch the exception while pattern matching:

```hkl
# let assoc_may_map f x l =
    match List.assoc x l with
    | exception Not_found -> None
    | y -> f y;;

val assoc_may_map : ('a -> 'b option) -> 'c -> ('c * 'a) list -> 'b option =
    <fun>
```

Note that this construction is only useful if the exception is raised between `match...with`. Exception patterns can be combined with ordinary patterns at the toplevel,

```hkl
# let flat assoc_opt x l =
    match List.assoc x l with
    | None | exception Not_found -> None
    | Some _ as v -> v;;

val flat assoc_opt : 'a -> ('a * 'b option) list -> 'b option = <fun>
```

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

```hkl
# let fixpoint f x =
    let exception Done in
    let x = ref x in
    try while true do
        let y = f !x in
        if !x = y then raise Done else x := y
    done
    with Done -> !x;;

val fixpoint : ('a -> 'a) -> 'a -> 'a = <fun>
```

the function `f` cannot raise a `Done` exception, which removes an entire class of misbehaving functions.

## 1.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 lazy expression.

```hkl
# let lazy_two = lazy (print_endline "lazy_two evaluation"; 1 + 1);;
val lazy_two : int lazy_t = <lazy>
```

We added `print_endline "lazy_two evaluation"` to see when the lazy expression is being evaluated.

The value of `lazy_two` is displayed as `<lazy>`, which means the expression has not been evaluated yet, and its final value is unknown.
Note that `lazy_two` has type `int lazy_t`. However, the type `'a lazy_t` is an internal type name, so the type `'a Lazy_t` should be preferred when possible.

When we finally need the result of a lazy expression, we can call `Lazy.force` on that expression to force its evaluation. The function `force` comes from standard-library module `Lazy`[28.29].

```hml
# Lazy.force lazy_two;;

lazy_two evaluation
- : int = 2
```

Notice that our function call above prints `lazy_two` evaluation and then returns the plain value of the computation.

Now if we look at the value of `lazy_two`, we see that it is not displayed as `<lazy>` anymore but as `lazy 2`.

```hml
# lazy_two;;
- : int lazy_t = lazy 2
```

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.

```hml
# Lazy.force lazy_two;;
- : int = 2
```

The expression is not evaluated this time; notice that `lazy_two` evaluation is not printed. The result of the initial computation is simply returned.

Lazy patterns provide another way to force a lazy expression.

```hml
# let lazy_1 = lazy ([1; 2] @ [3; 4]);
val lazy_1 : int list lazy_t = <lazy>
```

```hml
# let lazy 1 = lazy_1;;
val 1 : int list = [1; 2; 3; 4]
```

We can also use lazy patterns in pattern matching.

```hml
# let maybe_eval lazy-guard lazy-expr =
  match lazy-guard, lazy-expr with
  | lazy false, _ -> "matches if (Lazy.force lazy-guard = false); lazy-expr not forced"
  | lazy true, lazy _ -> "matches if (Lazy.force lazy-guard = true); lazy-expr forced";
val maybe_eval : bool lazy_t -> 'a lazy_t -> string = <fun>
```

The lazy expression `lazy_expr` is forced only if the `lazy-guard` value yields `true` once computed. Indeed, a simple wildcard pattern (not lazy) never forces the lazy expression's evaluation. However, a pattern with keyword `lazy`, even if it is wildcard, always forces the evaluation of the deferred computation.

## 1.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:
Note that `lazy_two` has type `int lazy_t`. However, the type `'a lazy_t` is an internal type name, so the type `'a Lazy_t` should be preferred when possible.

When we finally need the result of a lazy expression, we can call `Lazy.force` on that expression to force its evaluation. The function `force` comes from standard-library module `Lazy`[29.31].

```h
# Lazy.force lazy_two;;

lazy_two evaluation
- : int = 2
```

Notice that our function call above prints `"lazy_two evaluation"` and then returns the plain value of the computation.

Now if we look at the value of `lazy_two`, we see that it is not displayed as `<lazy>` anymore but as `lazy 2`.

```h
# lazy_two;;
- : int lazy_t = lazy 2
```

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.

```h
# Lazy.force lazy_two;;
- : int = 2
```

The expression is not evaluated this time; notice that `"lazy_two evaluation"` is not printed. The result of the initial computation is simply returned.

Lazy patterns provide another way to force a lazy expression.

```h
# let lazy_1 = lazy ([1; 2] @ [3; 4]);
val lazy_1 : int list lazy_t = <lazy>
```

```h
# let lazy 1 = lazy_1;;
val 1 : int list = [1; 2; 3; 4]
```

We can also use lazy patterns in pattern matching.

```h
# let maybe_eval lazy-guard lazy-expr =
  match lazy-guard, lazy-expr with
  | lazy false, _ -> "matches if (Lazy.force lazy-guard = false); lazy-expr not forced"
  | lazy true, lazy _ -> "matches if (Lazy.force lazy-guard = true); lazy-expr forced";
val maybe_eval : bool lazy_t -> 'a lazy_t -> string = <fun>
```

The lazy expression `lazy_expr` is forced only if the `lazy-guard` value yields `true` once computed. Indeed, a simple wildcard pattern (not lazy) never forces the lazy expression's evaluation. However, a pattern with keyword `lazy`, even if it is wildcard, always forces the evaluation of the deferred computation.

## 1.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:
```h
val print_expr : expression -> unit = <fun>

# let e = Sum(Prod(Const 2.0, Var "x"), Const 1.0);;
val e : expression = Sum (Prod (Const 2., Var "x"), Const 1.)

# print_expr e; print_newline ();;
2. * x + 1.
- : unit = ()

# print_expr (deriv e "x"); print_newline ();;
2. * 1. + 0. * x + 0.
- : unit = ()
```

## 1.10 Printf formats

There is a `printf` function in the `FORMAT` module (see chapter 2) 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 format string that describes the desired output as a text interspersed with specifiers (for instance `%d`, `%f`). Next, the specifiers are substituted by the following arguments in their order of apparition in the format string:

```h
# Printf準printf "%i + %i is an integer value, %F * %F is a float, %S\n"
3 2 4.5 1. "this is a string";;
3 + 2 is an integer value, 4.5 * 1. is a float, "this is a string"
- : unit = ()
```

The OCaml type system checks that the type of the arguments and the specifiers are compatible. If you pass it an argument of a type that does not correspond to the format specifier, the compiler will display an error message:

```h
# Printf準printf "Float value: %F" 42;;
Error: This expression has type int but an expression was expected of type
       float
Hint: Did you mean `42.'?`
```

The `fprintf` function is like `printf` except that it takes an output channel as the first argument. The `%a` specifier can be useful to define custom printers (for custom types). For instance, we can create a printing template that converts an integer argument to signed decimal:

```h
# let pp_int ppf n = Printf.fprintf ppf "%d" n;;
val pp_int : out_channel -> int -> unit = <fun>
```

```h
# Printf準printf "Outputting an integer using a custom printer: %a " pp_int 42;;
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'`:
```rust
val print_expr: expression -> unit = <fun>

# let e = Sum(Prod(Const 2.0, Var "x"), Const 1.0);
val e: expression = Sum (Prod (Const 2., Var "x"), Const 1.)

# print_expr e; print_newline ();;
2. * x + 1.
- : unit = ()

# print_expr (deriv e "x"); print_newline ();;
2. * 1. + 0. * x + 0.
- : unit = ()
```

## 1.10 Printf formats

There is a `printf` function in the `FORMAT` module (see chapter 2) 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 format string that describes the desired output as a text interspersed with specifiers (for instance `%d`, `%f`). Next, the specifiers are substituted by the following arguments in their order of apparition in the format string:

```rust
# Printf%i + %i is an integer value, %F * %F is a float, %S\n"
3 2 4.5 1. "this is a string";;
3 + 2 is an integer value, 4.5 * 1. is a float, "this is a string"
- : unit = ()
```

The OCaml type system checks that the type of the arguments and the specifiers are compatible. If you pass it an argument of a type that does not correspond to the format specifier, the compiler will display an error message:

```bash
# Printf準printf "Float value: %F" 42;;
Error: The constant 42 has type int but an expression was expected of type
       float
Hint: Did you mean 42.?
```

The `fprintf` function is like `printf` except that it takes an output channel as the first argument. The `%a` specifier can be useful to define custom printers (for custom types). For instance, we can create a printing template that converts an integer argument to signed decimal:

```rust
# let pp_int ppf n = Printf.fprintf ppf "%d" n;;
val pp_int: out_channel -> int -> unit = <fun>

# Printf準printf "Outputting an integer using a custom printer: %a " pp_int 42;;
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:
```h
# let pp_option printer ppf = function
| None -> Printf.fprintf ppf "None"
| Some v -> Printf.fprintf ppf "Some(%a)" printer v;;
val pp_option :
(out_channel -> 'a -> unit) -> out_channel -> 'a option -> unit = <fun>
```

```h
# Printf.fprintf stdout
"The current setting is %a. \nThere is only %a\n"
(pp_option pp_int) (Some 3)
(pp_option pp_int) None
;;
The current setting is Some(3).
There is only None
- : unit = ()
```

If the value of its argument its `None`, the printer returned by `pp_option` prints `None` otherwise it uses the provided printer to print `Some`.

Here is how to rewrite the pretty-printer using `fprintf`:

```h
# let pp_expr ppf expr =
let open_paren prec op_precision output =
    if prec > op_precision then Printf.fprintf output "%s" "(" in
let close_paren prec op_precision output =
    if prec > op_precision then Printf.fprintf output "%s" ")" in
let rec print prec ppf expr =
    match expr with
    | Const c -> Printf.fprintf ppf "%F" c
    | Var v -> Printf.fprintf ppf "%s" v
    | Sum(f, g) ->
        open_paren prec 0 ppf;
        Printf.fprintf ppf "%a + %a" (print 0) f (print 0) g;
        close_paren prec 0 ppf
    | Diff(f, g) ->
        open_paren prec 0 ppf;
        Printf.fprintf ppf "%a - %a" (print 0) f (print 1) g;
        close_paren prec 0 ppf
    | Prod(f, g) ->
        open_paren prec 2 ppf;
        Printf.fprintf ppf "%a * %a" (print 2) f (print 2) g;
        close_paren prec 2 ppf
    | Quot(f, g) ->
        open_paren prec 2 ppf;
        Printf.fprintf ppf "%a / %a" (print 2) f (print 3) g;
        close_paren prec 2 ppf
in print 0 ppf expr;;
```

```h
val pp_expr : out_channel -> expression -> unit = <fun>
```
```h
# let pp_option printer ppf = function
| None -> Printf.fprintf ppf "None"
| Some v -> Printf.fprintf ppf "Some(%a)" printer v;;
val pp_option :
(out_channel -> 'a -> unit) -> out_channel -> 'a option -> unit = <fun>
```

```h
# Printf.fprintf stdout
"The current setting is %a. \nThere is only %a\n"
(pp_option pp_int) (Some 3)
(pp_option pp_int) None
;;
The current setting is Some(3).
There is only None
- : unit = ()
```

If the value of its argument its `None`, the printer returned by `pp_option` prints `None` otherwise it uses the provided printer to print `Some`.

Here is how to rewrite the pretty-printer using `fprintf`:

```h
# let pp_expr ppf expr =
let open_paren prec op_precision output =
    if prec > op_precision then Printf.fprintf output "%s" "(" in
let close_paren prec op_precision output =
    if prec > op_precision then Printf.fprintf output "%s" ")" in
let rec print prec ppf expr =
    match expr with
    | Const c -> Printf.fprintf ppf "%F" c
    | Var v -> Printf.fprintf ppf "%s" v
    | Sum(f, g) ->
        open_paren prec 0 ppf;
        Printf.fprintf ppf "%a + %a" (print 0) f (print 0) g;
        close_paren prec 0 ppf
    | Diff(f, g) ->
        open_paren prec 0 ppf;
        Printf.fprintf ppf "%a - %a" (print 0) f (print 1) g;
        close_paren prec 0 ppf
    | Prod(f, g) ->
        open_paren prec 2 ppf;
        Printf.fprintf ppf "%a * %a" (print 2) f (print 2) g;
        close_paren prec 2 ppf
    | Quot(f, g) ->
        open_paren prec 2 ppf;
        Printf.fprintf ppf "%a / %a" (print 2) f (print 3) g;
        close_paren prec 2 ppf
in print 0 ppf expr;;
```

```h
val pp_expr : out_channel -> expression -> unit = <fun>
```
# pp_expr stdout e; print_newline ();;

2. * x + 1.

- : unit = ()

# pp_expr stdout (deriv e "x"); print_newline ();;

2. * 1. + 0. * x + 0.

- : unit = ()

Due to the way that format strings are built, storing a format string requires an explicit type annotation:

# let str : _ format =

"%i is an integer value, %F is a float, %S
";

# Printf printf str 3 4.5 "string value";;

3 is an integer value, 4.5 is a float, "string value"

- : unit = ()

1.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, which
will be evaluated at runtime in their order of appearance in the source file. Unlike in interactive
mode, types and values are not printed automatically; the program must call printing functions
explicitly to produce some output. The ;; used in the interactive examples is not required in
source files created for use with OCaml compilers, but can be helpful to mark the end of a top-level
expression unambiguously even when there are syntax errors. Here is a sample standalone program
to print the greatest common divisor (gcd) of two numbers:

(* File gcd.ml *)

let rec gcd a b =

if b = 0 then a

else gcd b (a mod b);;

let main () =

let a = int_of_string Sys.argv.(1) in

let b = int_of_string Sys.argv.(2) in

Printf printf "%d
" (gcd a b);

exit 0;

main ();;

Sys.argv is an array of strings containing the command-line parameters. Sys.argv.(1) is thus
the first command-line parameter. The program above is compiled and executed with the following
shell commands:

$ ocamlc -o gcd gcd.ml

$ ./gcd 6 9
# pp_expr stdout e; print_newline ();;

2. * x + 1.

- : unit = ()

# pp_expr stdout (deriv e "x"); print_newline ();;

2. * 1. + 0. * x + 0.

- : unit = ()

Due to the way that format strings are built, storing a format string requires an explicit type annotation:

# let str : _ format =

"%i is an integer value, %F is a float, %S
";

# Printf printf str 3 4.5 "string value";;

3 is an integer value, 4.5 is a float, "string value"

- : unit = ()

1.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, which
will be evaluated at runtime in their order of appearance in the source file. Unlike in interactive
mode, types and values are not printed automatically; the program must call printing functions
explicitly to produce some output. The ;; used in the interactive examples is not required in
source files created for use with OCaml compilers, but can be helpful to mark the end of a top-level
expression unambiguously even when there are syntax errors. Here is a sample standalone program
to print the greatest common divisor (gcd) of two numbers:

(* File gcd.ml *)

let rec gcd a b =

if b = 0 then a

else gcd b (a mod b);;

let main () =

let a = int_of_string Sys.argv.(1) in

let b = int_of_string Sys.argv.(2) in

Printf printf "%d
" (gcd a b);

exit 0;

main ();;

Sys.argv is an array of strings containing the command-line parameters. Sys.argv.(1) is thus
the first command-line parameter. The program above is compiled and executed with the following
shell commands:

$ ocamlc -o gcd gcd.ml

$ ./gcd 6 9
34

3

$ ./gcd 7 11

1

More complex standalone OCaml programs are typically composed of multiple source files, and
can link with precompiled libraries. Chapters 13 and 16 explain how to use the batch compilers
ocamlc and ocamlopt. Recompilation of multi-file OCaml projects can be automated using third-
party build systems, such as dune.
3
$ ./gcd 7 11
1

More complex standalone OCaml programs are typically composed of multiple source files, and can
link with precompiled libraries. Chapters 13 and 16 explain how to use the batch compilers ocamlc
and ocamlopt. Recompilation of multi-file OCaml projects can be automated using third-party
build systems, such as dune.
# Chapter 2

## The module system

This chapter introduces the module system of OCaml.

### 2.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 called a *structure* and is introduced by the `struct...end` construct, which contains an arbitrary sequence of definitions. The structure is usually given a name with the `module` binding. For instance, here is a structure packaging together a type of FIFO queues and their operations:

``` OCaml
# module Fifo =
struct
    type 'a queue = { front: 'a list; rear: 'a list }
    let make front rear =
        match front with
        | [] -> { front = List.rev rear; rear = [] }
        | _ -> { front; rear }
    let empty = { front = []; rear = [] }
    let is_empty = function { front = []; _ } -> true | _ -> false
    let add x q = make q.front (x :: q.rear)
    exception Empty
    let top = function
        | { front = []; _ } -> raise Empty
        | { front = x :: _; _ } -> x
    let pop = function
        | { front = []; _ } -> raise Empty
        | { front = _ :: f; rear = r } -> make f r
end;

module Fifo :
sig
    type 'a queue = { front : 'a list; rear : 'a list; }
```
# Chapter 2

## The module system

This chapter introduces the module system of OCaml.

### 2.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 called a *structure* and is introduced by the `struct...end` construct, which contains an arbitrary sequence of definitions. The structure is usually given a name with the `module` binding. For instance, here is a structure packaging together a type of FIFO queues and their operations:

``` OCaml
# module Fifo =
struct
    type 'a queue = { front: 'a list; rear: 'a list }
    let make front rear =
        match front with
        | [] -> { front = List.rev rear; rear = [] }
        | _ -> { front; rear }
    let empty = { front = []; rear = [] }
    let is_empty = function { front = []; _ } -> true | _ -> false
    let add x q = make q.front (x :: q.rear)
    exception Empty
    let top = function
        | { front = []; _ } -> raise Empty
        | { front = x :: _; _ } -> x
    let pop = function
        | { front = []; _ } -> raise Empty
        | { front = _ :: f; rear = r } -> make f r
end;

module Fifo :
sig
    type 'a queue = { front : 'a list; rear : 'a list; }
```
```kotlin
val make : 'a list -> 'a list -> 'a queue
val empty : 'a queue
val is_empty : 'a queue -> bool
val add : 'a -> 'a queue -> 'a queue
exception Empty
val top : 'a queue -> 'a
val pop : 'a queue -> 'a queue
end
```

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`.

```kotlin
# Fifo.add "hello" Fifo.empty;;
- : string Fifo.queue = {Fifo.front = ["hello"); rear = []}
```

Another possibility is to open the module, which brings all identifiers defined inside the module into the scope of the current structure.

```kotlin
# open Fifo;;
# add "hello" empty;;
- : string Fifo.queue = {front = ["hello"); rear = []}
```

Opening a module enables lighter access to its components, at the cost of making it harder to identify in which module an identifier has been defined. In particular, opened modules can shadow identifiers present in the current scope, potentially leading to confusing errors:

```kotlin
# let empty = []
open Fifo;;
val empty : 'a list = []

# let x = 1 :: empty ;;

Error: This expression has type 'a Fifo.queue
but an expression was expected of type int list
```

A partial solution to this conundrum is to open modules locally, making the components of the module available only in the concerned expression. This can also make the code both easier to read (since the open statement is closer to where it is used) and easier to refactor (since the code fragment is more self-contained). Two constructions are available for this purpose:

```kotlin
# let open Fifo in
add "hello" empty;;
- : string Fifo.queue = {front = ["hello"); rear = []}
```

and

```kotlin
# 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,
```kotlin
val make : 'a list -> 'a list -> 'a queue
val empty : 'a queue
val is_empty : 'a queue -> bool
val add : 'a -> 'a queue -> 'a queue
exception Empty
val top : 'a queue -> 'a
val pop : 'a queue -> 'a queue
end
```

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`.

```kotlin
# Fifo.add "hello" Fifo.empty;;
- : string Fifo.queue = {Fifo.front = ["hello"); rear = []}
```

Another possibility is to open the module, which brings all identifiers defined inside the module into the scope of the current structure.

```kotlin
# open Fifo;;
# add "hello" empty;;
- : string Fifo.queue = {front = ["hello"); rear = []}
```

Opening a module enables lighter access to its components, at the cost of making it harder to identify in which module an identifier has been defined. In particular, opened modules can shadow identifiers present in the current scope, potentially leading to confusing errors:

```kotlin
# let empty = []
open Fifo;;
val empty : 'a list = []

# let x = 1 :: empty ;;

Error: The value empty has type 'a Fifo.queue
but an expression was expected of type int list
```

A partial solution to this conundrum is to open modules locally, making the components of the module available only in the concerned expression. This can also make the code both easier to read (since the open statement is closer to where it is used) and easier to refactor (since the code fragment is more self-contained). Two constructions are available for this purpose:

```kotlin
# let open Fifo in
add "hello" empty;;
- : string Fifo.queue = {front = ["hello"); rear = []}
```

and

```kotlin
# 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,
```h
# Fifo. [empty] = Fifo. ([empty]);
- : bool = true
```

```h
# Fifo. [|empty|] = Fifo. ([|empty|]);
- : bool = true
```

```h
# Fifo. { contents = empty } = Fifo. ({ contents = empty });
- : bool = true
```

This second form also works for patterns:

```h
# let at_most_oneElement x = match x with
| Fifo. { front = ([] | [_]); rear = [] } -> true
| _ -> false ;
```

```h
val at_most_oneElement : 'a Fifo.queue -> bool = <fun>
```

It is also possible to copy the components of a module inside another module by using an `include` statement. This can be particularly useful to extend existing modules. As an illustration, we could add functions that return an optional value rather than an exception when the queue is empty.

```h
# module FifoOpt =
struct
  include Fifo
  let top_opt q = if is_empty q then None else Some(top q)
  let pop_opt q = if is_empty q then None else Some(pop q)
end;

module FifoOpt :
sig
  type 'a queue = 'a Fifo.queue = { front : 'a list; rear : 'a list; }
  val make : 'a list -> 'a list -> 'a queue
  val empty : 'a queue
  val is_empty : 'a queue -> bool
  val add : 'a -> 'a queue -> 'a queue
  exception Empty
  val top : 'a queue -> 'a
  val pop : 'a queue -> 'a queue
  val top_opt : 'a queue -> 'a option
  val pop_opt : 'a queue -> 'a queue option
end
```

## 2.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, the signature below specifies the queue operations `empty`, `add`, `top` and `pop`, but not the auxiliary function `make`. Similarly, it makes the `queue` type abstract (by not providing its actual
# Fifo. [empty] = Fifo. ([empty]);

- : bool = true

# Fifo. [|empty|] = Fifo. ([|empty|]);

- : bool = true

# Fifo. { contents = empty } = Fifo. ({ contents = empty });

- : bool = true

This second form also works for patterns:

# let at_most_one_element x = match x with
| Fifo. { front = ([] | [_]); rear = [] } -> true
| _ -> false ;;

val at_most_one_element : 'a Fifo.queue -> bool = <fun>

It is also possible to copy the components of a module inside another module by using an
**include** statement. This can be particularly useful to extend existing modules. As an illustration,
we could add functions that return an optional value rather than an exception when the queue is
empty.

# module FifoOpt =
    struct
        include Fifo
        let top_opt q = if is_empty q then None else Some(top q)
        let pop_opt q = if is_empty q then None else Some(pop q)
    end;

module FifoOpt :
sig
    type 'a queue = 'a Fifo.queue = { front : 'a list; rear : 'a list; }
    val make : 'a list -> 'a list -> 'a queue
    val empty : 'a queue
    val is_empty : 'a queue -> bool
    val add : 'a -> 'a queue -> 'a queue
    exception Empty
    val top : 'a queue -> 'a
    val pop : 'a queue -> 'a queue
    val top_opt : 'a queue -> 'a option
    val pop_opt : 'a queue -> 'a queue option
end

2.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, the signature below specifies the queue operations empty, add, top and pop, but not the
auxiliary function make. Similarly, it makes the queue type abstract (by not providing its actual
representation as a concrete type). This ensures that users of the `Fifo` module cannot violate data structure invariants that operations rely on, such as “if the front list is empty, the rear list must also be empty”.

```python
# module type FIFO =
sig
    type 'a queue              (* now an abstract type *)
    val empty : 'a queue
    val add : 'a -> 'a queue -> 'a queue
    val top : 'a queue -> 'a
    val pop : 'a queue -> 'a queue
    exception Empty
end;

module type FIFO =
sig
    type 'a queue
    val empty : 'a queue
    val add : 'a -> 'a queue -> 'a queue
    val top : 'a queue -> 'a
    val pop : 'a queue -> 'a queue
    exception Empty
end
```

Restricting the `Fifo` structure to this signature results in another view of the `Fifo` structure where the `make` function is not accessible and the actual representation of queues is hidden:

```python
# module AbstractQueue = (Fifo : FIFO);;
module AbstractQueue : FIFO
```

```python
# AbstractQueue.make [1] [2;3] ;;
Error: Unbound value AbstractQueue.make
```

```python
# AbstractQueue.add "hello" AbstractQueue.empty;;
- : string AbstractQueue.queue = <abstr>
```

The restriction can also be performed during the definition of the structure, as in

```python
module Fifo = (struct ... end : FIFO);;
```

An alternate syntax is provided for the above:

```python
module Fifo : FIFO = struct ... end;;
```

Like for modules, it is possible to include a signature to copy its components inside the current signature. For instance, we can extend the `FIFO` signature with the `top_opt` and `pop_opt` functions:

```python
# module type FIFO_WITH_OPT =
sig
    include FIFO
    val top_opt: 'a queue -> 'a option
    val pop_opt: 'a queue -> 'a queue option
end;;
```
representation as a concrete type). This ensures that users of the `Fifo` module cannot violate data structure invariants that operations rely on, such as “if the front list is empty, the rear list must also be empty”.

```python
# module type FIFO =
sig
    type 'a queue              (* now an abstract type *)
    val empty : 'a queue
    val add : 'a -> 'a queue -> 'a queue
    val top : 'a queue -> 'a
    val pop : 'a queue -> 'a queue
    exception Empty
end;

module type FIFO =
sig
    type 'a queue
    val empty : 'a queue
    val add : 'a -> 'a queue -> 'a queue
    val top : 'a queue -> 'a
    val pop : 'a queue -> 'a queue
    exception Empty
end
```

Restricting the `Fifo` structure to this signature results in another view of the `Fifo` structure where the `make` function is not accessible and the actual representation of queues is hidden:

```python
# module AbstractQueue = (Fifo : FIFO);;
module AbstractQueue : FIFO

# AbstractQueue.make [1] [2;3] ;;
Error: Unbound value AbstractQueue.make

# AbstractQueue.add "hello" AbstractQueue.empty;;
- : string AbstractQueue.queue = <abstr>
```

The restriction can also be performed during the definition of the structure, as in

```python
module Fifo = (struct ... end : FIFO);;
```

An alternate syntax is provided for the above:

```python
module Fifo : FIFO = struct ... end;;
```

Like for modules, it is possible to include a signature to copy its components inside the current signature. For instance, we can extend the `FIFO` signature with the `top_opt` and `pop_opt` functions:

```python
# module type FIFO_WITH_OPT =
sig
    include FIFO
    val top_opt: 'a queue -> 'a option
    val pop_opt: 'a queue -> 'a queue option
end;;
```
module type FIFO_WITH_OPT =
sig
type 'a queue
val empty : 'a queue
val add : 'a -> 'a queue -> 'a queue
val top : 'a queue -> 'a
val pop : 'a queue -> 'a queue
exception Empty
val top_opt : 'a queue -> 'a option
val pop_opt : 'a queue -> 'a queue option
end

## 2.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 element type and a comparison function compare (such as OrderedString):

# type comparison = Less | Equal | Greater;;
type comparison = Less | Equal | Greater

# module type ORDERED_TYPE =
sig
type t
val compare: t -> t -> comparison
end;;
module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end

# module Set =
functor (Elt: ORDERED_TYPE) ->
struct
type element = Elt.t
type set = element list
let empty = []
let rec add x s =
match s with
[] -> [x]
| hd::tl ->
match Elt compares with
  Equal -> s (* x is already in s *)
  Less  -> x :: s (* x is smaller than all elements of s *)
  Greater -> hd :: add x tl
let rec member x s =
match s with
[] -> false
module type FIFO_WITH_OPT =
sig
type 'a queue
val empty : 'a queue
val add : 'a -> 'a queue -> 'a queue
val top : 'a queue -> 'a
val pop : 'a queue -> 'a queue
exception Empty
val top_opt : 'a queue -> 'a option
val pop_opt : 'a queue -> 'a queue option
end

## 2.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 element type and a comparison function compare (such as OrderedString):

# type comparison = Less | Equal | Greater;;
type comparison = Less | Equal | Greater

# module type ORDERED_TYPE =
sig
type t
val compare: t -> t -> comparison
end;;
module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end

# module Set =
functor (Elt: ORDERED_TYPE) ->
struct
type element = Elt.t
type set = element list
let empty = []
let rec add x s =
match s with
[] -> [x]
| hd::tl ->
match Elt compares with
  Equal -> s (* x is already in s *)
  Less  -> x :: s (* x is smaller than all elements of s *)
  Greater -> hd :: add x tl
let rec member x s =
match s with
[] -> false
```hkl
| hd::tl ->
  match Elt compares x hd with
    Equal -> true (* x belongs to s *)
  | Less  -> false (* x is smaller than all elements of s *)
  | Greater -> member x tl
end;;

module Set :
  functor (Elt : ORDERED_TYPE) ->
  sig
    type element = Elt.t
    type set = element list
    val empty : 'a list
    val add : Elt.t -> Elt.t list -> Elt.t list
    val member : Elt.t -> Elt.t list -> bool
  end
```

By applying the `Set` functor to a structure implementing an ordered type, we obtain set operations for this type:

```hkl
# module OrderedString =
  struct
    type t = string
    let compare x y = if x = y then Equal else if x < y then Less else Greater
  end;;
```

```hkl
module OrderedString :
  sig
    type t = string val compare : 'a -> 'a -> comparison end
```

```hkl
# module StringSet = Set OrderedString;;
```

```hkl
module StringSet :
  sig
    type element = OrderedString.t
    type set = element list
    val empty : 'a list
    val add : OrderedString.t -> OrderedString.t list -> OrderedString.t list
    val member : OrderedString.t -> OrderedString.t list -> bool
  end
```

```hkl
# StringSet member "bar" (StringSet.add "foo" StringSet.empty);;
- : bool = false
```

## 2.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 achieved by restricting `Set` by a suitable functor signature:

```hkl
# module type SETFUNCTOR =
```
```hkl
| hd::tl ->
  match Elt compares x hd with
    Equal -> true (* x belongs to s *)
  | Less  -> false (* x is smaller than all elements of s *)
    | Greater -> member x tl
end;;

module Set :
  (Elt : ORDERED_TYPE) ->
  sig
    type element = Elt.t
    type set = element list
    val empty : 'a list
    val add : Elt.t -> Elt.t list -> Elt.t list
    val member : Elt.t -> Elt.t list -> bool
  end
```

By applying the `Set` functor to a structure implementing an ordered type, we obtain set operations for this type:

```hkl
# 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

# module StringSet = Set OrderedString);;
module StringSet :
  sig
    type element = OrderedString.t
    type set = element list
    val empty : 'a list
    val add : OrderedString.t -> OrderedString.t list -> OrderedString.t list
    val member : OrderedString.t -> OrderedString.t list -> bool
  end
```

```hkl
# StringSet member "bar" (StringSet.add "foo" StringSet.empty);;
- : bool = false
```

## 2.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 achieved by restricting `Set` by a suitable functor signature:

```hkl
# module type SETFUNCTOR =
```
functor (Elt: ORDERED_TYPE) ->
sig
    type element = Elt.t (* concrete *)
    type set (* abstract *)
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
end;;

module type SETFUNCTOR =
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

# AbstractStringSet.add "gee" AbstractStringSet.empty;;
- : AbstractStringSet.set = <abstr>

In an attempt to write the type constraint above more elegantly, one may wish to name the
signature of the structure returned by the functor, then use that signature in the constraint:

# module type SET =
sig
    type element
    type set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
end;;

module type SET =
sig
    type element
    type set
(Elt: ORDERED_TYPE) ->
sig
type element = Elt.t (* concrete *)
type set (* abstract *)
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end;;
module type SETFUNCTOR =
(Elt : ORDERED_TYPE) ->
sig
type element = Elt.t
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end

# AbstractStringSet.add "gee" AbstractStringSet.empty;;
- : AbstractStringSet.set = <abstr>

In an attempt to write the type constraint above more elegantly, one may wish to name the
signature of the structure returned by the functor, then use that signature in the constraint:

# module type SET =
sig
type element
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end;;
module type SET =
sig
type element
type set
```h
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```

```h
# module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);;
```

```h
module WrongSet : functor (Elt : ORDERED_TYPE) -> SET
```

```h
# module WrongStringSet = WrongSet(OrderedString);;
```

```h
module WrongStringSet :
```

```h
sig
    type element = WrongSet(OrderedString).element
    type set = WrongSet(OrderedString).set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
end
```

```h
# WrongStringSet.add "gee" WrongStringSet.empty ;;
```

```
Error: This expression has type string but an expression was expected of type
        WrongStringSet.element = WrongSet(OrderedString).element
```

The problem here is that `SET` specifies the type `element` abstractly, so that the type equality between `element` in the result of the functor and `t` in its argument is forgotten. Consequently, `WrongStringSet.element` is not the same type as `string`, and the operations of `WrongStringSet` cannot be applied to strings. As demonstrated above, it is important that the type `element` in the signature `SET` be declared equal to `Elt.t`; unfortunately, this is impossible above since `SET` is defined in a context where `Elt` does not exist. To overcome this difficulty, OCaml provides a `with type` construct over signatures that allows enriching a signature with extra type equalities:

```h
# module AbstractSet2 =
    (Set : functor(Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));;
```

```h
module AbstractSet2 :
    functor (Elt : ORDERED_TYPE) ->
```

```h
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 their result:

```h
module AbstractSet2(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) =
    struct ... end;
```

Abstracting a type component in a functor result is a powerful technique that provides a high degree of type safety, as we now illustrate. Consider an ordering over character strings that is
```hkl
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
```

```hkl
# module WrongSet = (Set : (Elt: ORDERED_TYPE) -> SET);;
```

```hkl
module WrongSet : (Elt : ORDERED_TYPE) -> SET
```

```hkl
# module WrongStringSet = WrongSet(OrderedString);;
```

```hkl
module WrongStringSet :
```

```hkl
sig
    type element = WrongSet(OrderedString).element
    type set = WrongSet(OrderedString).set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
end
```

```hkl
# WrongStringSet.add "gee" WrongStringSet.empty ;;
```

```
Error: This constant has type string but an expression was expected of type
       WrongStringSet.element = WrongSet(OrderedString).element
```

The problem here is that `SET` specifies the type `element` abstractly, so that the type equality between `element` in the result of the functor and `t` in its argument is forgotten. Consequently, `WrongStringSet.element` is not the same type as `string`, and the operations of `WrongStringSet` cannot be applied to strings. As demonstrated above, it is important that the type `element` in the signature `SET` be declared equal to `Elt.t`; unfortunately, this is impossible above since `SET` is defined in a context where `Elt` does not exist. To overcome this difficulty, OCaml provides a `with type` construct over signatures that allows enriching a signature with extra type equalities:

```hkl
# module AbstractSet2 =
    (Set : (Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));
```

```hkl
module AbstractSet2 :
(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 their result:

```hkl
module AbstractSet2(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) =
    struct ... end;
```

Abstracting a type component in a functor result is a powerful technique that provides a high degree of type safety, as we now illustrate. Consider an ordering over character strings that is different
different from the standard ordering implemented in the OrderedString structure. For instance,
we compare strings without distinguishing upper and lower case.

```h
# module NoCaseString =
struct
    type t = string
    let compare s1 s2 =
        OrderedString compares (String.lowercase_ascii s1) (String.lowercase_ascii s2)
end;
```

```h
module NoCaseString :
    sig type t = string val compare : string -> string -> comparison end
```

```h
# module NoCaseStringSet = AbstractSet(NoCaseString);;
```

```h
module NoCaseStringSet :
    sig
        type element = NoCaseString.t
        type set = AbstractSet(NoCaseString).set
        val empty : set
        val add : element -> set -> set
        val member : element -> set -> bool
    end
```

```h
# NoCaseStringSet.add "FOO" AbstractStringSet.empty ;;
```

```
Error: This expression has type
        AbstractStringSet.set = AbstractSet OrderedString.set
but an expression was expected of type
        NoCaseStringSet.set = AbstractSet(NoCaseString).set
```

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 type, and different invariants need to be maintained by the operations (being strictly increasing for the standard ordering and for the case-insensitive ordering). Applying operations from `AbstractStringSet` to values of type `NoCaseStringSet.set` could give incorrect results, or build lists that violate the invariants of `NoCaseStringSet`.

## 2.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 be compiled separately, thus minimizing recompilation after changes.

In OCaml, compilation units are special cases of structures and signatures, and the relationship between the units can be explained easily in terms of the module system. A compilation unit *A* comprises two files:

* the implementation file *A*.ml, which contains a sequence of definitions, analogous to the inside of a struct...end construct;
from the standard ordering implemented in the OrderedString structure. For instance, we compare
strings without distinguishing upper and lower case.

```pascal
# module NoCaseString =
    struct
        type t = string
    let compare s1 s2 =
        OrderedString compares (String.lowercase松 s1) (String.lowercase松 s2)
    end;;
```

```pascal
module NoCaseString :
    sig type t = string val compare : string -> string -> comparison end
```

```pascal
# module NoCaseStringSet = AbstractSet(NoCaseString);;
```

```pascal
module NoCaseStringSet :
    sig
        type element = NoCaseString.t
        type set = AbstractSet(NoCaseString).set
        val empty : set
        val add : element -> set -> set
        val member : element -> set -> bool
    end
```

```pascal
# NoCaseStringSet.add "FOO" AbstractStringSet.empty ;;
```

```pascal
Error: The value AbstractStringSet.empty has type
        AbstractStringSet.set = AbstractSet(OrderedString).set
but an expression was expected of type
        NoCaseStringSet.set = AbstractSet(NoCaseString).set
```

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 type, and different invariants need to be maintained by the operations (being strictly increasing for the standard ordering and for the case-insensitive ordering). Applying operations from `AbstractStringSet` to values of type `NoCaseStringSet.set` could give incorrect results, or build lists that violate the invariants of `NoCaseStringSet`.

## 2.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 be compiled separately, thus minimizing recompilation after changes.

In OCaml, compilation units are special cases of structures and signatures, and the relationship between the units can be explained easily in terms of the module system. A compilation unit *A* comprises two files:

* the implementation file *A*.ml, which contains a sequence of definitions, analogous to the inside of a struct...end construct;
* the interface file `A.mli`, which contains a sequence of specifications, analogous to the inside of a `sig...end` construct.

These two files together define a structure named `A` as if the following definition was entered at top-level:

```hml
module A: sig (* contents of file A.mli *) end
    = struct (* contents of file A.ml *) end;;
```

The files that define the compilation units can be compiled separately using the `ocamlc -c` command (the `-c` option means “compile only, do not try to link”); this produces compiled interface files (with extension `.cmi`) and compiled object code files (with extension `.cmo`). When all units have been compiled, their `.cmo` files are linked together using the `ocamlc` command. For instance, the following commands compile and link a program composed of two compilation units `Aux` and `Main`:

```
$ 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 Aux.cmo Main.cmo
```

The program behaves exactly as if the following phrases were entered at top-level:

```hml
module Aux: sig (* contents of Aux.mli *) end
    = struct (* contents of Aux.ml *) end;;
module Main: sig (* contents of Main.mli *) end
    = struct (* contents of Main.ml *) end;;
```

In particular, `Main` can refer to `Aux`: the definitions and declarations contained in `Main.ml` and `Main.mli` can refer to definition in `Aux.ml`, using the `Aux.ident` notation, provided these definitions are exported in `Aux.mli`.

The order in which the `.cmo` files are given to `ocamlc` during the linking phase determines the order in which the module definitions occur. Hence, in the example above, `Aux` appears first and `Main` can refer to it, but `Aux` cannot refer to `Main`.

Note that only top-level structures can be mapped to separately-compiled files, but neither functors nor module types. However, all module-class objects can appear as components of a structure, so the solution is to put the functor or module type inside a structure, which can then be mapped to a file.
* the interface file `A.mli`, which contains a sequence of specifications, analogous to the inside of a `sig...end` construct.

These two files together define a structure named `A` as if the following definition was entered at top-level:

```hml
module A: sig (* contents of file A.mli *) end
    = struct (* contents of file A.ml *) end;;
```

The files that define the compilation units can be compiled separately using the `ocamlc -c` command (the `-c` option means “compile only, do not try to link”); this produces compiled interface files (with extension `.cmi`) and compiled object code files (with extension `.cmo`). When all units have been compiled, their `.cmo` files are linked together using the `ocamlc` command. For instance, the following commands compile and link a program composed of two compilation units `Aux` and `Main`:

```
$ 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 Aux.cmo Main.cmo
```

The program behaves exactly as if the following phrases were entered at top-level:

```hml
module Aux: sig (* contents of Aux.mli *) end
    = struct (* contents of Aux.ml *) end;;
module Main: sig (* contents of Main.mli *) end
    = struct (* contents of Main.ml *) end;;
```

In particular, `Main` can refer to `Aux`: the definitions and declarations contained in `Main.ml` and `Main.mli` can refer to definition in `Aux.ml`, using the `Aux.ident` notation, provided these definitions are exported in `Aux.mli`.

The order in which the `.cmo` files are given to `ocamlc` during the linking phase determines the order in which the module definitions occur. Hence, in the example above, `Aux` appears first and `Main` can refer to it, but `Aux` cannot refer to `Main`.

Note that only top-level structures can be mapped to separately-compiled files, but neither functors nor module types. However, all module-class objects can appear as components of a structure, so the solution is to put the functor or module type inside a structure, which can then be mapped to a file.
# Chapter 3

## Objects in OCaml

*(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)*

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. Object-oriented features are used much less frequently in OCaml than in those languages. OCaml has alternatives that are often more appropriate, such as modules and functors. Indeed, many OCaml programs do not use objects at all.

### 3.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 = x <- x + d
    end;

class point :
    object val mutable x : int method get_x : int method move : int -> unit end
```

We now create a new point `p`, instance of the `point` class.

``` OCaml
# let p = new point;;
val p : point = <obj>
```

Note that the type of `p` is `point`. This is an abbreviation automatically defined by the class definition above. It stands for the object type `<get_x : int; move : int -> unit>`, listing the methods of class `point` along with their types.

We now invoke some methods of `p`:

``` OCaml
# p#get_x;;
```
# Chapter 3

## Objects in OCaml

*(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)*

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. Object-oriented features are used much less frequently in OCaml than in those languages. OCaml has alternatives that are often more appropriate, such as modules and functors. Indeed, many OCaml programs do not use objects at all.

### 3.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 = x <- x + d
end;;

class point :
  object val mutable x : int method get_x : int method move : int -> unit end
```

We now create a new point `p`, instance of the `point` class.

``` OCaml
# let p = new point;;
val p : point = <obj>
```

Note that the type of `p` is `point`. This is an abbreviation automatically defined by the class definition above. It stands for the object type `<get_x : int; move : int -> unit>`, listing the methods of class `point` along with their types.

We now invoke some methods of `p`:

``` OCaml
# p#get_x;;
```
- : int = 0

# p#move 3;;

- : unit = ()

# p#get_x;;

- : int = 3

The evaluation of the body of a class only takes place at object creation time. Therefore, in the following example, the instance variable x is initialized to different values for two different objects.

# let x0 = ref 0;;

val x0 : int ref = {contents = 0}

# class point =

object

val mutable x = incr x0; !x0

method get_x = x

method move d = x <- x + d

end;;

class point :

object val mutable x : int method get_x : int method move : int -> unit end

# new point#get_x;;

- : int = 1

# new point#get_x;;

- : int = 2

The class point can also be abstracted over the initial values of the x coordinate.

# 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:

# class point x_init =

object

val mutable x = x_init

method get_x = x

method move d = x <- x + d

end;;
- : int = 0

# p#move 3;;

- : unit = ()

# p#get_x;;

- : int = 3

The evaluation of the body of a class only takes place at object creation time. Therefore, in the following example, the instance variable x is initialized to different values for two different objects.

# let x0 = ref 0;;

val x0 : int ref = {contents = 0}

# class point =

object

val mutable x = incr x0; !x0

method get_x = x

method move d = x <- x + d

end;;

class point :

object val mutable x : int method get_x : int method move : int -> unit end

# new point#get_x;;

- : int = 1

# new point#get_x;;

- : int = 2

The class point can also be abstracted over the initial values of the x coordinate.

# 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:

# class point x_init =

object

val mutable x = x_init

method get_x = x

method move d = x <- x + d

end;;
```ocaml
class point :
    int ->
    object val mutable x : int method get_x : int method move : int -> unit end
```

An instance of the class `point` is now a function that expects an initial parameter to create a point object:

``` OCaml
# new point;;
- : int -> point = <fun>
```

``` OCaml
# let p = new point 7;;
val p : point = <obj>
```

The parameter `x_init` is, of course, visible in the whole body of the definition, including methods. For instance, the method `get_offset` in the class below returns the position of the object relative to its initial position.

``` OCaml
# class point x_init =
object
    val mutable x = x_init
    method get_x = x
    method get_offset = x - x_init
    method move d = x <- x + d
end;;

class point :
    int ->
    object
        val mutable x : int
        method get_offset : int
        method get_x : int
        method move : int -> unit
    end
```

Expressions can be evaluated and bound before defining the object body of the class. This is useful to enforce invariants. For instance, points can be automatically adjusted to the nearest point on a grid, as follows:

``` 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
```
```kotlin
class point :
    int ->
    object val mutable x : int method get_x : int method move : int -> unit end
```

An instance of the class `point` is now a function that expects an initial parameter to create a point object:

```kotlin
# new point;;
- : int -> point = <fun>
```

```kotlin
# let p = new point 7;;
val p : point = <obj>
```

The parameter `x_init` is, of course, visible in the whole body of the definition, including methods. For instance, the method `get_offset` in the class below returns the position of the object relative to its initial position.

```kotlin
# class point x_init =
    object
        val mutable x = x_init
        method get_x = x
        method get_offset = x - x_init
        method move d = x <- x + d
end;

class point :
    int ->
    object
        val mutable x : int
        method get_offset : int
        method get_x : int
        method move : int -> unit
end
```

Expressions can be evaluated and bound before defining the object body of the class. This is useful to enforce invariants. For instance, points can be automatically adjusted to the nearest point on a grid, as follows:

```kotlin
# 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
```
```kotlin
method get_x : int
method move : int -> unit
end
```

(One could also raise an exception if the `x_init` coordinate is not on the grid.) In fact, the same effect could be obtained here by calling the definition of class `point` with the value of the `origin`.

```kotlin
# class adjusted_point x_init = point ((x_init / 10) * 10);
class adjusted_point : int -> point
```

An alternate solution would have been to define the adjustment in a special allocation function:

```kotlin
# let newAdjusted_point x_init = new point ((x_init / 10) * 10);
val newAdjusted_point : int -> point = <fun>
```

However, the former pattern is generally more appropriate, since the code for adjustment is part of the definition of the class and will be inherited.

This ability provides class constructors as can be found in other languages. Several constructors can be defined this way to build objects of the same class but with different initialization patterns; an alternative is to use initializers, as described below in section 3.4.

## 3.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.

```kotlin
# let p =
    object
        val mutable x = 0
        method get_x = x
        method move d = x <- x + d
end;

val p : < get_x : int; move : int -> unit > = <obj>

# p#get_x;
- : int = 0

# p#move 3;
- : unit = ()

# p#get_x;
- : int = 3
```

Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment.

```kotlin
# let minmax x y =
    if x < y then object method min = x method max = y end
    else object method min = y method max = x end;
```
``` OCaml
method get_x : int
method move : int -> unit
end
```

(One could also raise an exception if the `x_init` coordinate is not on the grid.) In fact, the same effect could be obtained here by calling the definition of class `point` with the value of the `origin`.

``` OCaml
# class adjusted_point x_init = point ((x_init / 10) * 10);
class adjusted_point : int -> point
```

An alternate solution would have been to define the adjustment in a special allocation function:

``` OCaml
# let new_ADJUSTED_point x_init = new point ((x_init / 10) * 10);
val new_ADJUSTED_point : int -> point = <fun>
```

However, the former pattern is generally more appropriate, since the code for adjustment is part of the definition of the class and will be inherited.

This ability provides class constructors as can be found in other languages. Several constructors can be defined this way to build objects of the same class but with different initialization patterns; an alternative is to use initializers, as described below in section 3.4.

## 3.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.

``` OCaml
# let p =
object
  val mutable x = 0
  method get_x = x
  method move d = x <- x + d
end;

val p : < get_x : int; move : int -> unit > = <obj>

# p#get_x;;
- : int = 0

# p#move 3;;
- : unit = ()

# p#get_x;;
- : int = 3
```

Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment.

``` OCaml
# let minmax x y =
  if x < y then object method min = x method max = y end
  else object method min = y method max = x end;
```
```ocaml
val minmax : 'a -> 'a -> < max : 'a; min : 'a > = <fun>
```

Immediate objects have two weaknesses compared to classes: their types are not abbreviated, and you cannot inherit from them. But these two weaknesses can be advantages in some situations, as we will see in sections 3.3 and 3.10.

## 3.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_init
        method get_x = x
        method move d = x <- x + d
        method print = print_int s#get_x
    end;;

class printable_point :
    int ->
    object
        val mutable x : int
        method get_x : int
        method move : int -> unit
        method print : unit
    end
```

``` OCaml
# let p = new printable_point 7;;
val p : printable_point = <obj>

# p#print;;
7- : unit = ()
```

Dynamically, the variable `s` is bound at the invocation of a method. In particular, when the class `printable_point` is inherited, the variable `s` will be correctly bound to the object of the subclass.

A common problem with `self` is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example.

``` OCaml
# let ints = ref [];;
val ints : '_weak1 list ref = {contents = []}

# class my_int =
    object (self)
        method n = 1
        method register = ints := self :: !ints
    end;;
```
```val minmax: 'a -> 'a -> <max: 'a; min: 'a > = <fun>
```

Immediate objects have two weaknesses compared to classes: their types are not abbreviated, and you cannot inherit from them. But these two weaknesses can be advantages in some situations, as we will see in sections 3.3 and 3.10.

## 3.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`.)

```python
# class printable_point x_init =
object (s)
    val mutable x = x_init
    method get_x = x
    method move d = x <- x + d
    method print = print_int s#get_x
end;

class printable_point :
    int ->
    object
        val mutable x : int
        method get_x : int
        method move : int -> unit
        method print : unit
end
```

```python
# let p = new printable_point 7;;
val p : printable_point = <obj>

# p#print;;
7- : unit = ()
```

Dynamically, the variable `s` is bound at the invocation of a method. In particular, when the class `printable_point` is inherited, the variable `s` will be correctly bound to the object of the subclass.

A common problem with `self` is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example.

```python
# let ints = ref [];;
val ints : '_weak1 list ref = {contents = []}

# class my_int =
object (self)
    method n = 1
    method register = ints := self :: !ints
end ;;
```
```
Error: This expression has type < n : int; register : 'a; .. >
but an expression was expected of type 'weak1
Self type cannot escape its class
```

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 a workaround to this problem. Note however that, since immediate objects are not extensible, the problem does not occur with them.

```python
# let my_int =
    object (self)
    method n = 1
    method register = ints := self :: !ints
end;;

val my_int : < n : int; register : unit > = <obj>
```

## 3.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 variables.

```python
# class printable_point x_init =
    let origin = (x_init / 10) * 10 in
    object (self)
        val mutable x = origin
        method get_x = x
        method move d = x <- x + d
        method print = print_int self#get_x
    initializer print_string "new point at "; self#print; print_newline ()
end;;

class printable_point :
    int ->
    object
        val mutable x : int
        method get_x : int
        method move : int -> unit
        method print : unit
end
```

```python
# let p = new printable_point 17;;
new point at 10
val p : printable_point = <obj>
```

Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section 8.1.
```
Error: The value self has type < n : int; register : 'a; .. >
but an expression was expected of type 'weak1
Self type cannot escape its class
```

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 a workaround to this problem. Note however that, since immediate objects are not extensible, the problem does not occur with them.

```ocaml
# let my_int =
    object (self)
        method n = 1
        method register = ints := self :: !ints
    end;;

val my_int : < n : int; register : unit > = <obj>
```

## 3.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 variables.

```ocaml
# class printable_point x_init =
    let origin = (x_init / 10) * 10 in
    object (self)
        val mutable x = origin
        method get_x = x
        method move d = x <- x + d
        method print = print_int self#get_x
        initializer print_string "new point at "; self#print; print_newline ()
    end;;

class printable_point :
    int ->
    object
        val mutable x : int
        method get_x : int
        method move : int -> unit
        method print : unit
    end

# let p = new printable_point 17;;
new point at 10
val p : printable_point = <obj>
```

Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section 8.1.
## 3.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 type abbreviations (treating virtual methods as other methods.)

```ocaml
# class virtual abstract_point x_init =
    object (self)
        method virtual get_x : int
        method get_offset = self#get_x - x_init
        method virtual move : int -> unit
    end;

class virtual abstract_point :
    int ->
    object
        method get_offset : int
        method virtual get_x : int
        method virtual move : int -> unit
    end
```

```ocaml
# class point x_init =
    object
        inherit abstract_point x_init
        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_offset : int
        method get_x : int
        method move : int -> unit
    end
```

Instance variables can also be declared as virtual, with the same effect as with methods.

```ocaml
# class virtual abstract_point2 =
    object
        val mutable virtual x : int
        method move d = x <- x + d
    end;

class virtual abstract_point2 :
    object val mutable virtual x : int method move : int -> unit end

# class point2 x_init =
    object
```
## 3.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 type abbreviations (treating virtual methods as other methods.)

```kotlin
# class virtual abstract_point x_init =
    object (self)
        method virtual get_x : int
        method get_offset = self#get_x - x_init
        method virtual move : int -> unit
end;

class virtual abstract_point :
    int ->
    object
        method get_offset : int
        method virtual get_x : int
        method virtual move : int -> unit
end
```

```kotlin
# class point x_init =
    object
        inherit abstract_point x_init
        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_offset : int
        method get_x : int
        method move : int -> unit
end
```

Instance variables can also be declared as virtual, with the same effect as with methods.

```kotlin
# class virtual abstract_point2 =
    object
        val mutable virtual x : int
        method move d = x <- x + d
end;

class virtual abstract_point2 :
    object val mutable virtual x : int method move : int -> unit end

# class point2 x_init =
    object
```
```kotlin
    inherit abstract_point2
    val mutable x = x_init
    method get_offset = x - x_init
end;

class point2 :
    int ->
    object
        val mutable x: int
        method get_offset: int
        method move: int -> unit
end
```

## 3.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.

```kotlin
# 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;

class restricted_point :
    int ->
    object
        val mutable x: int
        method bump: unit
        method get_x: int
        method private move: int -> unit
end

# let p = new restricted_point 0;
val p: restricted_point = <obj>

# p#move 10 ;;

Error: This expression has type restricted_point
    It has no method move

# p#bump;,
- : unit = ()
```

Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in OCaml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section 3.17.
```ocaml
    inherit abstract_point2
    val mutable x = x_init
    method get_offset = x - x_init
end;

class point2 :
    int ->
    object
        val mutable x : int
        method get_offset : int
        method move : int -> unit
    end
```

## 3.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.

```csharp
# 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;

class restricted_point :
    int ->
    object
        val mutable x : int
        method bump : unit
        method get_x : int
        method private move : int -> unit
    end

# let p = new restricted_point 0;
val p : restricted_point = <obj>

# p#move 10 ;;

Error: This expression has type restricted_point
    It has no method move

# p#bump;,
- : unit = ()
```

Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in OCaml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section 3.17.
Private methods are inherited (they are by default visible in subclasses), unless they are hidden
by signature matching, as described below.

Private methods can be made public in a subclass.

``` OCaml
# class pointAgain x =
    object (self)
        inherit restricted_point x
        method virtual move : _
    end;

class pointAgain :
    int ->
    object
        val mutable x : int
        method bump : unit
        method get_x : int
        method move : int -> unit
    end
```

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 pointAgain x =
    object (self : < move : _; ..> )
        inherit restricted_point x
    end;

class pointAgain :
    int ->
    object
        val mutable x : int
        method bump : unit
        method get_x : int
        method move : int -> unit
    end
```

The constraint on self's type is requiring a public `move` method, and this is sufficient to override `private`.

One could think that a private method should remain private in a subclass. However, since the method is visible in a subclass, it is always possible to pick its code and define a method of the same name that runs that code, so yet another (heavier) solution would be:

``` OCaml
# class pointAgain x =
    object
        inherit restricted_point x as super
        method move = super#move
    end;

class pointAgain :
    int ->
    object
```
Private methods are inherited (they are by default visible in subclasses), unless they are hidden
by signature matching, as described below.

Private methods can be made public in a subclass.

```java
# class pointAgain x =
    object (self)
        inherit restricted_point x
        method virtual move : _
    end;

class pointAgain :
    int ->
    object
        val mutable x : int
        method bump : unit
        method get_x : int
        method move : int -> unit
end
```

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

```java
# class pointAgain x =
    object (self : < move : _; ..> )
        inherit restricted_point x
    end;

class pointAgain :
    int ->
    object
        val mutable x : int
        method bump : unit
        method get_x : int
        method move : int -> unit
end
```

The constraint on self's type is requiring a public `move` method, and this is sufficient to override `private`.

One could think that a private method should remain private in a subclass. However, since the method is visible in a subclass, it is always possible to pick its code and define a method of the same name that runs that code, so yet another (heavier) solution would be:

```java
# class pointAgain x =
    object
        inherit restricted_point x as super
        method move = super#move
    end;

class pointAgain :
    int ->
    object
```
```pascal
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
```

Of course, private methods can also be virtual. Then, the keywords must appear in this order: `method private virtual`.

## 3.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.

```pascal
# class type restricted_point_type =
  object
    method get_x : int
    method bump : unit
  end;;

class type restricted_point_type =
  object method bump : unit method get_x : int end
```

```pascal
# fun (x : restricted_point_type) -> x;;
  - : restricted_point_type -> restricted_point_type = <fun>
```

In addition to program documentation, class interfaces can be used to constrain the type of a class. Both concrete instance variables and concrete private methods can be hidden by a class type constraint. Public methods and virtual members, however, cannot.

```pascal
# class restricted_point' x = (restricted_point x : restricted_point_type);;
class restricted_point' : int -> restricted_point_type
```

Or, equivalently:

```pascal
# class restricted_point' = (restricted_point : int -> restricted_point_type);;
class restricted_point' : int -> restricted_point_type
```

The interface of a class can also be specified in a module signature, and used to restrict the inferred signature of a module.

```python
# module type POINT = sig
  class restricted_point' : int ->
    object
      method get_x : int
      method bump : unit
    end
  end;;

module type POINT =
  sig
    class restricted_point' :
```
``` OCaml
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
```

Of course, private methods can also be virtual. Then, the keywords must appear in this order:
`method private virtual`.

## 3.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;;

class type restricted_point_type =
    object method bump : unit method get_x : int end
```

``` OCaml
# fun (x : restricted_point_type) -> x;;
- : restricted_point_type -> restricted_point_type = <fun>
```

In addition to program documentation, class interfaces can be used to constrain the type of a
class. Both concrete instance variables and concrete private methods can be hidden by a class type
constraint. Public methods and virtual members, however, cannot.

``` OCaml
# class restricted_point' x = (restricted_point x : restricted_point_type);;
class restricted_point' : int -> restricted_point_type
```

Or, equivalently:

``` OCaml
# class restricted_point' = (restricted_point : int -> restricted_point_type);;
class restricted_point' : int -> restricted_point_type
```

The interface of a class can also be specified in a module signature, and used to restrict the inferred
signature of a module.

``` OCaml
# module type POINT = sig
    class restricted_point' : int ->
        object
            method get_x : int
            method bump : unit
        end
end;;

module type POINT =
    sig
        class restricted_point' :
```
```ocaml
int -> object method bump : unit method get_x : int end
end

# module Point : POINT = struct
    class restricted_point' = restricted_point
end;;

module Point : POINT
```

## 3.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 c = c
        method color = c
    end;;

class colored_point :
    int ->
    string ->
    object
        val c : string
        val mutable x : int
        method color : string
        method get_offset : int
        method get_x : int
        method move : int -> unit
    end

# let p' = new colored_point 5 "red";;
val p' : colored_point = <obj>

# p'#get_x, p'#color;;
- : int * string = (5, "red")
```

A point and a colored point have incompatible types, since a point has no method `color`. However, the function `get_x` below is a generic function applying method `get_x` to any object `p` that has this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it applies to both points and colored points.

```ocaml
# let get SUCC_x p = p#get_x + 1;;
val get_succ_x : < get_x : int; .. > -> int = <fun>

# get_succ_x p + get_succ_x p';;
- : int = 8
```
```pascal
int -> object method bump : unit method get_x : int end
end

# module Point : POINT = struct
class restricted_point' = restricted_point
end;;

module Point : POINT
```

## 3.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`.

```pascal
# class colored_point x (c : string) =
object
    inherit point x
    val c = c
    method color = c
end;;

class colored_point :
    int ->
    string ->
    object
        val c : string
        val mutable x : int
        method color : string
        method get_offset : int
        method get_x : int
        method move : int -> unit
end

# let p' = new colored_point 5 "red";;
val p' : colored_point = <obj>

# p'#get_x, p'#color;;
- : int * string = (5, "red")
```

A point and a colored point have incompatible types, since a point has no method `color`. However, the function `get S ucc_x` below is a generic function applying method `get_x` to any object `p` that has this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it applies to both points and colored points.

```pascal
# let get_succ_x p = p#get_x + 1;;
val get_succ_x : < get_x : int; .. > -> int = <fun>

# get_succ_x p + get_succ_x p';;
- : int = 8
```
Methods need not be declared previously, as shown by the example:

```kotlin
# let set_x p = p#set_x;;
val set_x : < set_x : 'a; .. > -> 'a = <fun>

# let incr p = set_x p (get_x p);;
val incr : < get_x : int; set_x : int -> 'a; .. > -> 'a = <fun>
```

## 3.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, **super** is bound to the ancestor **printable_point**. The name **super** is a pseudo value identifier that can only be used to invoke a super-class method, as in **super#print**.

```kotlin
# class printable_colored_point y c =
    object (self)
        val c = c
        method color = c
        inherit printable_point y as super
        method! print =
            print_string "(";
            super#print;
            print_string ", ";
            print_string (self#color);
            print_string ")"
        end;

class printable_colored_point :
    int ->
    string ->
    object
        val c : string
        val mutable x : int
        method color : string
        method get_x : int
        method move : int -> unit
        method print : unit
    end

# let p' = new printable_colored_point 17 "red";;
new point at (10, red)
val p' : printable_colored_point = <obj>

# p'#print;;
(10, red)-: unit = ()
```
Methods need not be declared previously, as shown by the example:

```ocaml
# let set_x p = p#set_x;;
val set_x : < set_x : 'a; .. > -> 'a = <fun>

# let incr p = set_x p (get_x p);;
val incr : < get_x : int; set_x : int -> 'a; .. > -> 'a = <fun>
```

## 3.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, **super** is bound to the ancestor **printable_point**. The name **super** is a pseudo value identifier that can only be used to invoke a super-class method, as in **super#print**.

```ocaml
# class printable_colored_point y c =
object (self)
  val c = c
  method color = c
  inherit printable_point y as super
  method! print =
    print_string "(";
    super#print;
    print_string ", ";
    print_string (self#color);
    print_string ")"
end;

class printable_colored_point :
  int ->
  string ->
  object
    val c : string
    val mutable x : int
    method color : string
    method get_x : int
    method move : int -> unit
    method print : unit
  end

# let p' = new printable_colored_point 17 "red";;
new point at (10, red)
val p' : printable_colored_point = <obj>

# p'#print;;
(10, red)-: unit = ()
```
A private method that has been hidden in the parent class is no longer visible, and is thus not overridden. Since initializers are treated as private methods, all initializers along the class hierarchy are evaluated, in the order they are introduced.

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
    method! m = ()
end;;
```

```
Error: The method `m` has no previous definition
```

This explicit overriding annotation also works for `val` and `inherit`:

``` OCaml
# class another_printable_colored_point y c c' =
    object (self)
        inherit printable_point y
        inherit! printable_colored_point y c
        val! c = c'
    end;;
```

``` OCaml
class another_printable_colored_point :
    int ->
    string ->
    string ->
    object
        val c : string
        val mutable x : int
        method color : string
        method get_x : int
        method move : int -> unit
        method print : unit
    end
```

## 3.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
```
A private method that has been hidden in the parent class is no longer visible, and is thus not overridden. Since initializers are treated as private methods, all initializers along the class hierarchy are evaluated, in the order they are introduced.

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:

```kotlin
# object
  method! m = ()
end;
```

```
Error: The method m has no previous definition
```

This explicit overriding annotation also works for `val` and `inherit`:

```kotlin
# class another_printable_colored_point y c c' =
  object (self)
  inherit printable_point y
  inherit! printable_colored_point y c
  val! c = c'
end;
```

```kotlin
class another_printable_colored_point :
  int ->
  string ->
  string ->
  object
    val c : string
    val mutable x : int
    method color : string
    method get_x : int
    method move : int -> unit
    method print : unit
end
```

## 3.10 Parameterized classes

Reference cells can be implemented as objects. The naive definition fails to typecheck:

```kotlin
# 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
```
```kotlin
method get : 'a
method set : 'a -> unit
end

The method get has type 'a where 'a is unbound
```

The reason is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus either the class should be parametric, or the method type should be constrained to a monomorphic type. A monomorphic instance of the class could be defined by:

```kotlin
# class oref (x_init:int) =
object
    val mutable x = x_init
    method get = x
    method set y = x <- y
end;

class oref :
    int ->
    object val mutable x : int method get : int method set : int -> unit end
```

Note that since immediate objects do not define a class type, they have no such restriction.

```kotlin
# let new_oref x_init =
object
    val mutable x = x_init
    method get = x
    method set y = x <- y
end;

val new_oref : 'a -> < get : 'a; set : 'a -> unit > = <fun>
```

On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are listed between `[` and `]`. The type parameters must also be bound somewhere in the class body by a type constraint.

```kotlin
# class ['a] oref x_init =
object
    val mutable x = (x_init : 'a)
    method get = x
    method set y = x <- y
end;

class ['a] oref :
    'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end

# 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 actual value of the type parameter is displayed in the `constraint` clause.

```kotlin
# class ['a] oref (x_init:'a) =
object
```
``` OCaml
method get : 'a
method set : 'a -> unit
end
```

The method `get` has type `'a` where `'a` is unbound

The reason is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus either the class should be parametric, or the method type should be constrained to a monomorphic type. A monomorphic instance of the class could be defined by:

``` OCaml
# class oref (x_init:int) =
object
  val mutable x = x_init
  method get = x
  method set y = x <- y
end;;

class oref :
  int ->
  object val mutable x : int method get : int method set : int -> unit end
```

Note that since immediate objects do not define a class type, they have no such restriction.

``` OCaml
# let new_oref x_init =
object
  val mutable x = x_init
  method get = x
  method set y = x <- y
end;;
val new_oref : 'a -> < get : 'a; set : 'a -> unit > = <fun>
```

On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are listed between `[` and `]`. The type parameters must also be bound somewhere in the class body by a type constraint.

``` OCaml
# class ['a] oref x_init =
object
  val mutable x = (x_init : 'a)
  method get = x
  method set y = x <- y
end;;

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
```

``` OCaml
# class ['a] oref (x_init:'a) =
object
```
```ocaml
val mutable x = x_init + 1
method get = x
method set y = x <- y
end;

class ['a] oref :
  'a ->
object
  constraint 'a = int
  val mutable x : int
  method get : int
  method set : int -> unit
end
```

Let us consider a more complex example: define a circle, whose center may be any kind of point. We put an additional type constraint in method `move`, since no free variables must remain unaccounted for by the class type parameters.

```ocaml
# class ['a] circle (c : 'a) =
object
  val mutable center = c
  method center = center
  method set_center c = center <- c
  method move = (center#move : int -> unit)
end;

class ['a] circle :
  'a ->
object
  constraint 'a = < move : int -> unit; .. >
  val mutable center : 'a
  method center : 'a
  method move : int -> unit
  method set_center : 'a -> unit
end
```

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 subclass of class `point`. It actually expands to `< get_x : int; move : int -> unit; .. >`. This leads to the following alternate definition of `circle`, which has slightly stronger constraints on its argument, as we now expect `center` to have a method `get_x`.

```ocaml
# class ['a] circle (c : 'a) =
object
  constraint 'a = #point
  val mutable center = c
  method center = center
  method set_center c = center <- c
  method move = center#move
end;
```