638 search results for ""

Showing 301 - 350
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. Functors

    Writing Your Own Functors

    <!-- TODO: Create this section When several implementations of the same interface are needed at runtime, functors allow sharing of their common parts. ## Multiple Implementation of the Same Signat

    Module System
  13. 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
  14. 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
  15. Basic Data Types and Pattern Matching

    Byte Sequences

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

    Introduction
  16. 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 b

    Introduction
  17. 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
  18. 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
  19. Sequences

    Miscellaneous Considerations

    <!-- ## Credits * Authors: 1. Cuihtlauac Alvarado [@cuihtlauac](https://github.com/cuihtlauac) * Suggestions and Corrections: * Miod Vallat [@dustanddreams](https://github.com/dustanddreams)

    Data Structures
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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 descr

    Projects
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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 ad

    Tooling
  35. 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
  36. 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
  37. 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
  38. 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
  39. Labelled and Optional Arguments

    Labelling Parameters

    At parameter definition ~first is the same as ~first:first . Passing argument ~last is the same as ~last:last . It is possible to use a shorter syntax when using the same name as label and p

    Introduction
  40. Transitioning to Multicore with ThreadSanitizer

    An Example Application

    Underneath the hood, the library may have been implemented in various ways. Consider the following thread-unsafe implementation in bank.ml : Consider a little bank library with the following

    Guides
  41. Formatting and Wrapping Text

    Printing Spaces

    Generally speaking, a printing routine using "format", should not directly output white spaces: the routine should use break hints instead. (For instance print_space () that is a convenient a

    Tutorials
  42. Understanding the Garbage Collector

    Heap Compaction

    <div class="note"> The heap compaction cycle avoids this by relocating all the values in the major heap into a fresh heap that places them all contiguously in memory again. A naive implementati

    Runtime & Compiler
  43. Bootstrapping a Project with Dune

    More Comprehensive Scaffolding

    spin drom carcass If you're looking for project templates that include more than the basics, there are other community projects that offer more comprehensive project scaffolding:

    Projects
  44. Installing OCaml

    Install opam

    Advanced Windows Users : If you are familiar with Cygwin or WSL2, there are other installation methods described on the OCaml on Windows page. On Windows, the winget package is maintained by opa

    First Steps
  45. OCaml Programming Guidelines

    How to Comment Programs

    Avoid comments in the bodies of functions. Prefer one comment at the beginning of the function that explains how a particular algorithm works. Once more, if there is no difficulty, there is no

    Resources
  46. Mutability and Imperative Control Flow

    References

    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
  47. Objects

    Objects and Classes

    s is an opaque object. The implementation (i.e., the list) is hidden from callers. In the OCaml toplevel, we can examine the types of objects and methods in more detail: Notice the syntax.

    Advanced Topics
  48. Modules

    Abstract and Read-Only Types

    Abstract and read-only types can be either variants, as shown in this section, records, or aliases. It is possible to access a read-only record field's value, but creating such a record requires usin

    Module System
  49. Sequences

    Taking Parts of a Sequence

    This can be used to print integers without looping forever, as shown previously: When executed, the function begins by unfreezing seq (that is, calling seq () ) and then pattern matching to loo

    Data Structures
  50. Higher Order Functions

    Mapping Custom Data Types

    Note that the structure of the tree is preserved, but every time we encounter a value , we update it with (fn value) . When working with our custom data types, such as the tree we used in the

    Introduction