The Ocaml System Release 4.09

Total Page:16

File Type:pdf, Size:1020Kb

The Ocaml System Release 4.09 The OCaml system release 4.09 Documentation and user's manual Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier R´emy and J´er^ome Vouillon September 11, 2019 Copyright © 2019 Institut National de Recherche en Informatique et en Automatique 2 Contents I An introduction to OCaml 11 1 The core language 13 1.1 Basics........................................... 13 1.2 Data types......................................... 14 1.3 Functions as values.................................... 16 1.4 Records and variants................................... 16 1.5 Imperative features.................................... 21 1.6 Exceptions......................................... 23 1.7 Lazy expressions...................................... 25 1.8 Symbolic processing of expressions........................... 26 1.9 Pretty-printing...................................... 27 1.10 Printf formats....................................... 28 1.11 Standalone OCaml programs............................... 31 2 The module system 33 2.1 Structures......................................... 33 2.2 Signatures......................................... 36 2.3 Functors.......................................... 37 2.4 Functors and type abstraction.............................. 38 2.5 Modules and separate compilation............................ 41 3 Objects in OCaml 43 3.1 Classes and objects.................................... 43 3.2 Immediate objects..................................... 46 3.3 Reference to self...................................... 47 3.4 Initializers......................................... 48 3.5 Virtual methods...................................... 48 3.6 Private methods...................................... 50 3.7 Class interfaces...................................... 52 3.8 Inheritance......................................... 53 3.9 Multiple inheritance.................................... 53 3.10 Parameterized classes................................... 55 3.11 Polymorphic methods................................... 58 3.12 Using coercions...................................... 61 3.13 Functional objects..................................... 65 1 2 3.14 Cloning objects...................................... 66 3.15 Recursive classes..................................... 68 3.16 Binary methods...................................... 69 3.17 Friends........................................... 71 4 Labels and variants 73 4.1 Labels........................................... 73 4.2 Polymorphic variants................................... 79 5 Polymorphism and its limitations 83 5.1 Weak polymorphism and mutation........................... 83 5.2 Polymorphic recursion.................................. 88 5.3 Higher-rank polymorphic functions........................... 91 6 Advanced examples with classes and modules 93 6.1 Extended example: bank accounts............................ 93 6.2 Simple modules as classes................................ 99 6.3 The subject/observer pattern.............................. 104 II The OCaml language 109 7 The OCaml language 111 7.1 Lexical conventions.................................... 111 7.2 Values........................................... 116 7.3 Names........................................... 118 7.4 Type expressions..................................... 121 7.5 Constants......................................... 124 7.6 Patterns.......................................... 125 7.7 Expressions........................................ 130 7.8 Type and exception definitions.............................. 144 7.9 Classes........................................... 147 7.10 Module types (module specifications).......................... 153 7.11 Module expressions (module implementations)..................... 158 7.12 Compilation units..................................... 161 8 Language extensions 163 8.1 Recursive definitions of values.............................. 163 8.2 Recursive modules..................................... 164 8.3 Private types........................................ 166 8.4 Local opens for patterns................................. 168 8.5 Locally abstract types.................................. 169 8.6 First-class modules.................................... 170 8.7 Recovering the type of a module............................. 172 8.8 Substituting inside a signature.............................. 173 8.9 Type-level module aliases................................. 175 3 8.10 Overriding in open statements.............................. 176 8.11 Generalized algebraic datatypes............................. 177 8.12 Syntax for Bigarray access................................ 182 8.13 Attributes......................................... 183 8.14 Extension nodes...................................... 189 8.15 Extensible variant types................................. 191 8.16 Generative functors.................................... 193 8.17 Extension-only syntax.................................. 194 8.18 Inline records....................................... 195 8.19 Documentation comments................................ 196 8.20 Extended indexing operators.............................. 199 8.21 Empty variant types................................... 199 8.22 Alerts........................................... 200 8.23 Generalized open statements............................... 201 8.24 Binding operators.................................... 203 III The OCaml tools 207 9 Batch compilation (ocamlc) 209 9.1 Overview of the compiler................................. 209 9.2 Options........................................... 210 9.3 Modules and the file system............................... 222 9.4 Common errors...................................... 223 9.5 Warning reference..................................... 226 10 The toplevel system or REPL (ocaml) 229 10.1 Options........................................... 230 10.2 Toplevel directives..................................... 237 10.3 The toplevel and the module system.......................... 240 10.4 Common errors...................................... 240 10.5 Building custom toplevel systems: ocamlmktop ..................... 240 10.6 The native toplevel: ocamlnat (experimental)..................... 241 11 The runtime system (ocamlrun) 243 11.1 Overview.......................................... 243 11.2 Options........................................... 244 11.3 Dynamic loading of shared libraries........................... 246 11.4 Common errors...................................... 247 12 Native-code compilation (ocamlopt) 249 12.1 Overview of the compiler................................. 249 12.2 Options........................................... 250 12.3 Common errors...................................... 262 12.4 Running executables produced by ocamlopt...................... 263 12.5 Compatibility with the bytecode compiler....................... 263 4 13 Lexer and parser generators (ocamllex, ocamlyacc) 265 13.1 Overview of ocamllex .................................. 265 13.2 Syntax of lexer definitions................................ 266 13.3 Overview of ocamlyacc .................................. 271 13.4 Syntax of grammar definitions.............................. 271 13.5 Options........................................... 274 13.6 A complete example.................................... 275 13.7 Common errors...................................... 276 14 Dependency generator (ocamldep) 279 14.1 Options........................................... 279 14.2 A typical Makefile..................................... 281 15 The browser/editor (ocamlbrowser) 285 16 The documentation generator (ocamldoc) 287 16.1 Usage............................................ 287 16.2 Syntax of documentation comments........................... 294 16.3 Custom generators.................................... 303 16.4 Adding command line options.............................. 306 17 The debugger (ocamldebug) 307 17.1 Compiling for debugging................................. 307 17.2 Invocation......................................... 307 17.3 Commands......................................... 308 17.4 Executing a program................................... 309 17.5 Breakpoints........................................ 312 17.6 The call stack....................................... 312 17.7 Examining variable values................................ 313 17.8 Controlling the debugger................................. 314 17.9 Miscellaneous commands................................. 317 17.10 Running the debugger under Emacs........................... 317 18 Profiling (ocamlprof) 319 18.1 Compiling for profiling.................................. 319 18.2 Profiling an execution................................... 320 18.3 Printing profiling information.............................. 320 18.4 Time profiling....................................... 321 19 The ocamlbuild compilation manager 323 20 Interfacing C with OCaml 325 20.1 Overview and compilation information......................... 325 20.2 The value type...................................... 332 20.3 Representation of OCaml data types.......................... 333 20.4 Operations on values................................... 336 5 20.5 Living in harmony with the garbage collector..................... 339 20.6 A complete example.................................... 343 20.7 Advanced topic: callbacks from C to OCaml...................... 347 20.8 Advanced example with callbacks............................ 352 20.9 Advanced topic: custom blocks............................
Recommended publications
  • Eff Directly in Ocaml
    Eff Directly in OCaml Oleg Kiselyov KC Sivaramakrishnan Tohoku University, Japan University of Cambridge, UK [email protected] [email protected] The language Eff is an OCaml-like language serving as a prototype implementation of the theory of algebraic effects, intended for experimentation with algebraic effects on a large scale. We present the embedding of Eff into OCaml, using the library of delimited continuations or the multicore OCaml branch. We demonstrate the correctness of the embedding denotationally, re- lying on the tagless-final–style interpreter-based denotational semantics, including the novel, direct denotational semantics of multi-prompt delimited control. The embedding is systematic, lightweight, performant and supports even higher-order, ‘dynamic’ effects with their polymorphism. OCaml thus may be regarded as another implementation of Eff, broadening the scope and appeal of that language. 1 Introduction Algebraic effects [33, 32] are becoming a more and more popular approach for expressing and com- posing computational effects. There are implementations of algebraic effects in Haskell [18, 22], Idris [4], OCaml [10, 18], Koka [27], Scala1, Javascript2, PureScript3, and other languages. The most direct embodiment of algebraic effect theory is the language Eff4 “built to test the mathematical ideas of alge- braic effects in practice”. It is an OCaml-like language with the native facilities (syntax, type system) to declare effects and their handlers [2]. It is currently implemented as an interpreter, with an optimizing compiler to OCaml in the works. Rather than compile Eff to OCaml, we embed it. After all, save for algebraic effects, Eff truly is a subset of OCaml and can be interpreted or compiled as a regular OCaml code.
    [Show full text]
  • Presentation on Ocaml Internals
    OCaml Internals Implementation of an ML descendant Theophile Ranquet Ecole Pour l’Informatique et les Techniques Avancées SRS 2014 [email protected] November 14, 2013 2 of 113 Table of Contents Variants and subtyping System F Variants Type oddities worth noting Polymorphic variants Cyclic types Subtyping Weak types Implementation details α ! β Compilers Functional programming Values Why functional programming ? Allocation and garbage Combinatory logic : SKI collection The Curry-Howard Compiling correspondence Type inference OCaml and recursion 3 of 113 Variants A tagged union (also called variant, disjoint union, sum type, or algebraic data type) holds a value which may be one of several types, but only one at a time. This is very similar to the logical disjunction, in intuitionistic logic (by the Curry-Howard correspondance). 4 of 113 Variants are very convenient to represent data structures, and implement algorithms on these : 1 d a t a t y p e tree= Leaf 2 | Node of(int ∗ t r e e ∗ t r e e) 3 4 Node(5, Node(1,Leaf,Leaf), Node(3, Leaf, Node(4, Leaf, Leaf))) 5 1 3 4 1 fun countNodes(Leaf)=0 2 | countNodes(Node(int,left,right)) = 3 1 + countNodes(left)+ countNodes(right) 5 of 113 1 t y p e basic_color= 2 | Black| Red| Green| Yellow 3 | Blue| Magenta| Cyan| White 4 t y p e weight= Regular| Bold 5 t y p e color= 6 | Basic of basic_color ∗ w e i g h t 7 | RGB of int ∗ i n t ∗ i n t 8 | Gray of int 9 1 l e t color_to_int= function 2 | Basic(basic_color,weight) −> 3 l e t base= match weight with Bold −> 8 | Regular −> 0 in 4 base+ basic_color_to_int basic_color 5 | RGB(r,g,b) −> 16 +b+g ∗ 6 +r ∗ 36 6 | Grayi −> 232 +i 7 6 of 113 The limit of variants Say we want to handle a color representation with an alpha channel, but just for color_to_int (this implies we do not want to redefine our color type, this would be a hassle elsewhere).
    [Show full text]
  • An Overview of the Scala Programming Language
    An Overview of the Scala Programming Language Second Edition Martin Odersky, Philippe Altherr, Vincent Cremet, Iulian Dragos Gilles Dubochet, Burak Emir, Sean McDirmid, Stéphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Stenman, Lex Spoon, Matthias Zenger École Polytechnique Fédérale de Lausanne (EPFL) 1015 Lausanne, Switzerland Technical Report LAMP-REPORT-2006-001 Abstract guage for component software needs to be scalable in the sense that the same concepts can describe small as well as Scala fuses object-oriented and functional programming in large parts. Therefore, we concentrate on mechanisms for a statically typed programming language. It is aimed at the abstraction, composition, and decomposition rather than construction of components and component systems. This adding a large set of primitives which might be useful for paper gives an overview of the Scala language for readers components at some level of scale, but not at other lev- who are familar with programming methods and program- els. Second, we postulate that scalable support for compo- ming language design. nents can be provided by a programming language which unies and generalizes object-oriented and functional pro- gramming. For statically typed languages, of which Scala 1 Introduction is an instance, these two paradigms were up to now largely separate. True component systems have been an elusive goal of the To validate our hypotheses, Scala needs to be applied software industry. Ideally, software should be assembled in the design of components and component systems. Only from libraries of pre-written components, just as hardware is serious application by a user community can tell whether the assembled from pre-fabricated chips.
    [Show full text]
  • Programming-With-Actuate-Basic.Pdf
    Programming with Actuate Basic This documentation has been created for software version 11.0.5. It is also valid for subsequent software versions as long as no new document version is shipped with the product or is published at https://knowledge.opentext.com. Open Text Corporation 275 Frank Tompa Drive, Waterloo, Ontario, Canada, N2L 0A1 Tel: +1-519-888-7111 Toll Free Canada/USA: 1-800-499-6544 International: +800-4996-5440 Fax: +1-519-888-0677 Support: https://support.opentext.com For more information, visit https://www.opentext.com Copyright © 2017 Actuate. All Rights Reserved. Trademarks owned by Actuate “OpenText” is a trademark of Open Text. Disclaimer No Warranties and Limitation of Liability Every effort has been made to ensure the accuracy of the features and techniques presented in this publication. However, Open Text Corporation and its affiliates accept no responsibility and offer no warranty whether expressed or implied, for the accuracy of this publication. Document No. 170215-2-130331 February 15, 2017 Contents About Programming with Actuate Basic. .xi Part 1 Working with Actuate Basic Chapter 1 Introducing Actuate Basic . 3 About Actuate Basic . 4 Programming with Actuate Basic . 4 Understanding code elements . 5 About statements . 5 About expressions . 6 About operators . 7 Using an arithmetic operator . 7 Using a comparison operator . 8 Using logical operators . 8 Using the concatenation operator . 9 Adhering to coding conventions . 9 Commenting code . 10 Breaking up a long statement . 10 Adhering to naming rules . 10 Using the code examples . .11 Chapter 2 Understanding variables and data types . 13 About variables . 14 Declaring a variable .
    [Show full text]
  • System F and Existential Types 15-312: Foundations of Programming Languages
    Recitation 6: System F and Existential Types 15-312: Foundations of Programming Languages Serena Wang, Charles Yuan February 21, 2018 We saw how to use inductive and coinductive types last recitation. We can also add polymorphic types to our type system, which leads us to System F. With polymorphic types, we can have functions that work the same regardless of the types of some parts of the expression.1 1 System F Inductive and coinductive types expand the expressivity of T considerably. The power of type operators allows us to genericly manipulate data of heterogeneous types, building new types from old ones. But to write truly \generic" programs, we want truly polymorphic expressions| functions that operate on containers of some arbitrary type, for example. To gain this power, we add parametric polymorphism to the language, which results in System F, introduced by Girand (1972) and Reynolds (1974). Typ τ ::= t type variable τ1 ! τ2 function 8(t.τ) universal type Exp e ::= x variable λ (x : τ) e abstraction e1(e2) application Λ(t) e type abstraction e[τ] type application Take stock of what we've added since last time, and what we've removed. The familiar type variables are now baked into the language, along with the universal type. We also have a new form of lambda expression, one that works over type variables rather than expression variables. What's missing? Nearly every other construct we've come to know and love! As will be the case repeatedly in the course, our tools such as products, sums, and inductive types are subsumed by the new polymorphic types.
    [Show full text]
  • Recursive Type Generativity
    JFP 17 (4 & 5): 433–471, 2007. c 2007 Cambridge University Press 433 doi:10.1017/S0956796807006429 Printed in the United Kingdom Recursive type generativity DEREK DREYER Toyota Technological Institute, Chicago, IL 60637, USA (e-mail: [email protected]) Abstract Existential types provide a simple and elegant foundation for understanding generative abstract data types of the kind supported by the Standard ML module system. However, in attempting to extend ML with support for recursive modules, we have found that the traditional existential account of type generativity does not work well in the presence of mutually recursive module definitions. The key problem is that, in recursive modules, one may wish to define an abstract type in a context where a name for the type already exists, but the existential type mechanism does not allow one to do so. We propose a novel account of recursive type generativity that resolves this problem. The basic idea is to separate the act of generating a name for an abstract type from the act of defining its underlying representation. To define several abstract types recursively, one may first “forward-declare” them by generating their names, and then supply each one’s identity secretly within its own defining expression. Intuitively, this can be viewed as a kind of backpatching semantics for recursion at the level of types. Care must be taken to ensure that a type name is not defined more than once, and that cycles do not arise among “transparent” type definitions. In contrast to the usual continuation-passing interpretation of existential types in terms of universal types, our account of type generativity suggests a destination-passing interpretation.
    [Show full text]
  • Haskell-Like S-Expression-Based Language Designed for an IDE
    Department of Computing Imperial College London MEng Individual Project Haskell-Like S-Expression-Based Language Designed for an IDE Author: Supervisor: Michal Srb Prof. Susan Eisenbach June 2015 Abstract The state of the programmers’ toolbox is abysmal. Although substantial effort is put into the development of powerful integrated development environments (IDEs), their features often lack capabilities desired by programmers and target primarily classical object oriented languages. This report documents the results of designing a modern programming language with its IDE in mind. We introduce a new statically typed functional language with strong metaprogramming capabilities, targeting JavaScript, the most popular runtime of today; and its accompanying browser-based IDE. We demonstrate the advantages resulting from designing both the language and its IDE at the same time and evaluate the resulting environment by employing it to solve a variety of nontrivial programming tasks. Our results demonstrate that programmers can greatly benefit from the combined application of modern approaches to programming tools. I would like to express my sincere gratitude to Susan, Sophia and Tristan for their invaluable feedback on this project, my family, my parents Michal and Jana and my grandmothers Hana and Jaroslava for supporting me throughout my studies, and to all my friends, especially to Harry whom I met at the interview day and seem to not be able to get rid of ever since. ii Contents Abstract i Contents iii 1 Introduction 1 1.1 Objectives ........................................ 2 1.2 Challenges ........................................ 3 1.3 Contributions ...................................... 4 2 State of the Art 6 2.1 Languages ........................................ 6 2.1.1 Haskell ....................................
    [Show full text]
  • Chapter 1 Basic Principles of Programming Languages
    Chapter 1 Basic Principles of Programming Languages Although there exist many programming languages, the differences among them are insignificant compared to the differences among natural languages. In this chapter, we discuss the common aspects shared among different programming languages. These aspects include: programming paradigms that define how computation is expressed; the main features of programming languages and their impact on the performance of programs written in the languages; a brief review of the history and development of programming languages; the lexical, syntactic, and semantic structures of programming languages, data and data types, program processing and preprocessing, and the life cycles of program development. At the end of the chapter, you should have learned: what programming paradigms are; an overview of different programming languages and the background knowledge of these languages; the structures of programming languages and how programming languages are defined at the syntactic level; data types, strong versus weak checking; the relationship between language features and their performances; the processing and preprocessing of programming languages, compilation versus interpretation, and different execution models of macros, procedures, and inline procedures; the steps used for program development: requirement, specification, design, implementation, testing, and the correctness proof of programs. The chapter is organized as follows. Section 1.1 introduces the programming paradigms, performance, features, and the development of programming languages. Section 1.2 outlines the structures and design issues of programming languages. Section 1.3 discusses the typing systems, including types of variables, type equivalence, type conversion, and type checking during the compilation. Section 1.4 presents the preprocessing and processing of programming languages, including macro processing, interpretation, and compilation.
    [Show full text]
  • The Rust Programming Language
    The Rust Programming Language The Rust Programming Language Steve Klabnik and Carol Nichols, with Contributions from the Rust Community The Rust Programming Language, © Steve Klabnik and Carol Nichols, with Contributions from the Rust Community. Contents I Getting started 7 1 Introduction 9 1.1 Contributing to the book ................. 10 1.2 ................................ 10 1.3 ................................ 12 2 Guessing Game 21 2.1 Setting Up a New Project ................. 21 2.2 Processing a Guess ..................... 22 2.3 Generating a Secret Number ............... 27 2.4 Comparing the Guess to the Secret Number ....... 33 2.5 Allowing Multiple Guesses with Looping ......... 38 2.6 Summary .......................... 44 3 Common Programming Concepts 45 3.1 ................................ 46 3.2 ................................ 50 3.3 ................................ 58 3.4 ................................ 65 3.5 ................................ 66 4 Understanding Ownership 77 4.1 ................................ 77 4.2 ................................ 90 4.3 ................................ 97 5 Using Structs to Structure Related Data 105 5.1 ................................ 105 5.2 ................................ 111 5.3 ................................ 117 6 6 Enums and Pattern Matching 123 6.1 ................................ 123 6.2 ................................ 132 6.3 ................................ 138 II Basic Rust Literacy 143 1 Using Modules to Reuse and Organize Code 145 1.1 ...............................
    [Show full text]
  • Generic Programming in OCAML
    Generic Programming in OCAML Florent Balestrieri Michel Mauny ENSTA-ParisTech, Université Paris-Saclay Inria Paris [email protected] [email protected] We present a library for generic programming in OCAML, adapting some techniques borrowed from other functional languages. The library makes use of three recent additions to OCAML: generalised abstract datatypes are essential to reflect types, extensible variants allow this reflection to be open for new additions, and extension points provide syntactic sugar and generate boiler plate code that simplify the use of the library. The building blocks of the library can be used to support many approachesto generic programmingthrough the concept of view. Generic traversals are implemented on top of the library and provide powerful combinators to write concise definitions of recursive functions over complex tree types. Our case study is a type-safe deserialisation function that respects type abstraction. 1 Introduction Typed functional programming languages come with rich type systems guaranteeing strong safety prop- erties for the programs. However, the restrictions imposed by types, necessary to banish wrong programs, may prevent us from generalizing over some particular programming patterns, thus leading to boilerplate code and duplicated logic. Generic programming allows us to recover the loss of flexibility by adding an extra expressive layer to the language. The purpose of this article is to describe the user interface and explain the implementation of a generic programming library1 for the language OCAML. We illustrate its usefulness with an implementation of a type-safe deserialisation function. 1.1 A Motivating Example Algebraic datatypes are very suitable for capturing structured data, in particular trees.
    [Show full text]
  • The Rust Programming Language by Steve Klabnik and Carol Nichols, with Contributions from the Rust Community
    The Rust Programming Language by Steve Klabnik and Carol Nichols, with contributions from the Rust Community This version of the text assumes you’re using Rust 1.41.0 or later with edition="2018" in Cargo.toml of all projects to use Rust 2018 Edition idioms. See the “Installation” section of Chapter 1 to install or update Rust, and see the new Appendix E for information on editions. The 2018 Edition of the Rust language includes a number of improvements that make Rust more ergonomic and easier to learn. This iteration of the book contains a number of changes to reflect those improvements: Chapter 7, “Managing Growing Projects with Packages, Crates, and Modules,” has been mostly rewritten. The module system and the way paths work in the 2018 Edition were made more consistent. Chapter 10 has new sections titled “Traits as Parameters” and “Returning Types that Implement Traits” that explain the new impl Trait syntax. Chapter 11 has a new section titled “Using Result<T, E> in Tests” that shows how to write tests that use the ? operator. The “Advanced Lifetimes” section in Chapter 19 was removed because compiler improvements have made the constructs in that section even rarer. The previous Appendix D, “Macros,” has been expanded to include procedural macros and was moved to the “Macros” section in Chapter 19. Appendix A, “Keywords,” also explains the new raw identifiers feature that enables code written in the 2015 Edition and the 2018 Edition to interoperate. Appendix D is now titled “Useful Development Tools” and covers recently released tools that help you write Rust code.
    [Show full text]
  • 2 Defining Variables
    2 Defining Variables Variables Dim Statement Option Explicit Variable Names Standard Naming Conventions Data Types and Dim Examples Byte Boolean Integer Long Currency Single Double Date String (for variable-length strings) String * length (for fixed-length strings) Object Variant user-defined type object type AutoComplete Indenting Code Indenting several lines of code Removing an indent TypeName Function Arrays Option Base Statement Array Examples Objective: Understand variables and Data Types; AutoComplete; indent code; Option Explicit and Option Base statements 2-2 Crystal's Introduction to Programming With Excel : Variables Variables When you are writing programs, you want to be able to keep track of values in code so you can use them later. For instance, let's say you want to write a program to ask the user their name. You can create a variable to hold the name and prompt the user for its value. "Declaring variables" means that you are going to tell Excel what variables you are going to use and (optionally, but suggested) what type of data those variables are going to have. To declare a variable will be used in the program code, the Dim (dimension) statement is used. Dim Statement Dim [WithEvents] varname[([subscripts])] [As [New] type] [, [WithEvents] varname[([subscripts])] [As [New] type]] . The most common form of the Dim statement is: Dim varname As type The following statement declares a variable named mName as a string, which means a sequence of characters. Dim mUserName As String If you don't declare your variable, Excel will automatically create it the first time you use it in your code.
    [Show full text]