638 search results for ""
-
Running Commands in an opam Switch
Using opam env
This command evaluates the output of opam env and sets the necessary environment variables for the currently active switch. After running this command, you'll have access to the packages installed in
Projects -
Configuring Your Editor
Visual Studio Code
Upon first loading an OCaml source file, you may be prompted to select the toolchain in use. Pick the version of OCaml you are using, e.g., 5.1.0 from the list. For VSCode, install the OCaml Pl
Tooling -
Sequences
Iterating Over Sequences
The key point is that it doesn't leak memory. This example runs in constant space. It is effectively nothing more than an infinite loop, which can be confirmed by monitoring the space consumption
Data Structures -
Sequences
Unfolding Sequences
The function Seq.uncons returns the head and tail of a sequence if it is not empty. Otherwise, it returns None . We can check our map function by applying a square root function to a sequen
Data Structures -
Error Handling
Exceptions Not Raised
This has improved since. Only linked C code should be able to trigger an undetected stack overflow. Xavier Leroy, October 2021 But catching stack overflows is tricky, both in Unix-like systems
Guides -
Objects
The Oo Module and Comparing Objects
= and <> can be used to compare objects for physical equality (an object and its copy are not physically identical). You can also use < etc., which provides an ordering of objects based app
Advanced Topics -
Error Handling
Conversion Between option and result
From option to result , use function Option.to_result : From result to option , use function Result.to_option : This is done by using the following functions:
Guides -
Values and Functions
The Application Operator
The @@ application operator applies an argument (on the right) to a function (on the left). It is useful when chaining several calls, as it avoids writing parentheses, which creates easier-to-read
Introduction -
Sequences
Introduction
In OCaml, any value a of type t can be turned into a constant function by writing fun _ -> a or fun () -> a . The latter function is called a thunk . Using this terminology, Seq.t value
Data Structures -
Debugging
Polymorphic Functions
For our sorting routine, a single type constraint on the argument of the exchange function warranties a monomorphic typing, that allows a proper trace of function calls: A simple way to overc
Guides -
Values and Functions
Inner Shadowing
<!-- A name-value pair in a local expression *shadows* a binding with the same name in the global environment. In other words, the local binding temporarily hides the global one, making it inaccessib
Introduction -
Fix Homebrew Errors on Apple M1
Return to Install Tutorial
You're all set to keep learning OCaml! Now that's all sorted, you can return to the Install OCaml tutorial to install and initialise opam.
Resources -
Preprocessors and PPXs
PPX Rewriters
Secondly, most of the PPX's code transformation do not need to be given the full AST; they can work locally in subparts of it. There are two kinds of such local restrictions to the general PPX re
Advanced Topics -
OCaml Programming Guidelines
When to Use Mutables
Mutable values are useful and sometimes indispensable for simple and clear programming. Nevertheless, you must use them with discernment because OCaml's normal data structures are immutable. They
Resources -
Your First OCaml Program
Minimum Setup
Note : minimo.exe is not a file name. This is how Dune is told to compile the minimo.ml file using OCaml's native compiler instead of the bytecode compiler. As a fun fact, note that an empty file
First Steps -
Error Handling
Concluding Remarks
Properly handling errors is a complex matter. It is cross-cutting concern , touches all parts of an application, and can't be isolated in a dedicated module. In contrast to several other mains
Guides -
Debugging
Detecting a Data Race with Thread Sanitizer
With the introduction of Multicore parallelism in OCaml 5, comes the risk of introducing data races among the involved Domain s. Luckily the Thread Sanitizer (TSan) mode for OCaml is helpful to
Guides -
Modules
File-Based Modules
In a project, it is preferable to create the dune configuration files and directory structure using the dune init project command. Refer to the Dune documentation for more on this matter. Ac
Module System -
Values and Functions
Defining Local Functions
Although local functions are often defined inside the function's scope, this is not a requirement. The function sq is only available inside the sq 7 * sq 7 expression. Calling sq gets an erro
Introduction -
How to Work with the Garbage Collector
Exercises
Implement the record as an object , and allow it to transparently pad/unpad strings. You will need to provide methods to set and get the name and address fields (four public methods in all). Hid
Guides -
OCaml Programming Guidelines
Use Assertions
Note as well that an assertion is often preferable to a comment because it's more trustworthy. An assertion is forced to be pertinent because it is verified upon each execution, while a comment c
Resources -
Error Handling
Naming Conventions
However, some projects tend to avoid or reduce the usage of exceptions. In such a context, the opposite convention is relatively common: the version of the function that raises exceptions is su
Guides -
Mutability and Imperative Control Flow
Imperative Control Flow
OCaml allows you to evaluate expressions in sequence and provides for and while loops to execute a block of code repeatedly.
Introduction -
Using the OCaml Compiler Toolchain
Other Build Systems
OMake Another OCaml build system. GNU make GNU make can build anything, including OCaml. May be used in conjunction with OCamlmakefile Oasis Generates a configure, build, and install system from
Guides -
Objects
Polymorphic Classes
We can force OCaml to be more specific and only allow drain_stack to be called on 'a stack s by narrowing the type of the s argument, like this: Notice the type of drain_stack . Cleverly
Advanced Topics -
Using the OCaml Compiler Toolchain
Compilation Basics
In this section, we will first see how to compile a simple program using only ocamlc or ocamlopt . Then we will see how to use libraries and how to take advantage of the findlib system, wh
Guides -
OCaml Programming Guidelines
Pattern-Matching
Never be afraid of overusing pattern-matching! On the other hand, be careful to avoid nonexhaustive pattern-matching constructs. Complete them with care, without using a “catch-all” clause su
Resources -
Objects
Class Types vs. Just Types
Mixing objects that share a common subtype can be done, but it requires explicit type coercion using the :> operator: In this example, t is also the type of objects that this class would
Advanced Topics -
Basic Data Types and Pattern Matching
Integers
There are no dedicated types for unsigned integers in OCaml. Bitwise operations on int treat the sign bit the same as other bits. Binary operators use standard symbols. The signed remainder operato
Introduction -
Higher Order Functions
Readability Notes
Versus a much more readable and easier to maintain version: For example, this is a pipeline with a lot of currying/uncurrying that would most likely be easier to read and maintain if we manuall
Introduction -
Sequences
Constructing Sequences
The OCaml Standard Library contains a module for sequences called Seq . It contains Seq.int , which we implemented above. The function ints n looks as if building the infinite sequence (n; n +
Data Structures -
Values and Functions
Global Definitions
Global definitions are those entered at the top level. Here, the_answer is defined globally. This is what happens when writing a definition in UTop: If the expression can be evaluated, it is. Ot
Introduction -
OCaml Programming Guidelines
while loops
Justification : while loops require one or more mutables, so the loop condition changes value and the loop finally terminates. To prove their correctness, you must discover the loop invarian
Resources -
Values and Functions
Pattern Matching on Tuples
The List.split function turns a list of pairs into a pair of lists. Here, each resulting list is bound to a name. A common case is tuples. It allows the creation of two names with a single let .
Introduction -
OCaml Programming Guidelines
Exceptions
Justification : try ... with _ -> silently catches all exceptions, even those which have nothing to do with the computation at hand (for example, an interruption will be captured and the
Resources -
Sets
Sets With Custom Comparators
You can use any type for elements, as long as you define a meaningful compare operation. The value "HELLO" is not added to the set because it is considered equal to the value "hello" , which
Data Structures -
Monads
Monad Laws
But the problem is that doesn't type check: f >>= g doesn't have the right type to be on the right-hand side of >>= . So we have to insert an extra anonymous function fun x -> ... to make th
Data Structures -
Configuring Your Editor
Editor Features at Your Disposal
If your editor is setup correctly, here are some important features you can begin using to your advantage:
Tooling -
OCaml Programming Guidelines
Compiler Warnings
Compiler warnings are meant to prevent potential errors, which is why you absolutely must heed them and correct your programs if compiling them produces such warnings. Besides, programs whose com
Resources -
Operators
Allowed Operators
Don't define wide scope operators. Restrict their scope to module or function. Don't use many of them. Before defining a custom binary operator, check that the symbol is not already used. This can be
Advanced Topics -
Modules
Module Signatures are Types
This allows writing interfaces shared by several modules. An implementation satisfies any module type listing some of its contents. This implies a module may have several types and that there is a su
Module System -
Libraries With Dune
Introduction
Note : The other terms we use are classifications of clouds. These include " cumulus " (fluffy), " nimbus " (precipitating), " cumulonimbus " (fluffy and precipitating), " nimbostratus " (flat, amorp
Module System -
Functors
Naming and Scoping
Warning : Don't shadow names too often because it makes the code harder to understand. In the example above, t from with type takes precedence over the local t , which only has a local scope.
Module System -
Options
Access the Content of an Option
In the standard library, these functions are Option.get and Option.value . However, it needs a default value as an additional parameter. Beware, get o throws an exception if o is None . T
Data Structures -
Modules
Naming and Scoping
The module access notation can be applied to an entire expression: You can open a module inside a definition, using the let open ... in construct: The standard library is a module called Std
Module System -
Values and Functions
Conclusion
<!-- One may wonder: > Why is function-as-values the key concept of functional programming? The answer to this question goes beyond the scope of this tutorial. This comes from the [λ-calculus](htt
Introduction -
Configuring Your Editor
Melpa and use-package
If your version of Emacs does not support the use-package macro (or is not set up to take MELPA packages into account), please update it and follow these instructions to install use-package and
Tooling -
Loops and Recursions
Looping Over Strings
String.copy copies a string, like strdup . There is also a String.iter function which works like List.iter , except over the characters of the string. The String module also contains dozen
Introduction -
OCaml Programming Guidelines
Subdivide Your Programs Into Little Functions
Small functions are easier to master.
Resources -
Monads
Example: The Lwt Monad
Metaphorically, as we discussed before, the box involved here is one that starts out empty but eventually will be filled with a value of type 'a . The "something more" in these computations is t
Data Structures