369 search results for "function"
-
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 -
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 -
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 -
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 -
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 -
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 -
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 -
Arrays
Length of an Array
The Array.length function returns the size of an array:
Data Structures -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
Modules
Interfaces and Implementations
module implementation) The public declarations of a module (the module interface) For this, we must distinguish: By default, anything defined in a module is accessible from other modules. Values, functions, types, or submodules, everything is public. This can be restricted to avoid exposing definitions that are not relevant from the outside.
Module System -
Modules
Stateful Modules
and third calls return the same results, showing that the internal state was reset. A module may have an internal state. This is the case for the Random module from the standard library. The functions Random.get_state and Random.set_state provide read and write access to the internal state, which is nameless and has an abstract type.
Module System -
Modules
Conclusion
Functors, which act like functions from modules to modules Libraries, which are compiled modules bundled together Packages, which are installation and distribution units Going further, here are the other means to handle OCaml softwar
Module System -
Maps
Adding Entries to a Map
Note that the initial map lucky_numbers remains unchanged. If the passed key is already associated with a value, the passed value replaces it. To add an entry to a map, use the add function that takes a key, a value, and the map to which it will be added. It returns a new map with that key-value pair added:
Data Structures -
Maps
Removing Entries From a Map
Note that the initial map lucky_numbers remains unchanged. Removing a key that isn't present in the map has no effect. To remove an entry from a map, use the remove function, which takes a key and a map. It returns a new map with that key's entry removed.
Data Structures -
Maps
Checking if a Key is Contained in a Map
To check if a key is a member of a map, use the mem function:
Data Structures -
Maps
Filtering a Map
To filter a map, use the filter function. It takes a predicate to filter entries and a map. It returns a new map containing the entries satisfying the predicate.
Data Structures -
Maps
Map a Map
sing string_of_int . Using StringMap.map , we create a map associating keys with string values: The lucky_numbers map associates string keys with integer values: Map modules have a map function:
Data Structures -
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 -
Operators
Binary Operator
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
Sets
Working With Sets
Let's look at a few functions for working with sets using these two sets.
Data Structures -
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 -
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 -
Sets
Union of Two Sets
With the function StringSet.union , we can compute the union of two sets.
Data Structures -
Sets
Intersection of Two Sets
With the function StringSet.inter , we can compute the intersection of two sets.
Data Structures -
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 -
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 -
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 -
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 -
Command-line Arguments
Sys.argv
ndard library, therefore its full name is Sys.argv . The number of arguments including the name of the program itself is simply the length of the array. It is obtained using the Array.length function.
Tutorials -
Formatting and Wrapping Text
Printing to stdout : Using printf
@. ” end the pretty-printing, closing all the boxes still opened ( print_newline () ). Pretty-printing annotations are introduced by the @ symbol, directly into the string format. Almost any function of the format module can be called from within a printf format string. For instance The format module provides a general printing facility “à la” printf . In addition to the usual con
Tutorials -
Formatting and Wrapping Text
A Concrete Example
nt the lambda-terms: First, I give the abstract syntax of lambda-terms: Thus the problem is to pretty-print the values of a concrete data type that models a language of expressions that defines functions and their applications to arguments. Let me give a full example: the shortest non trivial example you could imagine, that is the λ-calculus. :)
Tutorials -
File Manipulation
Writing
Standard out_channel s: stdout , stderr Commonly used functions: open_out , open_out_bin , flush , close_out , close_out_noerr Open the file to obtain an out_channel Write to the channel If you want to force writing to the physical device, you must flush
Tutorials -
File Manipulation
Reading
Standard in_channel : stdin Commonly used functions: open_in , open_in_bin , close_in , close_in_noerr Open the file to obtain an in_channel Read characters from the channel. Reading consumes the channel, so if you read a character, the chan
Tutorials -
How to Work with the Garbage Collector
The Gc Module
.ml --> <!-- TODO: Probably write a GC example without dependencies --> Here is a program that runs and then prints out GC statistics just before quitting: The Gc module contains some useful functions for querying and calling the garbage collector from OCaml programs.
Guides