714 search results for ""

Showing 51 - 100
  1. Preprocessors and PPXs

    Restricting PPXs for Composition, Speed, and Security

    Note that Dune combines all PPXs written using ppxlib in a single preprocessor binary, even if the PPXs come from different packages. Compared to this, rewriters that work on the whole AST can a

    Advanced Topics
  2. The Compiler Backend: Bytecode and Native code

    Generating Portable Bytecode

    <div class="note"> There are around 140 instructions in total, but most are just minor variants of commonly encountered operations (e.g., function application at a specific arity). You can find

    Runtime & Compiler
  3. Mutability and Imperative Control Flow

    if … then … else … and Side Effects

    Failing to group in the first branch results in a syntax error. What's before the semicolon is parsed as an if … then … without an else expression. What's after the semicolon appears as a da

    Introduction
  4. Error Handling

    Using the result Type for Errors

    Handling errors necessarily complicates code, making it harder to read and understand than simple code that behaves incorrectly or fails under exceptional conditions. The right tools, data, and f

    Guides
  5. The Compiler Backend: Bytecode and Native code

    Summarizing the File Extensions

    .o are compiled native object files of the module implementation. .cmx contains extra information for linking and cross-module optimization of the object file. .cmxa and .a are libraries of c

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

    Compiling and Linking Bytecode

    The bytecode files are then linked together with the OCaml standard library to produce an executable program. The order in which .cmo arguments are presented on the command line defines the ord

    Runtime & Compiler
  7. OCaml Programming Guidelines

    Sequence warnings and let _ = ...

    Justification : Sequences are much clearer! Compare e1; e2; e3 to In any case, use the let _ = ... construction exactly in those cases where you want to ignore a result. Don't systematicall

    Resources
  8. Mutability and Imperative Control Flow

    Good: Application-Wide State

    Note : Here, the state is copied, which is not memory efficient. In a memory-aware implementation, state-update functions would produce a “diff” (data describing the difference between the state'

    Introduction
  9. Your First OCaml Program

    Installing and Using Modules From a Package

    Finally, execute as before: Fun fact : Dune configuration files are S-expressions. Before the example will build and run, you need to tell Dune that it needs Sexplib to compile the project. D

    First Steps
  10. Using the OCaml Compiler Toolchain

    Using the ocamlfind Front-End

    Separate compilation (one command for module1.ml , another for module2.ml and another to link the final output) is usually not performed manually but only when using an automated build system t

    Guides
  11. OCaml Programming Guidelines

    Separate words by underscores: ( int_of_string , not intOfString )

    Case modifications are meaningful in OCaml. In effect, capitalised words are reserved for constructors and module names. In contrast, regular variables (functions or identifiers) must start with

    Resources
  12. OCaml Programming Guidelines

    No beastly alignment of the -> symbols in pattern-matching clauses

    Justification : This makes it harder to maintain the program (the addition of a supplementary case can lead to changes in all indentations, so we often give up alignment at that time. In this

    Resources
  13. OCaml Programming Guidelines

    How to Write Operator Symbols

    Justification : If you left out the spaces then x+1 would be understood, but x+!y would change its meaning, since +! would be interpreted as a multicharacter operator. Criticism : The abse

    Resources
  14. Values and Functions

    What Makes Functions Different From Other Values

    <!-- - Pattern matching does not allow inspecting a function. Catch-all patterns can match against a function, but it is useless. ```ocaml # match Fun.id with _ -> ();; - : unit = () ``` --> <!-- It

    Introduction
  15. Your First OCaml Program

    Using the Preprocessor to Generate Code

    Here is the result: Finally, you'll also need to edit bin/main.ml v has the type string list . We're using String.split_on_char to turn a string into a string list by splitting the str

    First Steps
  16. Mutability and Imperative Control Flow

    Example: get_char Function

    In the second call to tcsetattr , we restore the terminal attributes to their initial state. In this implementation, the record returned by the call to tcgetattr is not modified. A copy is made u

    Introduction
  17. Managing Dependencies With opam

    Adding a Git Dependency to a dune-project File

    to install the new dependency you added. Then, run Next, regenerate the .opam file of your project by running For example, if your project's opam file is my_project.opam , create my_projec

    Projects
  18. Higher Order Functions

    Pipelines, Composition, and Chaining

    <!-- NOTE(@leostera): this example kinda sucks, i'd like one where the use of labels greatly improves the readability but since `ListLabels.nth_opt` doesn't take an argument then we still need that n

    Introduction
  19. Memory Representation of Values

    Floating-Point Numbers and Arrays

    Only records and arrays can have the float array optimization, and for records, every single field must be a float. The first thing we tested was that a float array has the correct unboxed float

    Runtime & Compiler
  20. Objects

    Inheritance, Virtual Classes, Initialisers

    Let's create a label which says "Press me!" and add it to the button: Here's our comparatively trivial label class: Before defining our label class, let's play with the button class in

    Advanced Topics
  21. The Compiler Backend: Bytecode and Native code

    Compiling Fast Native Code

    Collections of .cmx and .o files can also be linked into a .cmxa archive by passing the -a flag to the compiler. However, unlike the bytecode version, you must keep the individual cmx fi

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

    Understanding Name Mangling

    Anonymous functions are hard to predict without inspecting intermediate compiler output. If you need to debug them, it's usually easier to modify the source code to let-bind the anonymous functio

    Runtime & Compiler
  23. OCaml Programming Guidelines

    How to Indent Global let ... ;; Definitions

    Justification : The first line of the definition is offset nicely, so it's easier to pass from definition to definition. Criticism : You run into the right margin too quickly. <!-- $MDX skip --

    Resources
  24. Formatting and Wrapping Text

    Most General Pretty-Printing: Using fprintf

    Given those general printing routines, procedures to print to stdout or stderr is just a matter of partial application: Using fprintf , the lambda-terms printing routines can be written as

    Tutorials
  25. The Compiler Backend: Bytecode and Native code

    Benchmarking Polymorphic Comparison

    <div class="note"> We see that the polymorphic comparison is close to 10 times slower! These results shouldn't be taken too seriously, as this is a very narrow test that, like all such microben

    Runtime & Compiler
  26. Calling Fortran Libraries

    Step 1: Compile the Fortran Routine

    Note that it's up to the caller to know that dens and temp are actually arrays. Failure to pass an array will cause a segmentation violation since the gtd6_ function is using them as arrays (

    Tutorials
  27. Preprocessors and PPXs

    The Limits of Manipulating Text Files

    Working with a much more structured representation of a program solves both the reading and writing issues. This is exactly what PPXs do! It is difficult to read parts of the program, such as the ty

    Advanced Topics
  28. OCaml Programming Guidelines

    Function application: same rules as for trigonometric functions

    In mathematics you write sin x to mean sin (x) . In the same way sin x + cos x means (sin x) + (cos x) not sin (x + (cos x)) . Use the same conventions in OCaml: write f x + g x to mean

    Resources
  29. The Compiler Backend: Bytecode and Native code

    Benchmarking Pattern Matching

    The lambda form is primarily a stepping stone to the bytecode executable format that we'll cover next. It's often easier to look at the textual output from this stage than to wade through the nat

    Runtime & Compiler
  30. Values and Functions

    Nested Pattern Matching on User-Defined Types

    Notice that contact is now available at the top-level as a bound variable: Next, we demonstrate the two-phase approach for accessing email and phone . This brings contact into our top-lev

    Introduction
  31. The Compiler Frontend: Parsing and Type Checking

    An Overview of the Toolchain

    Notice that the pipeline branches toward the end. OCaml has multiple compiler backends that reuse the early stages of compilation but produce very different final outputs. The bytecode can be r

    Runtime & Compiler
  32. Understanding the Garbage Collector

    Mark and Sweep Garbage Collection

    All blocks reachable from the roots by following edges in the graph must be retained, and unreachable blocks can be reused by the application. The algorithm used by OCaml to perform this heap tra

    Runtime & Compiler
  33. Memory Representation of Values

    OCaml Types Disappear at Runtime

    We'll cover how these values are managed by the runtime later on in Understanding The Garbage Collector . <!----> We'll explain this compilation pipeline in more detail in The Compiler Fronte

    Runtime & Compiler
  34. Preprocessors and PPXs

    Extension Nodes and Extenders

    Extenders which allow users to write OCaml values representing another language directly in such language. For example: - ppx_yojson to generate Yojson values by writing JSON code - tyxml-

    Advanced Topics
  35. Memory Representation of Values

    Integers, Characters, and Other Basic Types

    These basic types such as empty lists and unit are very efficient to use, since integers are never allocated on the heap. They can be passed directly in registers and not appear on the stack if

    Runtime & Compiler
  36. Mutability and Imperative Control Flow

    Bad: Undocumented Mutation

    <!-- TODO: ### Bad: Stateful External Factor GOTCHA: This is the dual of the previous anti-pattern. “Mutable in disguise” is an unintended or undocumented side-effect performed by a function.

    Introduction
  37. The Compiler Frontend: Parsing and Type Checking

    Modules and Separate Compilation

    This section discusses how the compiler implements them in more detail. Modules are essential for larger projects that consist of many source files (also known as compilation units ). It's impra

    Runtime & Compiler
  38. Understanding the Garbage Collector

    The Mutable Write Barrier

    The only way to know for sure is to benchmark your program under real-world scenarios using Core_bench and experiment with the trade-offs. The command-line benchmark binaries have a number of

    Runtime & Compiler
  39. Transitioning to Multicore with ThreadSanitizer

    Write a Parallel Test Runner (Step 1)

    From the above run under a regular 5.1.0 compiler, one may get the impression that everything is OK, as the balances sum to a total of $700 as expected, indicating that no money is lost. One

    Guides
  40. The Compiler Backend: Bytecode and Native code

    Accessing Stdlib Modules from Within Core

    </div> In the benchmark above comparing polymorphic and monomorphic comparison, you may have noticed that we prepended the comparison functions with Stdlib . This is because the Core module ex

    Runtime & Compiler
  41. The Compiler Frontend: Parsing and Type Checking

    Extension Attributes

    Finally, an attribute can also be attached to an individual expression. In the next example, the @warn_on_literal_pattern attribute indicates that the argument to the type constructor should

    Runtime & Compiler
  42. OCaml Programming Guidelines

    Factor out snippets of repeated code by defining them in separate functions

    Sharing code obtained in this way facilitates maintenance, since every correction or improvement automatically spreads throughout the program. Besides, the simple act of isolating and naming a sn

    Resources
  43. Values and Functions

    Functions With Side Effects

    This illustrates the relationship between functions that have side effects and the unit type. The presence of the unit type does not indicate the presence of side effects. The absence of the uni

    Introduction
  44. OCaml Programming Guidelines

    The destructuring let must be exhaustive

    Justification : There is no way to make the pattern-matching exhaustive if you use general destructuring let bindings. <!-- $MDX skip --> Global definition with destructuring let statemen

    Resources
  45. OCaml Programming Guidelines

    The relative precedences of the Boolean operators are those of mathematics

    Although mathematicians have a tendency to overuse parentheses, the Boolean “or” operator is analogous to addition and the “and” to multiplication. So, just as 1 + 2 * x means 1 + (2 *

    Resources
  46. Preprocessors and PPXs

    Why PPXs Are Especially Useful in OCaml

    Other rewriters, such as ppx_expect , show that being able to enrich the syntax via PPX rewriters is very useful, even outside of the specificity of OCaml. Secondly, one of the strong features of

    Advanced Topics
  47. Preprocessors and PPXs

    OCaml’s Parsetree: The OCaml AST

    Note that the Parsetree is an internal representation of the code that happens before typing the program, so an ill-typed program can be rewritten. The internal representation after the typing is

    Advanced Topics
  48. Basic Data Types and Pattern Matching

    Revisiting Predefined Types

    In the end, the only type construction that does not reduce to a variant is the function arrow type. Pattern matching allows the inspection of values of any type, except functions. Even integers and

    Introduction
  49. Mutability and Imperative Control Flow

    Remark: References Are Single Field Records

    create does the same as the ref function provided by the standard library. assign does the same as the ( := ) operator. deref does the same as the ( ! ) operator. The functions: Since ref

    Introduction
  50. Mutability and Imperative Control Flow

    References Inside Closures

    Calling c2 () increments the counter associated with c2 . Since c2 has its own independent counter, it starts at 0. Another call to c1 () increments its counter, resulting in 2. Calling c1 (

    Introduction