352 search results for "function"

Showing 251 - 300
  1. 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
  2. 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
  3. 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
  4. Options

    Conclusion

    By the way, any type where map and join functions can be implemented, with similar behaviour, can be called a monad , and option is often used to introduce monads. But don't freak out! You don't need to know what a monad is to use the option t

    Data Structures
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. Mutability and Imperative Control Flow

    Mutable Record Fields

    Remark : the left arrow symbol <- for mutating mutable record field values is not an operator function, like the assignment operator ( := ) is for refs . It is rather a construct of the language, it has no type. In contrast to references, there is no special syntax to dereference a mutable recor

    Introduction
  17. Mutability and Imperative Control Flow

    For Loop

    Note: Here is how to do the same thing using an iterator function: for loops are convenient to iterate over and modify arrays: When you use the downto keyword (instead of the to keyword), the counter decreases on every iteration of the loop. The body of

    Introduction
  18. Mutability and Imperative Control Flow

    Recommendations for Mutable State and Side Effects

    Functional and imperative programming styles are often used together. However, not all ways of combining them give good results. We show some patterns and anti-patterns relating to mutable states and

    Introduction
  19. Mutability and Imperative Control Flow

    Good: Memoization

    und in the cache (it's a miss), and the result is computed, stored in the cache, and returned. However, instead of precomputing everything, memoization uses a cache that is populated when calling the function. Either, the provided arguments The memoization technique relies on the same idea as the previous section's example: lookup results from a table of previously computed values.

    Introduction
  20. Objects

    Objects and Classes

    ogramming is the stack class. This is a pretty terrible example in many ways, but let's use it here to show the basics of writing object-oriented OCaml. OCaml is an object-oriented, imperative, functional programming language . It mixes all these paradigms and lets you use the most appropriate (or most familiar) programming paradigm for the task at hand. In this chapter, we're going to look at

    Advanced Topics
  21. Objects

    Polymorphic Classes

    te class which happened to contain pop and size methods with suitable type signatures, then we might accidentally call drain_stack on objects of that other type. We can define polymorphic functions which can operate on any type of stack. Our first attempt is this one: This stack is now a float stack , and only floating point numbers may be pushed and popped from this stack. Let's demon

    Advanced Topics
  22. Objects

    A Note About self

    The reference to self names the object, allowing you to call methods in the same class or pass the object to functions outside the class. In other words, it's exactly the same as this in C++/Java. You may completely omit the (self) part if you don't need to refer to yourself. Indeed, in all the examples abov

    Advanced Topics
  23. Objects

    The Oo Module and Comparing Objects

    IDs. Oo.copy makes a shallow copy of an object. Oo.id object returns a unique identifying number for each object (a unique number across all classes). The Oo module contains a few useful functions for OO programming.

    Advanced Topics
  24. Objects

    Immediate Objects and Object Types

    eir common methods are visible (see next section). type definitions : there is no need to define an object type in advance, so it lightens the dependency constraints between modules. In terms of functionality, both the object and the record are similar, but each solution has its own advantages: The implementation of a record working like our object would be: Compare with an equivalent record

    Advanced Topics
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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
  35. The Compiler Backend: Bytecode and Native code

    Perf

    home page . This trace broadly reflects the results of the benchmark itself. The mutable benchmark consists of the combination of the call to test_mutable and the caml_modify write barrier function in the runtime. This adds up to slightly over half the execution time of the application. When this completes, you can interactively explore the results: Run Perf on a compiled binary to reco

    Runtime & Compiler
  36. 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
  37. Sets

    Working With Sets

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

    Data Structures
  38. 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
  39. 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
  40. Sets

    Union of Two Sets

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

    Data Structures
  41. Sets

    Intersection of Two Sets

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

    Data Structures
  42. 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
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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
  48. 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
  49. 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
  50. 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