816 search results for ""
-
Functors
Injecting Dependencies Using Functors
Module System -
Functors
Dependencies Between Modules
Check the program's behaviour using opam exec -- dune exec funkt < dune . Module List through List.iter and f 's type Module Out_channel through Out_channel.output_string It embeds an addit
Module System -
Functors
Dependency Injection
The dependency List is injected when compiling the module Funkt . Observe that the code using IterPrint is unchanged. Check the program's behaviour using opam exec -- dune exec funkt < dune .
Module System -
Functors
Replacing a Dependency
Note : Modules received and returned by IterPrint.Make both have a type t . The with type ... := ... constraint exposes that the two types t are the same. This makes functions from the injecte
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 -
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 -
Functors
Initialisation of Stateful Modules
Calling R1.bits a third time returns the same result as the first call, which demonstrates the state has indeed been reset. Calling R2.bits a second time shows the modules aren't sharing states.
Module System -
Functors
Conclusion
Functor application essentially works the same way as function application: passing parameters and getting results. The difference is that we are passing modules instead of values. Beyond comfort, it
Module System -
First-Class Modules
First-Class Modules
Introduction
Prerequisites : Modules , Functors . First-class modules let you treat modules as values. You can pass them to functions, return them from functions, and store them in data structures. This provid
Module SystemFirst-Class Modules
Basic Example
The expression (module SimplePrinter : Printer) converts a module into a value of type (module Printer) . The expression (val printer : Printer) converts it back. The type annotation can often b
Module SystemFirst-Class Modules
Passing Modules to Functions
The pattern (module P : Printer) automatically unpacks the first-class module, making P available as a regular module inside the function. You can write functions that accept modules as parame
Module SystemFirst-Class Modules
Practical Example: Multiple Implementations
Now you can choose the database at runtime and store different implementations in data structures: First-class modules shine when you need to choose between implementations at runtime:
Module SystemFirst-Class Modules
Runtime Selection
A common pattern is selecting an implementation based on configuration:
Module SystemFirst-Class Modules
Using Type Constraints
The (type a) syntax creates a locally abstract type that connects the module's type t with the list elements' type. When you need to expose the type from a first-class module, use type constra
Module SystemFirst-Class Modules
When to Use First-Class Modules
Generate many similar modules at compile time Maximize performance (first-class modules have small runtime overhead) Complex module relationships with multiple dependencies Use functors when you need
Module SystemFirst-Class Modules
Common Patterns
Module SystemFirst-Class Modules
Plugin Registry
Module SystemFirst-Class Modules
Heterogeneous Collections
Module SystemFirst-Class Modules
Key Points
Pack modules with (module M : ModuleType) Unpack with let module M = (val x : ModuleType) in ... Functions can directly pattern match: fun (module M : ModuleType) -> ... Use with type constraint
Module SystemFirst-Class Modules
Conclusion
For compile-time module generation and maximum performance, use functors instead. First-class modules let you write flexible code that chooses implementations at runtime. They're particularly useful
Module SystemLibraries With Dune
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 SystemLibraries With Dune
Minimum Project Setup
<!-- FIXME: update with wmo --> The dune describe command allows having a look at the project's module structure. Here is its output: mixtli is the project's name (it means cloud in Nahuatl
Module SystemLibraries With Dune
Libraries
Dune creates a module Wmo from the contents of directory lib . The directory's name (here lib ) is irrelevant. The library name appears uncapitalised ( wmo ) in dune files: In its definition, i
Module SystemLibraries With Dune
Library Wrapper Modules
Have different public and internal names, module CumulusCloud = Cumulus Define values in the wrapper module, let ... = Expose module resulting from functor application, module StringSet = Set.Make
Module SystemLibraries With Dune
Include Subdirectories
<!-- ## Starting a Project from a Single File It is possible to start an empty Dune project from a single file. Create a fresh directory. ```shell $ mkdir foo.dir; cd foo.dir ``` Create a `dune-p
Module SystemLibraries 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 SystemLibraries With Dune
Disable Library Wrapping
When the file lib/wmo.ml exists, the modules stanza that doesn't list it prevents it from being bundled in the library When the file lib/wmo.ml doesn't exist, the wrapped false stanza preve
Module SystemLibraries With Dune
Conclusion
The OCaml module system allows organising a project in many ways. Dune provides several means to arrange modules into libraries.
Module SystemOptions
Options
Introduction
The option type is useful when the lack of data is better handled as the special value None rather than an exception. It is the type-safe version of returning error values. Since data wrapped in an
Data StructuresOptions
Exceptions vs Options
See Error Handling for a longer discussion on error handling using options, exceptions, and other means. The function Sys.getenv : string -> string from the OCaml standard library queries the
Data StructuresOptions
The Standard Library Option Module
Most of the functions in this section, as well as other useful ones, are provided by the OCaml standard library in the Stdlib.Option module.
Data StructuresOptions
Map Over an Option
Here, map is applied to a list inside Some , doubling each number. If None , the list transformation doesn't occur. Example 3 : Doubling Each Element in an Option of a List If there is a st
Data StructuresOptions
Peel Off Doubly Wrapped Options
Here, safe_divide may return Some or None . Option.join ensures we don’t get Some None . Example 2 : Nested Option with a Computation If Some (Some v) , join extracts v and retur
Data StructuresOptions
Extract the Content of an Option
These examples highlight the difference: Option.get is unsafe and raises an exception on None , while Option.value allows fallback behavior. Example 3 : Using Option.value for Safe Extracti
Data StructuresOptions
Fold an Option
This function safely handles optional names by providing a fallback greeting: Example 3 : Handling Optional User Input Since None is given, it returns the default 0 . Here, Option.fold ap
Data StructuresOptions
Bind an Option
This example retrieves a configuration value and ensures it falls within a valid range. Example 3 : Chaining Computations Notice how the function user_to_email does not require explicit pattern
Data StructuresOptions
Conclusion
The option type in OCaml provides a powerful and type-safe way to represent values that may be absent, avoiding the pitfalls of exceptions. By leveraging functions such as map , join , get , va
Data StructuresArrays
Arrays
Introduction
Storing and processing large amounts of data Implementing algorithms that require random access and modification of elements Working with matrices and other multi-dimensional data structures Arrays
Data StructuresArrays
Creating Arrays
Array.init generates an array of a given length by applying a function to each index of the array, starting at 0. The following line of code creates an array containing the first 5 even numbers us
Data StructuresArrays
Accessing Array Elements
You can access individual elements of an array using the .(index) syntax, with the index of the element you want to access. The index of the first element is 0, and the index of the last element
Data StructuresArrays
Modifying Array Elements
Note that this operation returns unit , not the modified array. even_numbers is modified in place as a side effect. To modify an element in an array, we simply assign a new value to it using th
Data StructuresArrays
The Standard Library Array Module
OCaml provides several useful functions for working with arrays. Here are some of the most common ones:
Data StructuresArrays
Length of an Array
The Array.length function returns the size of an array:
Data StructuresArrays
Iterate on an Array
Iterating on arrays can also be made using for loops. Here is the same example using a loop: Array.iter applies a function to each element of an array, one at a time. The given function must
Data StructuresArrays
Map an Array
The Array.map function creates a new array by applying a given function to each element of an array. For example, we can get an array containing the square of each number in the even_numbers ar
Data StructuresArrays
Folding an Array
These functions derive a single value from the whole array. For example, they can be used to find the maximum element of an array: fold_right f a init computes f a.(0) (f a.(1) ( ... (f a.(n-1)
Data Structures