714 search results for ""

Showing 301 - 350
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. Error Handling

    Using Fun.protect

    When head_file is called, it opens a file descriptor, defines finally and work , then Fun.protect ~finally work performs two computations in order: work () and then finally () , and has t

    Guides
  7. Basic Data Types and Pattern Matching

    Recursive Variants

    Here, the last pattern uses the symbol _ , which catches everything. It returns false on all data that is neither Array nor Object . Functions defined using pattern matching on recursive var

    Introduction
  8. Configuring Your Editor

    Getting Type Information in Vim

    In the Vim editor, press Esc to enter command mode. Place the cursor over the variable. Type :MerlinTypeOf and press Enter . The type information will be displayed in the command bar. Other Me

    Tooling
  9. Basic Data Types and Pattern Matching

    Functions

    (int -> int) -> int : This function takes a function of type int -> int as a parameter and returns an int as the result. int -> (int -> int) : This function takes an int as a parameter and re

    Introduction
  10. OCaml Programming Guidelines

    Don't use abbreviations for global names

    Global identifiers (including the names of functions) can be long because it's important to understand what purpose they serve far from their definition.

    Resources
  11. Error Handling

    Throwing Exceptions From option or result

    To raise other exceptions, pattern matching and raise must be used. From option to Invalid_argument exception, use function Option.get : From result to Invalid_argument exception, use

    Guides
  12. Configuring Your Editor

    Choosing a major mode

    For the purposes of this tutorial, we are going to focus on the use of tuareg as the major mode, but you should feel free to experiment and choose your favourite one! To use tuareg , you can add

    Tooling
  13. The Compiler Frontend: Parsing and Type Checking

    Parsing Source Code

    When a source file is passed to the OCaml compiler, its first task is to parse the text into a more structured abstract syntax tree (AST). The parsing logic is implemented in OCaml itself using t

    Runtime & Compiler
  14. Functors

    Functors From the Standard Library

    Set.S Map.S Hashtbl.S The functors Set.Make , Map.Make , and Hashtbl.Make return modules satisfying the interfaces Set.S , Map.S , and Hashtbl.S (respectively), which all contain an abstract

    Module System
  15. Values and Functions

    Pattern Matching on unit

    <!-- user-defined single constructor variant example --> Note : In order for compiled files to only evaluate an expression for its side effects, you must write them after let () = . Above, the pa

    Introduction
  16. Higher Order Functions

    Introduction

    Here's some other examples from the real world: This is the power of Higher-Order Functions . They empower you to create complex behaviors from simpler functions. And we can use repeat to re

    Introduction
  17. Introduction to opam Switches

    Creating a Local Switch

    If the directory contains .opam files, opam will automatically install their dependencies into the new switch. You can prevent this with opam switch create . 5.4.0 --no-install . This creates an

    Tooling
  18. Higher Order Functions

    Currying and Uncurrying

    Before we get to some examples, let's define some helper functions that will help us curry and uncurry functions. A curried add function will be called like add x y . An uncurried add function

    Introduction
  19. A Tour of OCaml

    Polymorphic Functions on Lists

    This function operates not just on lists of integers but on any kind of list. It is a polymorphic function. Its type indicates input of type 'a list where 'a is a type variable standing for any t

    First Steps
  20. Error Handling

    Predefined Exceptions

    Both can make sense, and there isn't a general rule. If the standard library exceptions are used, they must be raised under their intended conditions, otherwise handlers will have trouble process

    Guides
  21. Preprocessors and PPXs

    Source Preprocessors

    In OCaml, preprocessing text files do not have specific support from the language. Instead it is the build system's role to drive the preprocessing. So, applying preprocessors will boil down to t

    Advanced Topics
  22. Preprocessors and PPXs

    Preprocessing With Dune

    Putting it all together, the following dune file would rewrite the corresponding module files using our previously written preprocessor.sh : The stanza to apply preprocessing on the source fi

    Advanced Topics
  23. Basic Data Types and Pattern Matching

    Byte Sequences

    The memory representation of bytes is four times more compact than char array . Operations on bytes values are provided by the Stdlib and the Bytes modules. Only the function Bytes.get al

    Introduction
  24. Sequences

    Be Aware of Seq.Cons vs Seq.cons

    Let's look at how confusing Seq.Cons and Seq.cons can lead to unintended behavior. Now that we have seen these two versions of "cons-ing" can construct the same sequence, it begs the questio

    Data Structures
  25. OCaml Docker Images

    Docker Hub Repository: ocaml/opam

    Note: The older repositories ocaml/opam2 , ocaml/opam2-staging , ocurrent/opam , and ocaml/ocaml are no longer updated . Use ocaml/opam for the latest images. The official OCaml Docker imag

    Additional Tooling
  26. Values and Functions

    Pattern Matching in Function Parameters

    Note Using the discard pattern for parameter declaration is also possible. Here is an example with the name record: Here is an example with tuples: Single-case pattern matching can also be

    Introduction
  27. 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
  28. Mutability and Imperative Control Flow

    Dereference Operator

    it is impossible to create uninitialised references, and the mutable content and the reference have different syntax and type: no confusion between them is possible. When working with mutable data in

    Introduction
  29. Error Handling

    External Resources

    <!-- Acknowledgements - Authors 1. Simon Cruanes [@c-cube](https://github.com/c-cubeauthored) 2. John Whitington [@johnwhitington](https://github.com/johnwhitington) 3. Cuihtlauac Alvarado [@c

    Guides
  30. Profiling

    Basics of Assembly Language

    Almost all of the assembly language that we will look at is going to be dominated not by machine code instructions like movl but by what are known as assembler directives . These directives be

    Guides
  31. Arrays

    Copying Part of an Array into Another Array

    This copies two elements of zeroes , starting at index 1 into the last part of zeroes , starting at index 3 . We can also use this function to copy part of an array onto itself: This copies

    Data Structures
  32. Higher Order Functions

    Iterating over Lists

    That's exactly how List.iter is defined in the standard library. And this way we can call print_all with any function fn , so it really is just iterating over the list and running a function ov

    Introduction
  33. Operators

    Binding Operators

    <!-- TODO: move this into the list tutorial In the following example, we use that mechanism to write a function which produces the list of Friday 13th dates between two years. ```ocaml # let ( let

    Advanced Topics
  34. Values and Functions

    Applying Functions

    There are two alternative ways to apply functions. Labelled and optional parameters are detailed in the Labelled Arguments tutorial. Some functions, such as String.starts_with have labelled par

    Introduction
  35. Labelled and Optional Arguments

    Passing Optional Arguments

    It is also possible to pass optional arguments as values of type option . This is done using a question mark when passing the argument. Optional arguments can be omitted. When passed, a tilde

    Introduction
  36. Your First OCaml Program

    Working Within an opam Switch

    When you work on several OCaml projects simultaneously, you should create more opam switches. For instructions on how to do that, see Introduction to opam Switches . When you installed OCaml, a glo

    First Steps
  37. 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
  38. Monads

    The Maybe Monad

    Now that we're done playing with integer operators, we should restore their original meaning for the rest of this file: The result is we get code that (once you understand how to read the bind

    Data Structures
  39. Labelled and Optional Arguments

    Passing Labelled Arguments

    Note : Passing labelled arguments through the pipe operator ( |> ) throws a syntax error: Labelled arguments are passed using a tilde ~ and can be placed at any position and in any order. T

    Introduction
  40. Running Executables and Tests with Dune

    Running Tests

    If we run dune test again, the test should be successful and output the following: With the following module: Let's modify our dummy test to link to Alcotest: The output is not very descri

    Projects
  41. Higher Order Functions

    Common Higher-Order Functions

    Currying and uncurrying Pipelining, composition, and chaining Iterating Filtering Mapping Folding (or reducing) Sorting Binding (or flat mapping) In the wild, there's certain patterns that repeat ov

    Introduction
  42. Calling C Libraries

    MiniGtk

    (Pop quiz: what happens if we need to define a class which is both a base class from which other classes can be derived, and is also a non-virtual class of which the user should be allowed to cre

    Tutorials
  43. OCaml Programming Guidelines

    The hd and tl Functions

    Justification : This is just as brief as and much clearer than using hd and tl , which must be protected by try... with... to catch the exception that might be raised by these functions.

    Resources
  44. OCaml-CI

    Main Sources of OCaml-CI Documentation

    Getting Started page : https://ocaml.ci.dev/getting-started Very brief, covers only the basic setup steps GitHub README : https://github.com/ocurrent/ocaml-ci The most comprehensive source Covers

    Additional Tooling
  45. Values and Functions

    Defining Functions with Multiple Parameters

    To define a function with multiple parameters, each must be listed between the name of the function (right after the let keyword) and the equal sign, separated by space:

    Introduction
  46. Calling Fortran Libraries

    Step 4: Now to OCaml

    And voila, we've called the fortran function from OCaml. prompt> ocamlc -o test gtd6.cmo wrapper.so prompt> ocamlc -c gtd6.ml At this point, the steps that are given are to compile this into byt

    Tutorials
  47. Values and Functions

    Forms of Pattern Matching

    In the following sections, we explore matching inside let bindings, which is a special case. In the next chapter on Basic Data Types and Pattern Matching , we examine pattern matching in general c

    Introduction
  48. Introduction to opam Switches

    What Is an opam Switch?

    After installing OCaml , you'll have a single switch called default . An opam switch is an isolated OCaml environment. Each switch has its own OCaml compiler, installed packages, and binaries, all

    Tooling
  49. 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
  50. Sequences

    Filtering a Sequence

    Side Note : It may be interesting to learn that trial_div , while it can colloquially be called a recursive, is an example of a kind of recursion called corecursion . Corecursion differs from

    Data Structures