369 search results for "function"

Showing 201 - 250
  1. Modules

    Module Inclusion

    es a module Extlib.List that has everything the standard List module has, plus a new uncons function. In order to override the default List module [...] ib at the beginning. Let's say we feel that a function is missing from the List module, but we really want it as if it were part of it. In an extlib.

    Module System
  2. Operators

    Goals

    Using operators as functions and reciprocally, using functions as operators Assign the right associativity and precedence to a custom operator Use and define cus

    Advanced Topics
  3. Operators

    Unary Operators

    Unary operators are also called prefix operators. In some contexts, it can make sense to shorten a function's name into a symbol. This is often used as a way to shorten the name of a function that performs some sort of conversion over its argument.

    Advanced Topics
  4. Operators

    Operator Associativity and Precedence

    at the left, therefore &^ associates to the left Although both expressions are calling the same function ( par ), they are evaluated in different orders. [...] ator associativity with an example. The following function concatenates its string arguments, surrounded by | characters and separated by a _ character.

    Advanced Topics
  5. Functors

    Introduction

    his tutorial are available as a Git repo . As suggested by the name, a functor is almost like a function. However, while the inputs and outputs of functions are values, functors are between modules. A functor has a module as a parameter and returns a modu

    Module System
  6. Functors

    Dependency Injection

    .Make(Int) . The module IterPrint is refactored into a functor that takes a module providing the function iter as a parameter. The with type 'a t := 'a [...] cy. At its compilation time, no implementation of function iter is available yet. iterPrint.ml Here is a refactoring of the module IterPrint to use dep

    Module System
  7. Labelled and Optional Arguments

    Forwarding an Optional Argument

    ?len is sufficient to forward without unwrapping. In the definitions of take and rtake , the function sub is called with optional arguments passed wi [...] ithout unwrapping. These examples reuse the sub function defined in the Defining Optional Parameters Without Default Values section.

    Introduction
  8. Hash Tables

    Introduction

    A hash table data structure achieves efficient reads and writes by employing a hashing function that converts the key of a key/value pair into an [...] " known as a hash. OCaml has a built-in hashing function within the Hashtbl module that is available for each key. The Hashtbl module implements an ef

    Data Structures
  9. Sets

    Introduction

    StringSet , OCaml's toplevel displays the module's signature. Since it contains a large number of functions, the output copied here is shortened for brevity [...] e elements instead of to_list , which is a new function in OCaml 5.1, or upgrade OCaml by running opam update , then opam upgrade ocaml . Check your curr

    Data Structures
  10. First-Class Modules

    Introduction

    : Modules , Functors . First-class modules let you treat modules as values. You can pass them to functions, return them from functions, and store them in data structures. This provides an alternative to functors for some use cases an

    Module System
  11. Options

    Exceptions vs Options

    dling for a longer discussion on error handling using options, exceptions, and other means. The function Sys.getenv : string -> string from the OCaml st [...] e variable is not defined. On the other hand, the function Sys.getenv_opt : string -> string option does the same, except it returns None if the variable

    Data Structures
  12. Options

    Peel Off Doubly Wrapped Options

    itional examples demonstrating how Option.join works in different scenarios: Our custom join function is the same as the standard library's Option.joi [...] in multiple options. Let's define a custom join function of type 'a option option -> 'a option that peels off one layer from a doubly wrapped option:

    Data Structures
  13. Options

    Conclusion

    safe way to represent values that may be absent, avoiding the pitfalls of exceptions. By leveraging functions such as map , join , get , value , fold , a [...] red and expressive manner. These utilities enable functional-style programming while maintaining safety and composability. The Option module in the standard

    Data Structures
  14. Basic Data Types and Pattern Matching

    Byte Sequences

    rray . Operations on bytes values are provided by the Stdlib and the Bytes modules. Only the function Bytes.get allows direct access to the character [...] bytes literally, so they must be produced by a function. <!--CR Moved intro pp to after example, as it contains the definition. Perhaps a short intro se

    Introduction
  15. Basic Data Types and Pattern Matching

    Lists

    ce with respect to lists: Operations on lists are provided by the List module. The List.append function concatenates two lists. It can be used as an oper [...] values they contain. Lists play a central role in functional programming, so they have a dedicated tutorial . As literals, lists are very much like arrays

    Introduction
  16. Basic Data Types and Pattern Matching

    Tuples

    t associative . In the standard library, both are defined using pattern matching. Here is how a function extracts the third element of the product of four types: The predefined function fst returns the first element of a pair, while snd returns the second element of a pair. This

    Introduction
  17. Basic Data Types and Pattern Matching

    Recursive Variants

    bol _ , which catches everything. It returns false on all data that is neither Array nor Object . Functions defined using pattern matching on recursive variants are often recursive too. This function checks if a name is present in a whole JSON tree: Both constructors Array and Object contain values of type json . This is the case for the following definition, which can be used to store J

    Introduction
  18. 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 floats can be seen as enumerated-like variant types, with many constructors an

    Introduction
  19. Basic Data Types and Pattern Matching

    User-Defined Polymorphic Types

    ors. Here are the terms applicable to data types: In the OCaml community, as well as in the larger functional programming community, the word polymorphism [...] ssary to distinguish them. Here is how the map function can be defined in this type: It can be used to represent arbitrarily labelled binary trees. Assu

    Introduction
  20. Loops and Recursions

    For Loops and While Loops

    with for loops, the language doesn't provide a way to break out of a while loop, except by throwing an exception, so this means that while loops have fairly limited use. Again, remember that functional programmers like recursion, so while loops are second-class citizens in OCaml. <!-- $MDX skip --> While loops in OCaml are written: Functional programmers tend to use recursion instead

    Introduction
  21. Loops and Recursions

    Looping Over Strings

    String.copy copies a string, like strdup . There is also a String.iter function which works like List.iter , except over the cha [...] e also contains dozens of useful string-related functions, and some of them are concerned with looping over strings.

    Introduction
  22. Sequences

    Consumers vs Producers

    A function with a sequence parameter consumes it; it's a sequence consumer. A function with a sequence result produces it; it's a sequence producer. In both cases, consumption and produc

    Data Structures
  23. Sequences

    Producer Example: Seq.unfold

    This application of Seq.unfold has type unit -> int Seq.node , making it a function, a deferred producer. Each time this function is called, a new element is produced.

    Data Structures
  24. Sequences

    Be Aware of Seq.Cons vs Seq.cons

    n that both are capable of creating a new sequence: From the signature, we gather that it is a function that takes two parameters, a value and a sequen [...] wing: The other version of "cons-ing" is the function Seq.cons (with a lowercase c ) with the following value declaration: We have already been int

    Data Structures
  25. Arrays

    Iterate on an Array

    can also be made using for loops. Here is the same example using a loop: Array.iter applies a function to each element of an array, one at a time. The given function must return unit , operating by side effect. To print all the elements of the array zeroes creat

    Data Structures
  26. Arrays

    Map an Array

    The Array.map function creates a new array by applying a given function to each element of an array. For example, we can get an array containing the square of each number

    Data Structures
  27. Arrays

    Conclusion

    of arrays in OCaml, including how to create and manipulate them, as well as some of the most useful functions and use cases. Please refer to the standard lib [...] ary documentation to browse the complete list of functions of the Array module.

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

    Which Comes First: The ml or the mli?

    ode by starting with an ml file and using the type inference to guide you as you build up your functions. The mli file can then be generated as described, and the exported functions documented.

    Runtime & Compiler
  29. Lists

    Association Lists

    e able to make a list of pairs from a pair of lists and vice versa. The List module provides the functions split and combine for this purpose: Ass [...] library's Map or Hashtbl modules. But these functions from the List module are useful for lists which are generally small, and have other advantages

    Introduction
  30. Monads

    The Monad Signature

    its second argument to the first. That requires taking the 'a value out of its box, applying the function to it, and returning the result. a boxed value, which has type 'a t , and a function that itself takes an unboxed value of type 'a as input and returns a boxed value of type '

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

    Where Did the Bytecode Instruction Set Come From?

    laid the theoretical basis for the implementation of an instruction set for a strictly evaluated functional language such as OCaml. The bytecode interpre [...] different model since it uses CPU registers for function calls instead of always passing arguments on the stack, as the bytecode interpreter does. The by

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

    Accessing Stdlib Modules from Within Core

    g polymorphic and monomorphic comparison, you may have noticed that we prepended the comparison functions with Stdlib . This is because the Core module [...] always recover any of the OCaml standard library functions by accessing them through the Stdlib module, as we did in our benchmark.

    Runtime & Compiler
  33. Memory Representation of Values

    OCaml Types Disappear at Runtime

    trees (ASTs). The next stage is a type checking pass over the AST. In a validly typed program, a function cannot be applied with an unexpected type. For example, the print_endline function must receive a single string argument, and an int will result in a type error.

    Runtime & Compiler
  34. Memory Representation of Values

    String Values

    Care should be taken that any C library functions that receive these buffers can also cope with [...] , the C memcopy or memmove standard library functions can operate on arbitrary data, but strlen or strcpy both require a NULL -terminated buffer,

    Runtime & Compiler
  35. A Tour of OCaml

    Lists

    st of the list. In OCaml, pattern matching provides a means to inspect data of any kind, except functions. In this section, it is introduced on lists, and [...] attern matching can be used to define a recursive function that computes the sum of a list of integers: Lists are defined as being either empty, written [

    First Steps
  36. A Tour of OCaml

    Pairs and Tuples

    The type of tuples is written using * between the components' types. Note: The function snd is predefined in the OCaml standard library [...] ng pattern matching. For instance, the predefined function snd returns the second component of a pair: Tuples are fixed-length collections of elements of

    First Steps
  37. A Tour of OCaml

    Variant Types

    As previously shown, sum , length , and map functions provide examples of pattern matching over the list variant type. Like a function, a variant can be recursive if it refers to itself in its own definition. The predefined type list

    First Steps
  38. A Tour of OCaml

    Exceptions

    ptions are caught using the try … with … construction: Note that exceptions do not appear in function types. Exceptions are raised using the raise function. When a computation is interrupted, an exception is thrown. For instance:

    First Steps
  39. 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 of the reference text on standard output Up

    First Steps
  40. A Tour of OCaml

    Conclusion

    In this tutorial, OCaml was used interactively. The next tutorial, Your First OCaml Program , shows you how to write OCaml files, how to compile them, and how to kickstart a project. <!-- 1. Values

    First Steps
  41. OCaml on Windows

    Installing Opam on Windows

    You should now have a functioning OCaml environment ready for development. If yo [...] onment. opam requires a Unix-like environment to function. By default, opam relies on Cygwin and is also compatible with MSYS2. You will notice that the r

    Resources
  42. Your First OCaml Program

    Modules and the Standard Library, Cont'd

    This replaces the function print_endline with the function printf from the Printf module in the standard library. Building and executing this modified ver

    First Steps
  43. Values and Functions

    Local Definitions

    In both examples, d and e are local definitions. Arbitrary combinations of chaining or nesting are allowed. e is bound to 6 inside e * 5 d is bound to 30 inside d * 7 Here is how scopin

    Introduction
  44. Values and Functions

    Forms of Pattern Matching

    In the following sections, we explore matching inside let bindings, which is a special case. In the next chapter on Basic Data Types and Pattern Matching , we examine pattern matching in general c

    Introduction
  45. Values and Functions

    Pattern Matching in Definitions

    <!--the example illustrates tuples::--> When pattern matching only has one case, it can be used in name definitions and in let ... = and fun ... -> expressions. In that case, less or more than

    Introduction
  46. Values and Functions

    Pattern Matching on Records

    We can pattern match on records: <!--Because records are implicitly single-constructor variants,-->

    Introduction
  47. Values and Functions

    Pattern Matching on unit

    <!-- user-defined single constructor variant example --> Note : In order for compiled files to only evaluate an expression for its side effects, you must write them after let () = . Above, the pa

    Introduction
  48. Values and Functions

    Pattern Matching on User-Defined Types

    This also works with user-defined types.

    Introduction
  49. 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
  50. 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