714 search results for ""

Showing 251 - 300
  1. OCaml Programming Guidelines

    Clarity of OCaml Code

    The language features numerous programming styles (or programming paradigms): imperative programming (based on the notion of state and assignment), functional programming (based on the notion of

    Resources
  2. Memoization

    Memoization Using Higher-order Functions

    Now we can slightly rewrite the original fib function above using this general memoization technique: For recursive functions, however, the recursive call structure needs to be modified. T

    Data Structures
  3. Understanding the Garbage Collector

    The Fast Minor Heap

    To garbage-collect the minor heap, OCaml uses copying collection to move all live blocks in the minor heap to the major heap. This takes work proportional to the number of live blocks in the mi

    Runtime & Compiler
  4. Comparison of Standard Containers

    Set and Map: Immutable Trees

    Sets and maps are very useful in compilation and metaprogramming, but in other situations, hash tables are often more appropriate (see below). Adding an element: O(log n) Returning the number of

    Resources
  5. OCaml Programming Guidelines

    Indentation of Programs

    So each time, you must choose between the different styles suggested. The only absolute rule is the first below. When a justification for the adopted style has seemed obvious to me, I have ind

    Resources
  6. OCaml Programming Guidelines

    How to Edit Programs

    Developers describe how to use these features: the CTRL-C-CTRL-C combination recompiles the whole application; then, in case of errors, a succession of CTRL-X-` commands permits correction of

    Resources
  7. Memory Representation of Values

    Custom Heap Blocks

    The custom operations specify how the runtime should perform polymorphic comparison, hashing and binary marshaling. They also optionally contain a finalizer that the runtime calls just before th

    Runtime & Compiler
  8. Configuring Your Editor

    Using vim.lsp With runtimepath

    Then enable them in the toplevel init.lua . Add your LSP config to lsp/ocamllsp.lua . Your Neovim config should have the following structure now. Run the following at the root of your config

    Tooling
  9. Error Handling

    Using the option Type for Errors

    It tends to be considered good practice nowadays when a function can fail in cases that are not bugs (i.e., not assert false , but network failures, keys not present, etc.) to return type such a

    Guides
  10. Managing Dependencies With opam

    Installing a Package Directly

    This is handy for trying out a library, but for project work you should declare the dependency in your dune-project or *.opam file (as described above) so that collaborators and CI can reproduce

    Projects
  11. OCaml Programming Guidelines

    General principles

    Arrows of pattern-matching clauses should not be aligned. If an expression in a clause is too large to fit on one line, you must break the line immediately after the arrow of the corresponding cla

    Resources
  12. Introduction to opam Switches

    Global vs. Local Switches

    For project work, we recommend local switches. They keep each project's dependencies isolated and make it easy for collaborators to reproduce your setup. Global switches are named environments sto

    Tooling
  13. Introduction to the OCaml Toplevel

    Loading Libraries In UTop

    Tip : UTop knows about the available libraries and completion works. Outside utop you can use ocamlfind list to display the complete list of libraries. Note that opam package may bundle several l

    Tooling
  14. Error Handling

    Turning Exceptions into option or result

    Some may like to turn this into a higher-order generic function: It would be same for result , except some data must be provided to the Error constructor. The standard library does not prov

    Guides
  15. Managing Dependencies With opam

    Adding Dependencies From a Git Repository

    Sometimes, you may want to install a package directly from a Git repository, e.g., when it is not available on the opam repository or when you want to use an unreleased version.

    Projects
  16. Debugging

    Printing a Back Trace for an Uncaught Exception

    The environment variable OCAMLRUNPARAM also works when working on a program built with dune : From this back trace it should be clear that we receive a Not_found exception in List.assoc

    Guides
  17. 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
  18. OCaml Programming Guidelines

    Style dangers

    Another common “over-imperative error” in the imperative world is not to systematically choose the simple for loop to iterate on a vector's element, but instead to use a complex while loo

    Resources
  19. A Tour of OCaml

    Pattern Matching, Cont'd

    Note that OCaml throws a warning when pattern matching does not catch all cases: The underscore symbol is a catch-all pattern; it matches with anything. In this other example, the same comparis

    First Steps
  20. Introduction to opam Switches

    Switching Between Switches

    Local switches are selected automatically when you cd into their directory, but you still need to run eval $(opam env) (or use a tool like direnv ) to update the shell environment. The eval $(

    Tooling
  21. Values and Functions

    Recursive Functions

    Note : Notice that the fib_loop function has three parameters m n i but when defining fib only two arguments were passed 0 1 , using partial application. The second version fib uses the fir

    Introduction
  22. OCaml Programming Guidelines

    Pattern-matching in named functions

    <!-- $MDX skip --> Pattern-matching in functions defined by let or let rec gives rise to several reasonable styles that obey the preceding pattern-matching rules (the one for anonymous fun

    Resources
  23. OCaml Programming Guidelines

    Comparisons and Boolean operators

    Comparisons are infix operators, so the preceding rules apply. This is why f x < g x means (f x) < (g x) . For type reasons (and no other sensible interpretation), the expression f x < x + 2

    Resources
  24. Values and Functions

    Pattern Matching in Definitions

    <!--the example illustrates tuples::--> When pattern matching only has one case, it can be used in name definitions and in let ... = and fun ... -> expressions. In that case, less or more than

    Introduction
  25. OCaml Programming Guidelines

    Avoid Nocuous Comments

    <!-- $MDX skip --> An example of what to avoid, the following comment uses technical words and is thus masquerading as a real comment, but it has no additional information of interest: Absolu

    Resources
  26. Configuring Your Editor

    3) OCaml Commands With Ctrl + Shift + P

    Pressing the key combination Ctrl + Shift + P opens a modal dialog at the top. If you type the word ocaml , you will be presented with a list of various OCaml commands at your disposal which can b

    Tooling
  27. OCaml Programming Guidelines

    How to Write Long Character Strings

    <!-- $MDX skip --> Indent long character strings with the convention in force at that line, plus an indication of string continuation at the end of each line (a \ character at the end of the l

    Resources
  28. Memory Representation of Values

    String Values

    Care should be taken that any C library functions that receive these buffers can also cope with arbitrary bytes within the buffer contents and are not expecting C strings. For instance, the C me

    Runtime & Compiler
  29. Introduction to opam Switches

    Listing Available Compilers

    Omitting ocaml-base-compiler shows the full list, including compiler variants with additional options enabled (such as flambda optimisations or frame pointers). These are useful for advanced use ca

    Tooling
  30. Understanding the Garbage Collector

    Next-Fit Allocation

    Next-fit allocation is quite a cheap allocation mechanism, since the same heap chunk can be reused across allocation requests until it runs out. This in turn means that there is good memory loc

    Runtime & Compiler
  31. Comparison of Standard Containers

    Strings: Immutable Vectors

    Adding an element (by creating a new string): O(n) Length: O(1) Accessing character i : O(1) Finding an element: O(n) Strings are very similar to arrays, but they are immutable. Strings are s

    Resources
  32. Sequences

    Sequence Consumers: Partially Applied Functions as Parameters

    A consumer is a function that processes a sequence, consuming its elements. Consumers should be written as higher-order functions that take a function parameter. This allows for deferred evalua

    Data Structures
  33. OCaml Docker Images

    The opam-repository Snapshot May Be Stale

    Each image ships with a copy of opam-repository from the time the image was built. Since images are rebuilt weekly, the repository may be up to a week out of date. Run opam update before instal

    Additional Tooling
  34. Higher Order Functions

    Binding as early returns

    The main difference is that in this case Result.bind is biased towards Ok value , so that if a result value is an Error reason , it will short-circuit through the binds and just return the first

    Introduction
  35. Common Error Messages

    x.cmi is not a compiled interface

    It means that some_module.cmi is not valid according to the current version of the OCaml compiler. Most of the time, removing the old compiled files ( .cmi, .cmo, *.cmx, ...) and recompiling is

    Resources
  36. Modules

    Interfaces and Implementations

    This triggers a compilation error. You can check that Cairo.message is not public by attempting to compile a delhi.ml file containing: Compile and execute both programs: Update the dune

    Module System
  37. Mutability and Imperative Control Flow

    Immutable vs Mutable Data

    In the following sections, we introduce OCaml's language features for dealing with mutable states. When you use let … = … to bind a value to a name, this name-value binding is immutable , s

    Introduction
  38. OCaml Docker Images

    Default User is opam , Not root

    When copying files into the image, set ownership so the opam user can access them: When you use these images as a base in a Dockerfile ( FROM ocaml/opam... ), commands run as the opam user by

    Additional Tooling
  39. Common Error Messages

    Warning: Illegal backslash escape in string

    Recent versions of OCaml warn you against unprotected backslashes in strings since they should be doubled. Such a message may be displayed when compiling an older program, and can be turned off

    Resources
  40. OCaml Programming Guidelines

    Be Simple and Readable

    Writing programs law : A program is written once, modified ten times, and read 100 times. So it's beneficial to simplify its writing, always keep future modifications in mind, and never jeopardi

    Resources
  41. Common Error Messages

    This pattern is unused

    In our example, it is now clear that only the first item of the pair will ever be tested. This leads to the following results: the tree of cases is traversed linearly, from left to right. There

    Resources
  42. The Compiler Frontend: Parsing and Type Checking

    Syntax Errors

    The syntax error points to the line and character number of the first token that couldn't be parsed. In the broken example, the module keyword isn't a valid token at that point in parsing, so t

    Runtime & Compiler
  43. Hash Tables

    Creating a Polymorphic Hash Table

    The '_weak1 and '_weak2 correspond to the key and value types, respectively. There are no concrete types (e.g., int or float * string ) filled in those slots because the type of the key an

    Data Structures
  44. Comparison of Standard Containers

    Buffer: Extensible Strings

    Adding a char: O(1) if the buffer is big enough, or O(log n) on average if the initial buffer size was much smaller than the number of bytes n . Adding a string of k chars: O(k * "adding

    Resources
  45. OCaml Programming Guidelines

    Other Emacs tricks

    Under Unix, the CTRL-C-CTRL-C or Meta-X compile combination, followed by CTRL-X-` , is also used to find all occurrences of a certain string in an OCaml program. Instead of launching ma

    Resources
  46. OCaml Programming Guidelines

    Single branches

    If cond , e1 , and e2 are small, simply write them on one line: If the expressions making up a conditional are purely functional (without side effects), we advocate binding them within the

    Resources
  47. OCaml Programming Guidelines

    Multiple branches

    Yet again, choose your style and use it systematically. Justification : elsif is a keyword in many languages, so use indentation and else if to bring it to mind. Moreover, you do not have t

    Resources
  48. Mutability and Imperative Control Flow

    Byte Sequences

    <!-- FIXME: link to a dedicated Byte Sequences tutorial --> Note : the bytes type uses a much more compact memory representation than char array . As of writing this tutorial, there is an 8-fact

    Introduction
  49. A Tour of OCaml

    Recursive Functions

    Each => sign corresponds to the computation of a recursive step, except the last one. OCaml handles lists internally, as shown in the penultimate expression, but displays them as the last expressio

    First Steps
  50. Error Handling

    Errors as Special Values

    The rest of this document presents and compares approaches towards error handling. Exceptions provide a means to deal with errors at the control flow level, while option and result make error

    Guides