667 search results for ""

Showing 501 - 550
  1. Higher Order Functions

    Currying

    But we can also curry our reveal function to take 2 arguments! If we wanted to use reveal on a name, we have to put it into a tuple, and then do the call. Like this: Take for example this

    Introduction
  2. Preprocessors and PPXs

    Using PPXs

    And that's all you need to use PPXs! Although these instructions will work for most PPXs, note that the first source of information will be the package documentation, as some PPXs might need some

    Advanced Topics
  3. OCaml Programming Guidelines

    How Much to Indent

    The change in indentation between successive lines of the program is generally 1 or 2 spaces. Pick an amount to indent and stick with it throughout the program.

    Resources
  4. Options

    Exceptions vs Options

    See Error Handling for a longer discussion on error handling using options, exceptions, and other means. The function Sys.getenv : string -> string from the OCaml standard library queries the

    Data Structures
  5. Debugging

    Limitations

    Compiler builtins are described in the standard library documentation. At compile time, the __LOC__ builtin is substituted with its location in the program, described as a string "File %S, l

    Guides
  6. 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. Access to the components of tuples is done using patte

    First Steps
  7. Formatting and Wrapping Text

    Boxes

    within a “h” box: within a “v” box: within a “hv” box: If there is enough room to print the box on the line: But "---b---b---" that cannot fit on the line is written within a

    Tutorials
  8. Higher Order Functions

    Mapping Lists

    Note how we use the :: constructor to both deconstruct the list and reconstruct it. The main difference is that instead of throwing away the resulting value from running our function over the el

    Introduction
  9. Values and Functions

    Pattern Matching on Records

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

    Introduction
  10. Profiling

    Profiling Tools

    After running the program as normal, the profiling code dumps out a file gmon.out which we can interpret with gprof : We compile it using the -p option to ocamlopt which tells the compil

    Guides
  11. Debugging

    Tracing Functions Calls in the Toplevel

    The simplest way to debug programs in the toplevel is to follow the function calls, by “tracing” the faulty function:

    Guides
  12. Debugging

    Getting Help and Info in the Debugger

    To get more info about the current status of the debugger you can ask it directly at the toplevel prompt of the debugger; for instance:

    Guides
  13. A Tour of OCaml

    Using the result Type

    So one may write: Another way to deal with errors in OCaml is by returning value of type result , which can represent either the correct result or an error. Here is how it is defined:

    First Steps
  14. Debugging

    Launching the Debugger

    Then the debugger answers with a banner and a prompt: We launch the debugger: At runtime, the program raises an uncaught exception Not_found . Suppose we want to find where and why this e

    Guides
  15. OCaml Programming Guidelines

    Width of the Page

    Justification : This width makes it possible to read the code on all displays and to print it in a legible font on a standard sheet. The page is 80 columns wide.

    Resources
  16. Command-line Arguments

    Sys.argv

    <!-- $MDX dir=examples --> Note that ocaml launched a subprocess that actually runs the program where argv is args.ml arg1 arg2 arg3 . You can also compile your program using ocamlopt -o ar

    Tutorials
  17. Fix Homebrew Errors on Apple M1

    Install CLT

    If they're not installed, let's install them now. You don't have to install all of XCode; you can install just the CLT by downloading them directly from Apple's Developer . Look for a non-beta versi

    Resources
  18. Profiling

    Further Reading

    <!--### Java dynamic dispatch **There are some serious mistakes in the last paragraph:** * Dynamic method dispatch itself is seldom a performance problem. In languages without multiple inheritance

    Guides
  19. Sequences

    Fibs with Seq.Cons

    <!-- Or with an int version ``` ocaml # ints_v2 1 |> Seq.take 10 |> List.of_seq;; - : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] ``` --> This implementation successfully defines a producer of laz

    Data Structures
  20. Values and Functions

    Introduction

    We use UTop to understand these concepts by example. You are encouraged to modify the examples to gain a better understanding. In OCaml, functions are treated as values, so you can use functions as

    Introduction
  21. Options

    Fold an Option

    This function safely handles optional names by providing a fallback greeting: Example 3 : Handling Optional User Input Since None is given, it returns the default 0 . Here, Option.fold ap

    Data Structures
  22. Maps

    Changing the Value Associated With a Key

    You should experiment with different update functions; several behaviors are possible. To change a key's associated value, use the update function. It takes a key, a map, and an update functio

    Data Structures
  23. OCaml Programming Guidelines

    Iterators

    In case of express need, be sure to add an explanatory comment. In my opinion, it's absolutely necessary! <!-- $MDX skip --> even though you get: <!-- $MDX skip --> On the other hand, avoid w

    Resources
  24. OCaml Programming Guidelines

    How to Compile

    The make utility is indispensable for managing the compilation and recompilation of programs. Sample make files can be found on The Hump . You can also consult the Makefiles for the OCam

    Resources
  25. Memory Representation of Values

    Conclusion

    Understanding the Garbage Collector Calling C Libraries Other recommended tutorials: We covered the precise mapping from OCaml types to their internal runtime representation in memory, which shou

    Runtime & Compiler
  26. Profiling

    Tail Recursion

    So that's pretty conclusive. Calling Tail__loop_56 will first print the string, and then jump back to the top, then print the string, and jump back, and so on forever. It's a simple loop, not

    Guides
  27. Values and Functions

    Pattern Matching on User-Defined Types

    This also works with user-defined types.

    Introduction
  28. Values and Functions

    Closures

    Inside the max_42 function, the environment contains an additional binding between the first parameter of max and the value 42. Partially applying arguments to a function also creates a new clo

    Introduction
  29. 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 algorithmically unique "fingerprint" known as a h

    Data Structures
  30. Basic Data Types and Pattern Matching

    Characters

    The module Uchar provides support for Unicode characters. Operations on char values are provided by the Stdlib and the Char modules. Values of type char correspond to the 256 symbols of

    Introduction
  31. 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 the

    Data Structures
  32. Error Handling

    Language Bugs

    Here is an example of such a bug: <https://github.com/ocaml/ocaml/issues/7241> Make sure the crash affects both compilers: bytecode and native Write a self-contained and minimal proof-of-concept co

    Guides
  33. Options

    Bind an Option

    This example retrieves a configuration value and ensures it falls within a valid range. Example 3 : Chaining Computations Notice how the function user_to_email does not require explicit pattern

    Data Structures
  34. 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++

    Advanced Topics
  35. Arrays

    Folding an Array

    These functions derive a single value from the whole array. For example, they can be used to find the maximum element of an array: fold_right f a init computes f a.(0) (f a.(1) ( ... (f a.(n-1)

    Data Structures
  36. Maps

    Maps With Custom Key Types

    Note that our module has a type t and also a compare function. Now we can call the Map.Make functor to get a map for non-negative numbers: We'll start by defining a module for strings th

    Data Structures
  37. 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
  38. A Tour of OCaml

    Functions

    Some functions, such as String.ends_with have labelled parameters. Labels are useful when a function has several parameters of the same type; naming arguments allows to guess their purpose. Above,

    First Steps
  39. Sequences

    Fibs with Seq.cons

    This produces a never-ending recursion that leads to a stack overflow. <!-- Or with an int version: ```ocaml # let rec ints_v1 n = Seq.cons n (n + 1);; val fibs : int -> int -> int Seq.t = <fun> #

    Data Structures
  40. OCaml Programming Guidelines

    Naming Complex Arguments

    <!-- $MDX skip --> write <!-- $MDX skip --> In place of

    Resources
  41. Modules

    Submodule Implementation

    dune Definitions from a submodule are accessed by chaining module names, here Florence.Hello.print . Here is the updated dune file, with an additional executable: glasgow.ml florence.ml

    Module System
  42. Loops and Recursions

    Recursion

    In the first example, we'll read the whole file into memory (into a long string). There are essentially three possible approaches to this: Writing recursive functions requires a change in mindse

    Introduction
  43. Maps

    Finding Entries in a Map

    Note that find_first_opt and find_last_opt return the key-value pair, not just the value. The functions find_first and find_last behave similarly, except they throw exceptions instead of

    Data Structures
  44. 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
  45. Error Handling

    Exceptions

    Here, we add a variant Foo to the type exn and create a function that will raise this exception. Now, how do we handle exceptions? The construct is try ... with ... : Exceptions belong to

    Guides
  46. 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 succ

    Introduction
  47. File Manipulation

    Gotchas

    Don't forget to flush your out_channel s if you want to actually write something. This is particularly important if you are writing to non-files such as the standard output ( stdout ) or a socke

    Tutorials
  48. OCaml on Windows

    Vim and Emacs

    If you use Vim , the default Cygwin Vim will not work with Merlin. You will need install Vim separately. In addition to the usual instructions printed when installing Merlin, you may need to se

    Resources
  49. Mutability and Imperative Control Flow

    Arrays

    For a more detailed discussion on arrays, see the Arrays tutorial. the array location to update (when on the left-hand side of <- ), or the cell's content (when on the right-hand side of <- ). T

    Introduction
  50. File Manipulation

    Buffered Channels

    channels that write to a file: type out_channel channels that read from a file: type in_channel The normal way of opening a file in OCaml returns a channel . There are two kinds of channels:

    Tutorials