638 search results for ""
-
Objects
Immediate Objects and Object Types
speed : slightly faster field access in records field names : it is inconvenient to manipulate records of different types when some fields are named identically but it's not a problem with object
Advanced Topics -
Sequences
Reading a File with Seq.Unfold
<!-- Suggestion: perhaps it would be enlightening to illustrate the use of Seq.unfold by re-implementing the already seen function primes? Perhaps in an exercise rather than in the main text of the t
Data Structures -
OCaml Programming Guidelines
Clarity of OCaml Code
The language features numerous programming styles (or programming paradigms): imperative programming (based on the notion of state and assignment), functional programming (based on the notion of
Resources -
Memoization
Memoization Using Higher-order Functions
Now we can slightly rewrite the original fib function above using this general memoization technique: For recursive functions, however, the recursive call structure needs to be modified. T
Data Structures -
Understanding the Garbage Collector
The Fast Minor Heap
To garbage-collect the minor heap, OCaml uses copying collection to move all live blocks in the minor heap to the major heap. This takes work proportional to the number of live blocks in the mi
Runtime & Compiler -
Comparison of Standard Containers
Set and Map: Immutable Trees
Sets and maps are very useful in compilation and metaprogramming, but in other situations, hash tables are often more appropriate (see below). Adding an element: O(log n) Returning the number of
Resources -
OCaml Programming Guidelines
Indentation of Programs
So each time, you must choose between the different styles suggested. The only absolute rule is the first below. When a justification for the adopted style has seemed obvious to me, I have ind
Resources -
OCaml Programming Guidelines
How to Edit Programs
Developers describe how to use these features: the CTRL-C-CTRL-C combination recompiles the whole application; then, in case of errors, a succession of CTRL-X-` commands permits correction of
Resources -
Memory Representation of Values
Custom Heap Blocks
The custom operations specify how the runtime should perform polymorphic comparison, hashing and binary marshaling. They also optionally contain a finalizer that the runtime calls just before th
Runtime & Compiler -
Error Handling
Using the option Type for Errors
It tends to be considered good practice nowadays when a function can fail in cases that are not bugs (i.e., not assert false , but network failures, keys not present, etc.) to return type such a
Guides -
OCaml Programming Guidelines
General principles
Arrows of pattern-matching clauses should not be aligned. If an expression in a clause is too large to fit on one line, you must break the line immediately after the arrow of the corresponding cla
Resources -
Introduction to the OCaml Toplevel
Loading Libraries In UTop
Tip : UTop knows about the available libraries and completion works. Outside utop you can use ocamlfind list to display the complete list of libraries. Note that opam package may bundle several l
Tooling -
Error Handling
Turning Exceptions into option or result
Some may like to turn this into a higher-order generic function: It would be same for result , except some data must be provided to the Error constructor. The standard library does not prov
Guides -
Managing Dependencies With opam
Adding Dependencies From a Git Repository
Sometimes, you may want to install a package directly from a Git repository, e.g., when it is not available on the opam repository or when you want to use an unreleased version.
Projects -
Debugging
Printing a Back Trace for an Uncaught Exception
The environment variable OCAMLRUNPARAM also works when working on a program built with dune : From this back trace it should be clear that we receive a Not_found exception in List.assoc
Guides -
Libraries With Dune
Remove Duplicated Interfaces
This result is the same, except implementations Cumulus.M and Stratus.M are explicitly bound to the same interface, defined in module Wmo . wmo.ml wmo.mli Here is a possible way to fix th
Module System -
OCaml Programming Guidelines
Style dangers
Another common “over-imperative error” in the imperative world is not to systematically choose the simple for loop to iterate on a vector's element, but instead to use a complex while loo
Resources -
A Tour of OCaml
Pattern Matching, Cont'd
Note that OCaml throws a warning when pattern matching does not catch all cases: The underscore symbol is a catch-all pattern; it matches with anything. In this other example, the same comparis
First Steps -
Values and Functions
Recursive Functions
Note : Notice that the fib_loop function has three parameters m n i but when defining fib only two arguments were passed 0 1 , using partial application. The second version fib uses the fir
Introduction -
OCaml Programming Guidelines
Pattern-matching in named functions
<!-- $MDX skip --> Pattern-matching in functions defined by let or let rec gives rise to several reasonable styles that obey the preceding pattern-matching rules (the one for anonymous fun
Resources -
OCaml Programming Guidelines
Comparisons and Boolean operators
Comparisons are infix operators, so the preceding rules apply. This is why f x < g x means (f x) < (g x) . For type reasons (and no other sensible interpretation), the expression f x < x + 2
Resources -
Values and Functions
Pattern Matching in Definitions
<!--the example illustrates tuples::--> When pattern matching only has one case, it can be used in name definitions and in let ... = and fun ... -> expressions. In that case, less or more than
Introduction -
Managing Dependencies With opam
Installing a Dependency in Your Switch
instead. If you want to install a specific version of the package, use to get the latest version of the package. Installing a package from the opam repository to your active switch, you can run
Projects -
OCaml Programming Guidelines
Avoid Nocuous Comments
<!-- $MDX skip --> An example of what to avoid, the following comment uses technical words and is thus masquerading as a real comment, but it has no additional information of interest: Absolu
Resources -
Configuring Your Editor
3) OCaml Commands With Ctrl + Shift + P
Pressing the key combination Ctrl + Shift + P opens a modal dialog at the top. If you type the word ocaml , you will be presented with a list of various OCaml commands at your disposal which can b
Tooling -
OCaml Programming Guidelines
How to Write Long Character Strings
<!-- $MDX skip --> Indent long character strings with the convention in force at that line, plus an indication of string continuation at the end of each line (a \ character at the end of the l
Resources -
Understanding the Garbage Collector
Next-Fit Allocation
Next-fit allocation is quite a cheap allocation mechanism, since the same heap chunk can be reused across allocation requests until it runs out. This in turn means that there is good memory loc
Runtime & Compiler -
Comparison of Standard Containers
Strings: Immutable Vectors
Adding an element (by creating a new string): O(n) Length: O(1) Accessing character i : O(1) Finding an element: O(n) Strings are very similar to arrays, but they are immutable. Strings are s
Resources -
Memory Representation of Values
String Values
Care should be taken that any C library functions that receive these buffers can also cope with arbitrary bytes within the buffer contents and are not expecting C strings. For instance, the C me
Runtime & Compiler -
Higher Order Functions
Binding as early returns
The main difference is that in this case Result.bind is biased towards Ok value , so that if a result value is an Error reason , it will short-circuit through the binds and just return the first
Introduction -
Common Error Messages
x.cmi is not a compiled interface
It means that some_module.cmi is not valid according to the current version of the OCaml compiler. Most of the time, removing the old compiled files ( .cmi, .cmo, *.cmx, ...) and recompiling is
Resources -
Modules
Interfaces and Implementations
This triggers a compilation error. You can check that Cairo.message is not public by attempting to compile a delhi.ml file containing: Compile and execute both programs: Update the dune
Module System -
Mutability and Imperative Control Flow
Immutable vs Mutable Data
In the following sections, we introduce OCaml's language features for dealing with mutable states. When you use let … = … to bind a value to a name, this name-value binding is immutable , s
Introduction -
Sequences
Sequences Are Functions
When code dealing with sequences does not behave as expected, like if it is crashing or hanging, there's a fair chance a mistake like in the first definition of fibs was made. Sequence consume
Data Structures -
Common Error Messages
Warning: Illegal backslash escape in string
Recent versions of OCaml warn you against unprotected backslashes in strings since they should be doubled. Such a message may be displayed when compiling an older program, and can be turned off
Resources -
OCaml Programming Guidelines
Be Simple and Readable
Writing programs law : A program is written once, modified ten times, and read 100 times. So it's beneficial to simplify its writing, always keep future modifications in mind, and never jeopardi
Resources -
Common Error Messages
This pattern is unused
In our example, it is now clear that only the first item of the pair will ever be tested. This leads to the following results: the tree of cases is traversed linearly, from left to right. There
Resources -
The Compiler Frontend: Parsing and Type Checking
Syntax Errors
The syntax error points to the line and character number of the first token that couldn't be parsed. In the broken example, the module keyword isn't a valid token at that point in parsing, so t
Runtime & Compiler -
Introduction to opam Switches
Selecting a Switch
Learn more details and uses of opam switches in the opam manual's File Hierarchies page and its page dedicated to switches . Command-Line Flag : Use the --switch <switch> command-line flag to
Tooling -
Comparison of Standard Containers
Buffer: Extensible Strings
Adding a char: O(1) if the buffer is big enough, or O(log n) on average if the initial buffer size was much smaller than the number of bytes n . Adding a string of k chars: O(k * "adding
Resources -
OCaml Programming Guidelines
Other Emacs tricks
Under Unix, the CTRL-C-CTRL-C or Meta-X compile combination, followed by CTRL-X-` , is also used to find all occurrences of a certain string in a OCaml program. Instead of launching mak
Resources -
OCaml Programming Guidelines
Single branches
If cond , e1 , and e2 are small, simply write them on one line: If the expressions making up a conditional are purely functional (without side effects), we advocate binding them within the
Resources -
OCaml Programming Guidelines
Multiple branches
Yet again, choose your style and use it systematically. Justification : elsif is a keyword in many languages, so use indentation and else if to bring it to mind. Moreover, you do not have t
Resources -
Mutability and Imperative Control Flow
Byte Sequences
<!-- FIXME: link to a dedicated Byte Sequences tutorial --> Note : the bytes type uses a much more compact memory representation than char array . As of writing this tutorial, there is an 8-fact
Introduction -
A Tour of OCaml
Recursive Functions
Each => sign corresponds to the computation of a recursive step, except the last one. OCaml handles lists internally, as shown in the penultimate expression, but displays them as the last expressio
First Steps -
Error Handling
Errors as Special Values
The rest of this document presents and compares approaches towards error handling. Exceptions provide a means to deal with errors at the control flow level, while option and result make error
Guides -
OCaml Programming Guidelines
Pattern-matching in anonymous functions
<!-- $MDX skip --> Similarly to match or try , pattern-matching of anonymous functions, starting with function , are indented with respect to the function keyword:
Resources -
Mutability and Imperative Control Flow
Good: Memoization
You can find a concrete example of memoization and an in-depth explanation in the chapter on Memoization of "OCaml Programming: Correct + Efficient + Beautiful." are found in the cache (it is a hi
Introduction -
OCaml Programming Guidelines
How to Write Pairs
Definition of the components of a pair : In place of let (x, y) = ... , you can write let x, y = ... . Justification : The point is to define several values simultaneously, not to constr
Resources -
Comparison of Standard Containers
Arrays: Mutable Vectors
Well-suited for the following cases: dealing with sets of elements of known size, accessing elements by numeric index, and modifying in-place elements. Basic arrays have a fixed length. Adding an el
Resources