638 search results for ""

Showing 201 - 250
  1. Mutability and Imperative Control Flow

    Breaking Loops Using Exceptions

    This while loop echoes characters typed on the keyboard. When the ASCII Escape character is read, the Exit exception is thrown, which terminates the iteration and displays the REPL reply: - :

    Introduction
  2. Understanding the Garbage Collector

    Memory Allocation Strategies

    The free list of blocks is always checked first when allocating a new block in the major heap. The default free list search is called best-fit allocation , with alternatives next-fit and first

    Runtime & Compiler
  3. Calling Fortran Libraries

    Step 3: Compile the Shared Library

    This will create a shared object library called wrapper.so containing the fortran function and the wrapper function. The -lg2c option is required to provide the implementations of the built in fo

    Tutorials
  4. Libraries With Dune

    Disable Library Wrapping

    When the file lib/wmo.ml exists, the modules stanza that doesn't list it prevents it from being bundled in the library When the file lib/wmo.ml doesn't exist, the wrapped false stanza preve

    Module System
  5. Preprocessors and PPXs

    Preprocessing With ocamlc and ocamlopt

    Compiling a classic "Hello, World!" program with this option would alter the compilation: OCaml's compiler ocamlc and ocamlopt offer the -pp option to preprocess a file in the compilat

    Advanced Topics
  6. Preprocessors and PPXs

    Preprocessing in OCaml

    This guide presents the state of the two kinds of preprocessors in OCaml, but with an emphasis on PPXs. Although the latter is the recommended way of writing preprocessors, we start with source p

    Advanced Topics
  7. Libraries With Dune

    Minimum Project Setup

    <!-- FIXME: update with wmo --> The dune describe command allows having a look at the project's module structure. Here is its output: mixtli is the project's name (it means cloud in Nahuatl

    Module System
  8. Using the OCaml Compiler Toolchain

    Dune: An Automated Build System

    The dune quick-start guide shows you how to write such description files for more complicated situations, and how to structure, build, and run dune projects. The most popular modern system

    Guides
  9. OCaml Programming Guidelines

    match construct in a match construct

    <!-- $MDX skip --> When a match ... with or try ... with construct appears in a pattern-matching clause, it is absolutely necessary to delimit this embedded construct (otherwise subsequent

    Resources
  10. OCaml Programming Guidelines

    How to Delimit Constructs in Programs

    This explicit delimiting of constructs essentially concerns pattern-matching constructs or sequences embedded within if then else constructs. When it is necessary to delimit syntactic const

    Resources
  11. A Tour of OCaml

    Side-Effects and the unit Type

    Input-output is an example of something taking place when executing a function but which does not appear in the function type. This is called a side-effect and does not stop at I/O. The unit type

    First Steps
  12. Memory Representation of Values

    Variants and Lists

    Lists are stored with a representation that is exactly the same as if the list was written as a variant type with Nil and Cons . The empty list [] is an integer 0 , and subsequent blocks hav

    Runtime & Compiler
  13. OCaml Programming Guidelines

    How to Indent Operations

    <!-- $MDX skip --> These guidelines extend to all operators. For example: <!-- $MDX skip --> write <!-- $MDX skip --> You most certainly must bind expressions too large to be written in

    Resources
  14. Debugging

    Finding the Cause of a Spurious Exception

    To sum up: if you're developing a program you can compile it with the -g option, to be ready to debug the program if necessary. Hence, to find a spurious exception you just need to type ocamlde

    Guides
  15. OCaml Programming Guidelines

    How to Edit With the Interactive System

    Under Unix: use the line editor ledit , which offers great editing capabilities “à la Emacs” (including ESC-/ !) as well as a history mechanism that lets you retrieve previously-typed comm

    Resources
  16. Higher Order Functions

    Iterating over Maps and Sets

    The actual implementation of iteration functions for Maps and Sets does use pattern-matching under the hood. You'll notice that we did not use pattern-matching this time around to iterate over the v

    Introduction
  17. Using the OCaml Compiler Toolchain

    Interlude: Making a Custom Toplevel

    OCamlfind also supports ocamlmktop : We run toplevel and get an OCaml toplevel with modules Unix , Module1 , and Module2 all available, allowing us to experiment interactively with our p

    Guides
  18. Higher Order Functions

    Iterating over Lazy Sequences

    This is almost exactly how Seq.iter is defined in the standard library. This function will try to get the first element of the sequence, and if there is one, run our function fn over it. Then it

    Introduction
  19. Basic Data Types and Pattern Matching

    Enumerated Data Types

    unit is a variant with a unique constructor, which does not carry data: () . bool is also a variant with two constructors that doesn't carry data: true and false . Note that: Pattern matchi

    Introduction
  20. Labelled and Optional Arguments

    Forwarding an Optional Argument

    In take the optional argument has the same name as in sub ; writing ?len is sufficient to forward without unwrapping. In the definitions of take and rtake , the function sub is called with

    Introduction
  21. Managing Dependencies With opam

    Adding a Dependency to Your .opam File

    Either way, once you have added your dependency in the appropriate file, you can run opam install . --deps-only to update your current switch dependencies. If the *.opam files are not generat

    Projects
  22. Higher Order Functions

    Iterating over Optionals and Results

    This is how Option.iter and Result.iter are defined in the standard library. We can do this by pattern-matching on our value and calling our function over the inner value in the Some or Ok bra

    Introduction
  23. Your First OCaml Program

    Defining Multiple Modules in a Library

    A more detailed introduction to modules can be found at Modules . Finally, run dune build and dune exec hello to see the new output, using the modules you just created in the hello librar

    First Steps
  24. A Tour of OCaml

    Working with Mutable State

    This behaviour is the same as in an imperative language. However, although ; is not defined as a function, it behaves as if it were a function of type unit -> unit -> unit . Display the contents

    First Steps
  25. Monads

    Example: The Writer Monad

    It's debatable which version of loggable is easier to read. Certainly you need to be comfortable with the monadic style of programming to appreciate the version of it that uses >>= . But if yo

    Data Structures
  26. Mutability and Imperative Control Flow

    Good: Precomputing Values

    However, it is possible to make a faster implementation by precomputing all the possible values in advance. There are only 256 of them, which you'll see listed after the first result below: Let'

    Introduction
  27. Common Error Messages

    This pattern-matching is not exhaustive

    In general, that kind of simplification is not possible and the best solution is to add a catch-all case which should never be reached: A short solution without pattern matching would be: O

    Resources
  28. Labelled and Optional Arguments

    Function with Only Optional Arguments

    Without the unit parameter, the optional argument cannot be erased warning would be emitted. When all parameters of a function need to be optional, a dummy, positional and occurring last paramet

    Introduction
  29. Values and Functions

    Partial Application and Closures

    fun x -> sweet_cat "kitty" x sweet_cat "kitty" These expressions have the same value: Passing a single argument to sour_kitty or sweet_kitty returns a function of type string -> string . The

    Introduction
  30. Using the OCaml Compiler Toolchain

    Bytecode Using Dune

    We can also do that with .exe . The .bc stands for generic bytecode file, and it can be an executable or library. Finally, we compile and execute it. Next, create a main.ml file, ad

    Guides
  31. The Compiler Frontend: Parsing and Type Checking

    Type Inference

    OCaml does have some language extensions that strain the limits of principal type inference, but by and large, most programs you write will never require annotations (although they sometimes hel

    Runtime & Compiler
  32. Profiling

    Digression: Where Are the Types?

    Fully knowing all your types at compile time is a major performance win because it totally avoids any dynamic type checking at run time. Compare this to a Java method invocation for example: obj

    Guides
  33. Introduction to opam Switches

    Creating a New Switch

    If the output is the name of your new switch, you've successfully activated it! Now you can use it for your OCaml projects and install OCaml packages, libraries, and dependencies specific to this swi

    Tooling
  34. Common Error Messages

    Warning: This optional argument cannot be erased

    See the Labels section for more details on functions with labelled arguments. The solution is simply to add one argument of type unit, like this: Functions with optional arguments must have

    Resources
  35. Libraries With Dune

    Library Wrapper Modules

    Have different public and internal names, module CumulusCloud = Cumulus Define values in the wrapper module, let ... = Expose module resulting from functor application, module StringSet = Set.Mak

    Module System
  36. Libraries With Dune

    Include Subdirectories

    <!-- ## Starting a Project from a Single File It is possible to start an empty Dune project from a single file. Create a fresh directory. ```shell $ mkdir foo.dir; cd foo.dir ``` Create a `dune-p

    Module System
  37. Loops and Recursions

    Approach 3

    <!-- $MDX skip --> All that remains now to make this a working program is a little bit of code to call read_directory and display the result: <!-- $MDX skip --> The use of recursion to bui

    Introduction
  38. Understanding the Garbage Collector

    Controlling the Heap Allocation Policy

    The same behavior can be controlled via an environment variable by setting OCAMLRUNPARAM to a=0 for next-fit, a=1 for first-fit, or a=2 for best-fit. You can set the heap allocation pol

    Runtime & Compiler
  39. Running Executables and Tests with Dune

    Running Executables

    You can run it with dune exec bin/main.exe or dune exec my-app . For instance, if you've put your dune file in bin/dune with the following content: Once Dune has produced the executable wi

    Projects
  40. Loops and Recursions

    Tail Recursion

    One thing is that recursive functions have a dangerous trap for inexperienced programmers. Your function can appear to work for small inputs (during testing), but then fail catastrophically in

    Introduction
  41. How to Work with the Garbage Collector

    The Gc Module

    (We haven't seen the { expression with field = value } form before, but it should be mostly obvious what it does). The above code causes the GC to print a message at the start of every major co

    Guides
  42. Basic Data Types and Pattern Matching

    Floats and Type Conversions

    Operations on float are provided by the Stdlib and the Float modules. OCaml does not perform any implicit type conversion between values. Therefore, arithmetic expressions can't mix integers

    Introduction
  43. OCaml Programming Guidelines

    How to Optimize Programs

    Justification : Clarity and correctness of programs take precedence. Besides, in a substantial program, it is practically impossible to identify a priori the parts of the program whose effic

    Resources
  44. Higher Order Functions

    Folding (or reducing)

    And voila! Our function now type-checks correctly and we can use it to reduce our trees down to any value. So to fix our fold_tree we just need to pass in a zero or accumulator value: Some data

    Introduction
  45. The Compiler Frontend: Parsing and Type Checking

    Extension Nodes

    We've already seen extension nodes in use via the Core syntax extensions earlier in the book, where they act as syntactic sugar for error handling ( let%bind ), for command-line parsing ( let%ma

    Runtime & Compiler
  46. Basic Data Types and Pattern Matching

    Conclusion

    <!-- ## Next: Advanced Data Types Going further, you can explore several advanced topics related to OCaml's data types to deepen your understanding and enhance your programming skills. - Mutually Re

    Introduction
  47. Understanding the Garbage Collector

    First-Fit Allocation

    For some workloads that need more real-time behavior under load, the reduction in the frequency of heap compaction will outweigh the extra allocation cost. First-fit allocation focuses on reduci

    Runtime & Compiler
  48. Running Commands in an opam Switch

    Using direnv

    By using direnv in conjunction with opam, you can streamline your development workflow, ensuring that the correct opam switch is automatically set up whenever you work on a specific project. On e

    Projects
  49. Using the OCaml Playground

    Let's Enter Some Code

    The output will be the following. That's amazing! You are doing great. Now let's write a short program. I'll be using the code sample that we saw when we entered the playground. - : string = "O

    Resources
  50. Values and Functions

    Scopes and Environments

    <!-- With respect to the environment, there are no means to: - List its contents - Clear its contents - Remove a definition - Reset it to an earlier state --> Top-level expressions are also statemen

    Introduction