638 search results for ""

Showing 151 - 200
  1. Managing Dependencies With opam

    Adding a Git Dependency to Your .opam File

    Finally, use opam install to install the dependencies, including the one specified in the pin-depends field. Add the pin-depends field in the opam file if it doesn't exist. Inside this fie

    Projects
  2. Loops and Recursions

    For Loops and While Loops

    <!-- $MDX skip --> Luckily OCaml does have references, so we can write the code above if we want. Don't get confused and think that the ! (exclamation mark) means "not" as in C/Java. It's

    Introduction
  3. Mutability and Imperative Control Flow

    Recommendations for Mutable State and Side Effects

    Functional and imperative programming styles are often used together. However, not all ways of combining them give good results. We show some patterns and anti-patterns relating to mutable states and

    Introduction
  4. OCaml Programming Guidelines

    When to Use Parentheses Within an Expression

    Parentheses are meaningful. They indicate the necessity of using an unusual precedence, so they should be used wisely and not sprinkled randomly throughout programs. To this end, you should know

    Resources
  5. The Compiler Backend: Bytecode and Native code

    Activating the Debug Runtime

    </div> To use the debug library, just link your program with the -runtime-variant d flag: Despite your best efforts, it is easy to introduce a bug into some components, such as C bindings, t

    Runtime & Compiler
  6. Command-line Arguments

    Using the Arg Module

    The Arg module has many more actions than just Set and Set_string , and some lower-level function for parsing more complicated command lines. Here is the whole program: <!-- $MDX dir=exam

    Tutorials
  7. Your First OCaml Program

    Every File Defines a Module

    <!-- FIXME refer to Dune/Library tutorial when available --> Note : If you add a file named hello.ml in the lib directory, Dune will consider this the whole Hello module and it will make En

    First Steps
  8. Understanding the Garbage Collector

    Controlling Frequency of Compactions

    </div> A value of 0 triggers a compaction after every major garbage collection cycle, whereas the maximum value of 1000000 disables heap compaction completely. The default settings should

    Runtime & Compiler
  9. Preprocessors and PPXs

    Attributes and Derivers

    ppx_show generates a pretty printer from a type for values of this type. Derivers that derive serializers from OCaml types to other formats, such as JSON with ppx_yojson_conv , YAML with ppx

    Advanced Topics
  10. Error Handling

    Composing Functions Returning Options

    The recommended way to avoid that is to refrain from or delay attempting to access the content of an option value, as explained in the next sub section. Linux Kernel Style Guide if you need mor

    Guides
  11. OCaml Programming Guidelines

    Destructuring let bindings

    let with complex patterns: let [x; y] as l = ... simultaneously defines a list l and its two elements x and y . let with simple pattern: let _ = ... does not define anything, it just

    Resources
  12. OCaml Programming Guidelines

    Comments line by line in imperative code

    When writing difficult code, and particularly in case of highly imperative code with a lot of memory modifications (physical mutations in data structures), it is sometimes mandatory to comment in

    Resources
  13. Understanding the Garbage Collector

    Attaching Finalizer Functions to Values

    <div class="note"> OCaml's automatic memory management guarantees that a value will eventually be freed when it's no longer in use, either via the GC sweeping it or the program terminating. It'

    Runtime & Compiler
  14. Labelled and Optional Arguments

    Passing Labelled Arguments Using the Pipe Operator

    Let's modify the range function previously defined by adding an additional parameter step . Declaring a function's unlabelled argument as the first one simplifies reading the function's type an

    Introduction
  15. A Tour of OCaml

    Type Conversion and Type-Inference

    There are several reasons why OCaml requires explicit conversions. Most importantly, it enables types to be worked out automatically. OCaml's type inference algorithm computes a type for each expre

    First Steps
  16. The Compiler Frontend: Parsing and Type Checking

    Preprocessing with ppx

    There are two primary forms of extension points in OCaml: attributes and extension nodes . Let's first run through some examples of what they look like, and then see how to use them in your ow

    Runtime & Compiler
  17. Mutability and Imperative Control Flow

    Good: Functional by Default

    Most existing modules provide an interface meant to be used in a functional way. Some require the development and maintenance of wrapper libraries to be used in an imperative setting and such use r

    Introduction
  18. A Tour of OCaml

    Modules and the Standard Library

    Modules also allow for efficient separate compilation. This is illustrated in the next tutorial. This illustrates the first feature of the OCaml module system. It provides a means to separate concer

    First Steps
  19. The Compiler Frontend: Parsing and Type Checking

    The Typed Syntax Tree

    The cmt files are particularly useful for IDE tools to match up OCaml source code at a specific location to the inferred or external types. For example, the merlin and ocaml-lsp-server opam

    Runtime & Compiler
  20. Calling Fortran Libraries

    Step 2: Create the C Wrapper

    The file must include the OCaml header files alloc.h , memory.h , and mlvalue.h . The function first calls the CAMLparam5 macro. This is required at the start of any function that uses the CAM

    Tutorials
  21. Mutability and Imperative Control Flow

    Mutable Record Fields

    Remark : the left arrow symbol <- for mutating mutable record field values is not an operator function, like the assignment operator ( := ) is for refs . It is rather a construct of the langua

    Introduction
  22. OCaml Programming Guidelines

    Pattern-matching warnings

    Nonexhaustive pattern-matches induced by clauses with guards must also be corrected. A typical case consists in suppressing a redundant guard. Justification : It's not really more complicated t

    Resources
  23. Memory Representation of Values

    OCaml Blocks and Values

    OCaml uses a uniform memory representation in which every OCaml variable is stored as a value . An OCaml value is a single memory word that is either an immediate integer or a pointer to some ot

    Runtime & Compiler
  24. Mutability and Imperative Control Flow

    It Depends: Module State

    On the other hand, a module may define mutable data internally impacting its behaviour without exposing it in its interface. This is inadvisable. For example, the Hashtbl module provides an inte

    Introduction
  25. Your First OCaml Program

    Defining Module Interfaces

    This is because we haven't changed lib/en.mli . Since it does not list hello , it is therefore private. Trying to compile this fails. Also edit the bin/main.ml file like this: Amend the

    First Steps
  26. Functors

    Injecting Dependencies Using Functors

    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
  27. OCaml on Windows

    Installing Opam on Windows

    You should now have a functioning OCaml environment ready for development. If you encounter any issues or need further assistance, don't hesitate to consult the OCaml community . You can verify y

    Resources
  28. Mutability and Imperative Control Flow

    Good: Function-Encapsulated Mutability

    The function sum is written in an imperative style, using mutable data structures and a for loop. However, no mutability is exposed. It is a fully encapsulated implementation choice. This functio

    Introduction
  29. Understanding the Garbage Collector

    Intergenerational Pointers

    OCaml maintains a set of such intergenerational pointers to avoid this dependency between a major and minor heap collection. The compiler introduces a write barrier to update this so-called re

    Runtime & Compiler
  30. The Compiler Backend: Bytecode and Native code

    The Untyped Lambda Form

    The lambda form is the key stage that discards the OCaml type information and maps the source code to the runtime memory model described in Memory Representation Of Values . This stage also

    Runtime & Compiler
  31. Operators

    Operator Associativity and Precedence

    The complete list of precedence is longer because it includes the predefined operators that are not allowed to be used as custom operators. The OCaml Manual has a table that sums up the operator as

    Advanced Topics
  32. Managing Dependencies With opam

    Installing Existing Dependencies

    Or if you set your environment with eval $(opam env) : Once the dependencies have been installed successfully, and assuming the project uses Dune as the build system, you can compile it with:

    Projects
  33. Values and Functions

    Currying and Uncurrying

    They allow partial application No parentheses or commas No pattern matching over a tuple takes place In practice, curried functions are the default because: <!-- Currying and uncurrying can be under

    Introduction
  34. Formatting and Wrapping Text

    Indentation of New Lines

    when defining the box : when you open a box, you can fix the indentation added to each new line opened within that box. For instance: open_hovbox 1 opens a “hov” box with new lines indent

    Tutorials
  35. OCaml Programming Guidelines

    How to Choose Between Classes and Modules

    Use modules when the data structures are fixed and their functionality is equally fixed or it's enough to add new functions in the programs which use them. Use conventional data structures (in p

    Resources
  36. Loops and Recursions

    Looping Over Lists

    (Notice that this factorial function isn't very useful because it overflows the integers and gives wrong answers even for quite small values of n .) That was easy! Notice that I've accidental

    Introduction
  37. Values and Functions

    Tuples as Function Parameters

    In many imperative languages, the spicy_cat ("hello", "world") syntax reads as a function call with two arguments; but in OCaml, it denotes applying the function spicy_cat to a tuple containing

    Introduction
  38. Higher Order Functions

    Iterating over custom data types

    Again, we iterate by pattern matching on values, applying a function to the deconstructed value and recursing over the remaining data. For our example, we'll iterate from the top down as we go alo

    Introduction
  39. Understanding the Garbage Collector

    Best-Fit Allocation

    Best-fit allocation is the default allocation mechanism. It represents a good trade-off between the allocation cost (in terms of CPU work) and heap fragmentation. Small allocations, when there a

    Runtime & Compiler
  40. Command-line Arguments

    Other Tools for Parsing Command-Line Options

    Cmdliner is a modern interface for command line processing, which also generates UNIX man pages automatically. Clap is an imperative command line parser. Minicli has good support for rej

    Tutorials
  41. Values and Functions

    Discarding Values Using Pattern Matching

    <!-- END Version Two --> Tuples behave differently from records; contained data is anonymous, and its position is used to access it. To discard the email value from the tuple of the contact fi

    Introduction
  42. Memory Representation of Values

    Tuples, Records, and Arrays

    The Obj.repr function retrieves the runtime representation of any OCaml value. Obj.is_block checks the bottom bit to determine if the value is a block header or an unboxed integer. You can

    Runtime & Compiler
  43. OCaml Programming Guidelines

    Data Structures

    The same objection is admissible for enumerated types represented as integers when those integers have an evident interpretation with respect to the represented data. <!-- $MDX skip --> A cont

    Resources
  44. Basic Data Types and Pattern Matching

    Constructors With Data

    The constructor C1 has two parameters of type int and bool , whilst the constructor C2 has a single parameter of type int * bool . Warning : Wrapping product types with parentheses turns t

    Introduction
  45. Loops and Recursions

    Mutually Recursive Functions

    You can also use similar syntax for writing mutually recursive class definitions and modules. There are no "forward prototypes" (as seen in languages descended from C) in OCaml, but there is

    Introduction
  46. The Compiler Backend: Bytecode and Native code

    Profiling Native Code

    Note that many other tools that operate on native binaries, such as Valgrind, will work just fine with OCaml as long as the program is linked with the -g flag to embed debugging symbols. GNU g

    Runtime & Compiler
  47. Error Handling

    bind as a Binary Operator

    OCaml has a strict typing discipline, not a strict styling discipline; therefore, picking the right style is left to the author's decision. That applies error handling, so pick a style knowingly.

    Guides
  48. Comparison of Standard Containers

    Lists: Immutable Singly-Linked Lists

    Not very efficient for: random access, indexed elements Well-suited for: I/O, pattern-matching Adding an element: O(1) , cons operator :: Length: O(n) , function List.length Accessing cell i

    Resources
  49. Formatting and Wrapping Text

    Practical Advice

    Boxes must be opened and closed consistently ( open_* and close_box must be nested like parentheses). Never hesitate to open a box. Output many break hints, otherwise the pretty-printer is in a

    Tutorials
  50. Configuring Your Editor

    2) Jump to Definitions With Ctrl + Click

    If you hold down the Ctrl key while hovering, the code appears as a clickable link which if clicked takes you to the file where the implementation is. This can be great if you want to understand ho

    Tooling