364 search results for "function"

Showing 301 - 350
  1. Operators

    Defining Binary Operators

    It is a recommended practice to define operators in two steps, like shown in the example. The first definition contains the function's logic. The second definition is merely an alias of the first one. This provides a default pronunciation to the operator and clearly indicates that the operator is syntactic sugar : a means to ease

    Advanced Topics
  2. Operators

    Allowed Operators

    Don't define wide scope operators. Restrict their scope to module or function. Don't use many of them. Before defining a custom binary operator, check that the symbol is not already used. This can be done in two ways: By surrounding the candidate symbol with parentheses in UTo

    Advanced Topics
  3. Functors

    Functors From the Standard Library

    e 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 type t and associated functions. Refer to the documentation for the details about what they provide: Here is the module's signature that the functor Hashtbl.Make expects: Here is the module's signature that the functors S

    Module System
  4. Functors

    Naming and Scoping

    he same type as Dep.t ( List.t in this case). However, since Make is invoked to create module IterPrint in funkt.ml , the project fails to compile with the following error message: If the function f isn't used, the project compiles without error. Naively, we might have defined Iter.Make as follows: The with type constraint unifies types within a functor's parameter and result modules

    Module System
  5. Functors

    Write a Functor to Extend Modules

    inside the toplevel, enter the following commands. scanLeft.ml dune dune-project Create a fresh directory with the following files: In this example, we extend List and Array modules with a function scan_left . It does almost the same as fold_left , except it returns all the intermediate values, not the last one as fold_left does. In this section, we define a functor to extend several modul

    Module System
  6. Functors

    Conclusion

    Functor application essentially works the same way as function application: passing parameters and getting results. The difference is that we are passing modules instead of values. Beyond comfort, it enables a design approach where concerns are not only separate

    Module System
  7. Understanding the Garbage Collector

    Generational Garbage Collection

    different memory layouts and garbage-collection algorithms for the major and minor heaps to account for this generational difference. We'll explain how they differ in more detail next. A typical functional programming style means that young blocks tend to die young and old blocks tend to stay around for longer than young ones. This is often referred to as the generational hypothesis . A small

    Runtime & Compiler
  8. Understanding the Garbage Collector

    The Gc Module and OCAMLRUNPARAM

    ttings. The format of OCAMLRUNPARAM is documented in the OCaml manual . OCaml provides several mechanisms to query and alter the behavior of the runtime system. The Gc module provides this functionality from within OCaml code, and we'll frequently refer to it in the rest of the chapter. As with several other standard library modules, Core alters the Gc interface from the standard OCaml

    Runtime & Compiler
  9. Understanding the Garbage Collector

    Understanding Allocation

    <div class="note"> These poll points check ptr against limit and developers should expect them to be placed at the start of every function and the back edge of loops. The compiler includes a dataflow pass that removes all but the minimum set of points necessary to ensure these checks happen in a bounded amount of time. It is possib

    Runtime & Compiler
  10. Understanding the Garbage Collector

    Setting the Size of the Minor Heap

    t at the cost of a bigger memory profile). This setting can be overridden via the s=<words> argument to OCAMLRUNPARAM . You can change it after the program has started by calling the Gc.set function:

    Runtime & Compiler
  11. Understanding the Garbage Collector

    The Mutable Write Barrier

    install the Core benchmarking suite via opam install core_bench before you compile this code: The OCaml compiler keeps track of any mutable types and adds a call to the runtime caml_modify function before making the change. This checks the location of the target write and the value it's being changed to, and ensures that the remembered set is consistent. Although the write barrier is reas

    Runtime & Compiler
  12. 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. The function Option.value from the standard library has a parameter labelled default .

    Introduction
  13. 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 parameter must be added. The unit () value comes in handy for this. This is what is done here.

    Introduction
  14. Labelled and Optional Arguments

    Conclusion

    Functions can have named or optional parameters. Refer to the reference manual for more examples and details on labels.

    Introduction
  15. Sets

    Creating a Set

    There's another relevant function StringSet.of_seq: string Seq.t -> StringSet.t that creates a set from a sequence . Converting a list into a set using StringSet.of_list : A set with a single element is created using Strin

    Data Structures
  16. Sets

    Working With Sets

    Let's look at a few functions for working with sets using these two sets.

    Data Structures
  17. Sets

    Adding an Element to a Set

    The function StringSet.add with type string -> StringSet.t -> StringSet.t takes both a string and a string set. It returns a new string set. Sets created with the Set.Make functor in OCaml are immutable, so

    Data Structures
  18. Sets

    Removing an Element from a Set

    The function StringSet.remove with type string -> StringSet.t -> StringSet.t takes both a string and a string set. It returns a new string set without the given string.

    Data Structures
  19. Sets

    Union of Two Sets

    With the function StringSet.union , we can compute the union of two sets.

    Data Structures
  20. Sets

    Intersection of Two Sets

    With the function StringSet.inter , we can compute the intersection of two sets.

    Data Structures
  21. Sets

    Subtracting a Set from Another

    With the function StringSet.diff , we can remove the elements of the second set from the first set.

    Data Structures
  22. Sets

    Filtering a Set

    The function StringSet.filter of type (string -> bool) -> StringSet.t -> StringSet.t creates a new set by keeping the elements that satisfy a predicate from an existing set.

    Data Structures
  23. Sets

    Checking if an Element is Contained in a Set

    To check if an element is contained in a set, use the StringSet.mem function.

    Data Structures
  24. Sets

    Conclusion

    We gave an overview of OCaml's Set module by creating a StringSet module using the Set.Make functor. Further, we looked at how to create sets based on a custom comparison function. For more information, refer to Set in the Standard Library documentation.

    Data Structures
  25. First-Class Modules

    When to Use First-Class Modules

    performance (first-class modules have small runtime overhead) Complex module relationships with multiple dependencies Use functors when you need to: Pass different module implementations to the same function Store modules in data structures (lists, hash tables) Choose implementations at runtime based on configuration Build plugin systems Use first-class modules when you need to:

    Module System
  26. First-Class Modules

    Key Points

    Pack modules with (module M : ModuleType) Unpack with let module M = (val x : ModuleType) in ... Functions can directly pattern match: fun (module M : ModuleType) -> ... Use with type constraint

    Module System
  27. Options

    The Standard Library Option Module

    Most of the functions in this section, as well as other useful ones, are provided by the OCaml standard library in the Stdlib.Option module.

    Data Structures
  28. Basic Data Types and Pattern Matching

    Introduction

    ng dedicated syntax - Write variant type definitions: simple, recursive, and polymorphic - Write record type definitions (without mutable fields) - Write type aliases - Use pattern matching to define functions for all basic type --> Note : As in previous tutorials, expressions after # and ending with ;; are for the toplevel, like UTop. In OCaml, there are no type checks at runtime, and values don't

    Introduction
  29. Basic Data Types and Pattern Matching

    Results

    Operations on results are provided by the Result module. Results are discussed in the Error Handling guide. The result type can be used to express that a function's outcome can be either success or failure. There are only two ways to build a result value: either using Ok or Error with the intended meaning. Both constructors can hold any kind of data. The

    Introduction
  30. Basic Data Types and Pattern Matching

    Function Parameter Aliases

    This is useful for matching variant values of parameters. Function parameters can also be given a name with pattern matching for tuples and records.

    Introduction
  31. Basic Data Types and Pattern Matching

    Conclusion

    ) on OCaml. OCaml aggregates several type systems, also known as disciplines: - A [nominal type system](https://en.wikipedia.org/wiki/Nominal_type_system) is used for predefined types, variants, and functions. , and it is also the scope of this tutorial. - Two different [structural type systems](https://en.wikipedia.org/wiki/Structural_type_system) are also used: * One for polymorphic variants * Anot

    Introduction
  32. Sequences

    Iterating Over Sequences

    ers forever,” and you have to press Ctrl-C to interrupt the execution. The following code is the same infinite loop without any output: The OCaml Standard Library also contains a Seq.iter function, which has the same behavior as List.iter . Writing this:

    Data Structures
  33. Sequences

    Reading a File with Seq.Unfold

    ition. Note : To make the code in the next section work, create a file named "README.md" and add dummy content. We use a file generated by the following command: Before doing so, let's define a function that reads a file's line from a provided channel, with the type signature needed by Seq.unfold . For the next example, we will demonstrate the versatility of Seq.unfold by using it to read a

    Data Structures
  34. Sequences

    Consumer Example: Seq.iter

    In print_seq , Seq.iter takes the function print_int and applies it to each element as they are generated. If List.iter was used, the whole integer list would be needed before displaying them starts.

    Data Structures
  35. Arrays

    The Standard Library Array Module

    OCaml provides several useful functions for working with arrays. Here are some of the most common ones:

    Data Structures
  36. Arrays

    Length of an Array

    The Array.length function returns the size of an array:

    Data Structures
  37. The Compiler Frontend: Parsing and Type Checking

    Generating Documentation from Interfaces

    some source code that's been annotated with docstring comments: OCaml uses specially formatted comments in the source code to generate documentation bundles. These comments are combined with the function definitions and signatures, and output as structured documentation in a variety of formats. Tools such as odoc and ocamldoc can generate HTML pages, LaTeX and PDF documents, UNIX manual p

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

    Adding Type Annotations to Find Errors

    her verbose and with a line number that doesn't point to the exact location of the incorrect variant name. The best the compiler can do is to point you in the general direction of the algebra function application. There's a single character typo in the code so that it uses Nu instead of Num . The resulting type error is impressive: For instance, consider this broken example that expresse

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

    Enforcing Principal Typing

    pal will show you a new warning: Here's an example of principality warnings when used with record disambiguation. Polymorphic methods for objects Permuting the order of labeled arguments in a function from their type definition Discarding optional labeled arguments Generalized algebraic data types (GADTs) present from OCaml 4.0 onward Automatic disambiguation of record field and constructor n

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

    Shorter Module Paths in Type Errors

    rovide a complete replacement standard library. It collects these modules into a single Std module, which provides a single module that needs to be opened to import the replacement modules and functions.

    Runtime & Compiler
  41. Monads

    Example: The Lwt Monad

    that we saw before involves creating references, but those references are completely hidden behind the monadic interface. Moreover, we know that bind involves registering callbacks, but that functionality (which as you might imagine involves maintaining collections of callbacks) is entirely encapsulated. And Lwt.Infix.( >>= ) is a synonym for Lwt.bind , so the library does provide an infi

    Data Structures
  42. The Compiler Backend: Bytecode and Native code

    The Untyped Lambda Form

    ype information into a simpler intermediate lambda form . The lambda form discards higher-level constructs such as modules and objects and replaces them with simpler values such as records and function pointers. Pattern matches are also analyzed and compiled into highly optimized automata.

    Runtime & Compiler
  43. 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 full details online . The preceding bytecode has been simplified from the lambda form into a set of simple instructions that are executed seriall

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

    Compiling and Linking Bytecode

    le program. The order in which .cmo arguments are presented on the command line defines the order in which compilation units are initialized at runtime. Remember that OCaml has no single main function like C, so this link order is more important than in C programs. The individual objects in the library are linked as regular cmo files in the order specified when the library file was built. I

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

    Embedding OCaml Bytecode in C

    ile. Here's an example to show how it all fits together. This mode causes ocamlc to output an object file containing the bytecode for the OCaml part of the program, as well as a caml_startup function. All of the OCaml modules are linked into this object file as bytecode, just as they would be for an executable. A consequence of using the bytecode compiler is that the final link phase must

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

    Compiling Fast Native Code

    ks modules together into an executable, it uses the contents of the cmx files to perform cross-module inlining across compilation units. This can be a significant speedup for standard library functions that are frequently used outside of their module. A .o file containing native object code A .cmx file containing extra information for linking and cross-module optimization A .cmi compile

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

    Benchmarking Polymorphic Comparison

    ee that this polymorphic comparison is much heavier than the simple monomorphic integer comparison from earlier. Let's confirm this hypothesis again by writing a quick Core_bench test with both functions:

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

    Debugging Native Code Binaries

    assembly when the library is compiled in debug mode. These include the CFI stubs you will have noticed in the profiling output earlier ( .cfi_start_proc and .cfi_end_proc to delimit an OCaml function call, for example). The native code compiler builds executables that can be debugged using conventional system debuggers such as GNU gdb . You need to compile your libraries with the -g optio

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

    Interactive Breakpoints with the GNU Debugger

    e first call to take : Now we can run this interactively within gdb : Compile and run this with debugging symbols. You should see the following output: Let's write a mutually recursive function that selects alternating values from a list. This isn't tail-recursive, so our stack size will grow as we single-step through the execution: Let's see name mangling in action with some interacti

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

    Gprof

    gmon.out when the program is executed. This profile information can then be examined using gprof . gprof produces an execution profile of an OCaml program by recording a call graph of which functions call one another, and recording the time these calls take during the program execution.

    Runtime & Compiler