816 search results for ""

Showing 251 - 300
  1. Functors

    Injecting Dependencies Using Functors

    Module System
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. First-Class Modules

  10. 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 System
  11. First-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 System
  12. First-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 System
  13. First-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 System
  14. First-Class Modules

    Runtime Selection

    A common pattern is selecting an implementation based on configuration:

    Module System
  15. First-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 System
  16. First-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 System
  17. First-Class Modules

    Common Patterns

    Module System
  18. First-Class Modules

    Plugin Registry

    Module System
  19. First-Class Modules

    Heterogeneous Collections

    Module System
  20. First-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 System
  21. First-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 System
  22. Libraries With Dune

  23. 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
  24. Libraries 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 System
  25. Libraries 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 System
  26. Libraries 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 System
  27. Libraries 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 System
  28. 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
  29. Libraries 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 System
  30. Libraries With Dune

    Conclusion

    The OCaml module system allows organising a project in many ways. Dune provides several means to arrange modules into libraries.

    Module System
  31. Options

  32. 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 Structures
  33. Options

    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 Structures
  34. Options

    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 Structures
  35. Options

    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 Structures
  36. Options

    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 Structures
  37. Options

    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 Structures
  38. Options

    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 Structures
  39. Options

    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 Structures
  40. Options

    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 Structures
  41. Arrays

  42. 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 Structures
  43. Arrays

    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 Structures
  44. Arrays

    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 Structures
  45. Arrays

    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 Structures
  46. Arrays

    The Standard Library Array Module

    OCaml provides several useful functions for working with arrays. Here are some of the most common ones:

    Data Structures
  47. Arrays

    Length of an Array

    The Array.length function returns the size of an array:

    Data Structures
  48. Arrays

    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 Structures
  49. Arrays

    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 Structures
  50. Arrays

    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