364 search results for "function"

Showing 301 - 350
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. Arrays

    Length of an Array

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

    Data Structures
  11. 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
  12. 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
  13. 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
  14. Sets

    Working With Sets

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

    Data Structures
  15. 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
  16. 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
  17. Sets

    Union of Two Sets

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

    Data Structures
  18. Sets

    Intersection of Two Sets

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

    Data Structures
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. Using the OCaml Compiler Toolchain

    The ocamlc and ocamlopt Compilers

    tance, if you create a file graphics.ml and use the graphics library, the Graphics module exposed from the graphics library will be hidden by your newly defined module, hence all of the functions defined in it will be made inaccessible. Moving on, we'll see how to use ocamlopt . Let's assume that our program program has two source files, module1.ml and module2.ml . We will compile

    Guides
  41. Profiling

    Digression: Where Are the Types?

    time, OCaml knows that the type of loop is unit -> unit . It knows that the type of "hello, world\n" is string . It doesn't make any attempt to communicate this fact to the output_string function. output_string is expecting a channel and a string as arguments, and indeed that's what it gets. What would happen if we passed, say, an int instead of a string ?

    Guides
  42. Profiling

    Floats

    string_of_float isn't polymorphic, but suppose we have a polymorphic function foo : 'a -> unit taking one polymorphic argument. If we call foo with %eax containing 7, then this is equivalent to foo 3 , whereas if we call foo with %eax containing a pointer to Flo

    Guides
  43. Profiling

    Using Instruments on macOS

    From there, you can click on your program there and dig to see which functions are taking the longest to execute. <img width="100%" alt="macOS Instruments" src="/media/tutorials/macos-instruments.png"> As you launch your application, real-time results will appear listed i

    Guides
  44. Profiling

    Summary

    find out where it's spending its time and concentrate optimisations on just those areas. Check for unintentional polymorphism, and add type hints for the compiler. Closures are slower than simple function calls, but add to maintainability and readability. As a last resort, rewrite hotspots in your program in C (but first check the assembly language produced by the OCaml compiler to see if you ca

    Guides
  45. Profiling

    Further Reading

    p of pointer indirection. Objects in OCaml are also dynamically dispatched. Since this is the point with polymorphism in an OO setting. * Dynamic method dispatch often hinders a compiler to inline function and this hits the performance. * In Java is a dynamic type check (aka cast) much more expensive than a dynamic method dispatch. --> You can find out more about how OCaml represents different typ

    Guides
  46. 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
  47. 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
  48. Error Handling

    Documentation

    <!-- $MDX skip --> Functions that can raise exceptions should be documented like this:

    Guides
  49. Error Handling

    Language Bugs

    sh File an issue in the OCaml Bug Tracker in GitHub it may be a language bug. It happens. Here is what to do when this is suspected: A limitation of the native code compiler An inherently unsafe function such as are found in modules Marshal and Obj When a crash isn't coming from:

    Guides
  50. Error Handling

    External Resources

    odule result in Ocaml Library “Error Handling” in “Real World OCaml”, part 7, Yaron Minsky and Anil Madhavapeddy, 2ⁿᵈ edition, Cambridge University Press, October 2022 “Add "finally" function to Pervasives”, Marcello Seri, GitHub PR, ocaml/ocaml/pull/1855 “A guide to recover from interrupts”, Guillaume Munch-Maccagnoni, parf the memprof-limits documentation

    Guides