714 search results for ""
-
Labelled and Optional Arguments
Labelling Parameters
At parameter definition ~first is the same as ~first:first . Passing argument ~last is the same as ~last:last . It is possible to use a shorter syntax when using the same name as label and p
Introduction -
Sequences
Taking Parts of a Sequence
( Seq.ints i is the infinite sequence of the integers beginning at i and counting up.) This can be used to print integers without looping forever, as shown previously: When executed, the functio
Data Structures -
Transitioning to Multicore with ThreadSanitizer
An Example Application
Underneath the hood, the library may have been implemented in various ways. Consider the following thread-unsafe implementation in bank.ml : Consider a little bank library with the following
Guides -
Formatting and Wrapping Text
Printing Spaces
Generally speaking, a printing routine using "format", should not directly output white spaces: the routine should use break hints instead. (For instance print_space () that is a convenient a
Tutorials -
Managing Dependencies With opam
Dependency Categories
See opam documentation for more details on the opam syntax. In *.opam files: In dune-project , flags look like this: Normal (no flag): used at runtime Build ( build ): used only to buil
Projects -
Mutability and Imperative Control Flow
Semicolon
Fun fact : begin … end and parentheses are literally the same: Remember the value of a semicolon-separated sequence is the value of its last expression. Grouping the first two steps with begi
Introduction -
Understanding the Garbage Collector
Heap Compaction
<div class="note"> The heap compaction cycle avoids this by relocating all the values in the major heap into a fresh heap that places them all contiguously in memory again. A naive implementati
Runtime & Compiler -
Bootstrapping a Project with Dune
More Comprehensive Scaffolding
spin drom carcass If you're looking for project templates that include more than the basics, there are other community projects that offer more comprehensive project scaffolding:
Projects -
OCaml Programming Guidelines
How to Comment Programs
Avoid comments in the bodies of functions. Prefer one comment at the beginning of the function that explains how a particular algorithm works. Once more, if there is no difficulty, there is no
Resources -
Sequences
Understanding the Difference
If the distinction remains a mystery, take a moment to compare the inputs to the Seq.Cons constructor and Seq.cons function. They look deceptively similar, but one takes as input a value of ty
Data Structures -
Configuring Your Editor
LSP setup for OCaml
You are now ready to edit OCaml code productively with Emacs! And that's all there is to it! Now all you need to do is install ocaml-lsp-server and ocamlformat in your switch : Next, we
Tooling -
Objects
Objects and Classes
s is an opaque object. The implementation (i.e., the list) is hidden from callers. In the OCaml toplevel, we can examine the types of objects and methods in more detail: Notice the syntax.
Advanced Topics -
Modules
Abstract and Read-Only Types
Abstract and read-only types can be either variants, as shown in this section, records, or aliases. It is possible to access a read-only record field's value, but creating such a record requires usin
Module System -
Higher Order Functions
Mapping Custom Data Types
Note that the structure of the tree is preserved, but every time we encounter a value , we update it with (fn value) . When working with our custom data types, such as the tree we used in the
Introduction -
OCaml Programming Guidelines
Naming Anonymous Functions
Justification : Much clearer, in particular if the name given to the function is meaningful. <!-- $MDX skip --> write <!-- $MDX skip --> In the case of an iterator whose argument is a comp
Resources -
Hash Tables
Adding Data to a Hash Table
Where the type used to be the polymorphic (_weak1, _weak2) , it now has the concrete representation of (string * string) . Now that we put data into my_hash , let's look at its type: The ret
Data Structures -
Functors
Write a Functor to Extend Modules
Modules Array and List appear augmented with Array.scan_left and List.scan_left . For brevity, the output of the first two toplevel commands is not shown here. Run the dune utop command. O
Module System -
Values and Functions
Local Definitions
In both examples, d and e are local definitions. Arbitrary combinations of chaining or nesting are allowed. e is bound to 6 inside e * 5 d is bound to 30 inside d * 7 Here is how scopin
Introduction -
Basic Data Types and Pattern Matching
Introduction
<!-- The goal of this tutorial is to provide for the following capabilities: - Handle data of all predefined types using dedicated syntax - Write variant type definitions: simple, recursive, and poly
Introduction -
OCaml Programming Guidelines
Usage in Module Interface
The function's usage must appear in the module's interface that exports it, not in the program that implements it. Choose comments as in the OCaml system's interface modules, which will subsequen
Resources -
Sequences
A Mental Model for Seq.Cons vs Seq.cons
It is useful to think of Seq.Cons and Seq.cons as accomplishing different tasks. Seq.Cons provides a convenient means of recursively defining a sequence generator and a clumsy means to prep
Data Structures -
Basic Data Types and Pattern Matching
User-Defined Types
These three kinds of type definitions are covered in the next three sections. Variant Record Aliases User-defined types are always introduced using the type … = … statement. The keyword type
Introduction -
Transitioning to Multicore with ThreadSanitizer
A Proposed Workflow
Install TSan Write a parallel test runner Run tests under TSan If TSan complains about data races, address the reported issue and go to step 2. Now if we want to see if this code is Multicore read
Guides -
Values and Functions
Function as Values
<!-- For now, let's put aside those definitions and instead start playing with functions. Their meaning will arise from experience. Once things make sense, using these terms is just a means to interac
Introduction -
Debugging
Detecting a Data Race
The TSan instrumentation benefits from compiling programs with debug information, which happens by default under dune . To manually invoke the ocamlopt compiler under our 5.2.0+tsan switch
Guides -
Error Handling
Asynchronous Exceptions
The latter is thrown when the user interrupts an interactive execution. Because they are loosely or not at all related with the program logic, it mostly doesn't make sense to track the place wher
Guides -
Higher Order Functions
Async code
<!-- Comment let f () = 42 let f () = g 42 One possible issue with the repeat function used in the intro comes from the fact it is used to produce a side effect. Therefore two stories get mixed tog
Introduction -
Configuring Your Editor
1) Hovering for Type Information
This is a great feature that lets you see type information of any OCaml variable or function. All you have to do is place your cursor over the code and it will be displayed in the tooltip. VSCode Ho
Tooling -
Configuring Your Editor
Getting Type Information
OCaml-eglot README provides a comprehensive overview of all the functions available in this mode! Emacs Type information Opening an OCaml file should launch an ocaml-lsp server, and you can con
Tooling -
OCaml Docker Images
What's Inside Each Image
/Dockerfile.opam - the first stage installing the opam binary /Dockerfile.ocaml - builds on the first stage by installing a particular opam switch Each image also includes two Dockerfiles showing h
Additional Tooling -
Sequences
Reading a File with Seq.Unfold
Note: production code should handle file opening errors, this example has been kept short to focus only on how files relate to sequences. Finally, let's read the file's contents using Seq.unfol
Data Structures -
Installing OCaml
Install Platform Tools
You're now all set and ready to start hacking. All these tools can be installed using a single command: UTop , a modern interactive toplevel (REPL: Read-Eval-Print Loop) Dune , a fast and full-fe
First Steps -
Hash Tables
Finding Data in Hash Tables
This returns ["hard"; "hug"; "hi"; "hello"] , demonstrating that hashed key collisions are associated with a list of values associated with that key. However, the previous values associated wit
Data Structures -
Operators
Using Binary Operators
Finally, in the third line, all the arguments expected by List.filter are provided. The returned list contains the values satisfying the ( <= ) 10 function. The first shows the List.filter typ
Advanced Topics -
Error Handling
Safe vs. Unsafe Functions
The main ways to write such safe error-handling functions are to use either option (next section) or result (following section) values. Although handling errors in data using those types may a
Guides -
Managing Dependencies With opam
Installing a Git Dependency in Your Switch
You can install a package in your active switch directly from a Git URL:
Projects -
Functors
Extending a Module with a Standard Library Functor
This allows the user to seemingly extend the module String with a submodule Set . Check the behaviour using opam exec -- dune exec funkt < dune . funkt.ml Using the include statement, here i
Module System -
OCaml Programming Guidelines
Using Tab Stops
Justification : Between one display and another, the indentation of the program changes completely. It can also become completely wrong if the programmer used both tabulations and spaces to inden
Resources -
Values and Functions
Anonymous Functions
Anonymous functions are often passed as arguments to other functions. The identity function, which takes anything and returns it unchanged The square function, which takes an integer and returns it
Introduction -
Values and Functions
Defining Global Functions
The former explicitly binds the anonymous function to a name. The latter uses a more compact syntax and avoids the fun keyword and the arrow symbol. The expression, which happens to be a function
Introduction -
Formatting and Wrapping Text
A Concrete Example
<!-- $MDX skip --> In Caml Light, replace the first line by: I use the format library to print the lambda-terms: First, I give the abstract syntax of lambda-terms: Thus the problem is to pr
Tutorials -
Basic Data Types and Pattern Matching
Function Parameter Aliases
This is useful for matching variant values of parameters. Function parameters can also be given a name with pattern matching for tuples and records.
Introduction -
Installing OCaml
Binary Distribution
Advanced Windows Users : If you are familiar with Cygwin or WSL2, there are other installation methods described on the OCaml on Windows page. On Windows, the winget package is maintained by opa
First Steps -
Modules
Displaying a Module's Interface
If you are using Dune, .cmi file are in the _build directory. Otherwise, you can compile manually to generate them. The command ocamlc -c cairo.ml will create cairo.cmo (the executable byteco
Module System -
OCaml Programming Guidelines
Formatting Guidelines
Pseudo spaces law : never hesitate to separate words in your programs with spaces. The space bar is the easiest key to find on the keyboard, so press it as often as necessary! If you choose no
Resources -
Profiling
Polymorphic Types
Lesson: if you have a function which is unintentionally polymorphic then you can help the compiler by specifying types for one or more of the arguments. Disappointingly although the definition o
Guides -
Objects
Inheritance and Coercions
Is it possible to coerce from a superclass (e.g., widget ) to a subclass (e.g., button )? The answer, perhaps surprisingly, is NO! Coercing in this direction is unsafe . You might try to coerc
Advanced Topics -
Installing OCaml
Initialise opam
Any problems installing? Be sure to read the latest release notes . You can file an issue at <https://github.com/ocaml/opam/issues> or <https://github.com/ocaml-windows/papercuts/issues> . Note
First Steps -
Monads
Composition and Monad Laws
In that formulation, it becomes immediately clear that return is a left and right identity, and that composition is associative. Law 1: return >=> f behaves the same as f . Law 2: f >=> r
Data Structures -
OCaml Programming Guidelines
Arithmetic operators: the same rules as in mathematics
For example: 1 + 2 * x means 1 + (2 * x) .
Resources