358 search results for "function"

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

    Iterating Over Sequences

    ers forever,” and you have to press Ctrl-C to interrupt the execution. The following code is the same infinite loop without any output: The OCaml Standard Library also contains a Seq.iter function, which has the same behavior as List.iter . Writing this:

    Data Structures
  10. 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
  11. 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
  12. Memory Representation of Values

    Distinguishing Integers and Pointers at Runtime

    . This representation means that integers are unboxed runtime values in OCaml so that they can be stored directly without having to allocate a wrapper block. They can be passed directly to other function calls in registers and are generally the cheapest and fastest values to use in OCaml. OCaml values don't all have to be boxed at runtime. Instead, values use a single tag bit per word to disting

    Runtime & Compiler
  13. Memory Representation of Values

    Integers, Characters, and Other Basic Types

    it are very efficient to use, since integers are never allocated on the heap. They can be passed directly in registers and not appear on the stack if you don't have too many parameters to your functions. Modern architectures such as x86_64 have a lot of spare registers to further improve the efficiency of using unboxed integers. Many basic types are efficiently stored as unboxed integers at

    Runtime & Compiler
  14. Memory Representation of Values

    Tuples, Records, and Arrays

    The Obj.repr function retrieves the runtime representation of any OCaml value. Obj.is_block checks the bottom bit to determine if the value is a block header or an unboxed integer. You can check the difference be

    Runtime & Compiler
  15. Memory Representation of Values

    Floating-Point Numbers and Arrays

    hich are not optimized in the same way and have the normal tuple tag value (0). This tells us that float arrays have a tag value of 254. Now let's test some sample values using the Obj.tag function to check that the allocated block has the expected runtime tag, and also use Obj.double_field to retrieve a float from within the block: First, let's check that float arrays do in fact have

    Runtime & Compiler
  16. Memory Representation of Values

    Custom Heap Blocks

    ted. This finalizer has nothing to do with ordinary OCaml finalizers (as created by Gc.finalize and explained in Understanding The Garbage Collector ). They are instead used to call C cleanup functions such as free . The first word of the data within the custom block is a C pointer to a struct of custom operations. The custom block cannot have pointers to OCaml blocks and is opaque to the

    Runtime & Compiler
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. Operators

    Allowed Operators

    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
  24. 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
  25. Arrays

    Length of an Array

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

    Data Structures
  26. A Tour of OCaml

    Type Conversion and Type-Inference

    ison to other languages. Arguably, this saves more time than we lose by being more explicit. In OCaml you need to explicitly convert the integer to a floating point number using the float_of_int function: In the first example, + is intended to be used with integers, so it can't be used with the 2.5 float. In the second example, +. is intended to be used with floats, so it can't be used with th

    First Steps
  27. A Tour of OCaml

    Pattern Matching, Cont'd

    mes, just as let does. In the third pattern, x designates the data inside the double-wrapped option. Pattern matching isn't limited to lists. Any kind of data can be inspected using it, except functions. Patterns are expressions that are compared to an inspected value. It could be performed using if … then … else … , but pattern matching is more convenient. Here is an example using the opti

    First Steps
  28. A Tour of OCaml

    Records

    Here, the pattern { age = x; _ } is typed with the most recently declared record type that has an age field of type int . The type int is inferred from the expression 13 <= x && x <= 19 . The function is_teenager will only work with the found record type, here person . When defining gerard , no type needs to be declared. The type checker will search for a record which has exactly three fiel

    First Steps
  29. Configuring Your Editor

    1) Hovering for Type Information

    This is a great feature that let's you see type information of any OCaml variable or function. All you have to do is place your cursor over the code and it will be displayed in the tooltip. VSCode Hovering

    Tooling
  30. Configuring Your Editor

    Finer configuration

    OCaml-eglot can be finely configured, the project README gives several configuration paths to adapt perfectly to your workflow. You will also find there an exhaustive presentation of the different functions offered by the mode.

    Tooling
  31. Configuring Your Editor

    Getting Type Information

    OCaml-eglot README provides a comprehensive overview of all the functions available in this mode! Emacs Type information Opening an OCaml file should launch an ocaml-lsp server, and you can convince yourself that it's working by using, for example, the ocaml-eglot-ty

    Tooling
  32. Your First OCaml Program

    Installing and Using Modules From a Package

    efer to the Sexplib documentation for more information. Next, define a string containing a valid S-expression in bin/main.ml . Parse it into a S-expression with the Sexplib.Sexp.of_string function, and then convert it back into a string with Sexplib.Sexp.to_string and print it. To illustrate this, let's update our hello project to parse a string containing an S-expression and print

    First Steps
  33. Your First OCaml Program

    Using the Preprocessor to Generate Code

    le, and edit it to look like this: Let's assume we'd like hello to display its output as if it was a list of strings in UTop: ["hello"; "using"; "an"; "opam"; "library"] . To do that, we need a function turning a string list into a string , adding brackets, spaces, and commas. Instead of defining it ourselves, let's generate it automatically with a package. We'll use ppx_deriving . Here is how t

    First Steps
  34. OCaml Programming Guidelines

    Usage in Module Interface

    The function's usage must appear in the module's interface that exports it, not in the program that implements it. Choose comments as in the OCaml system's interface modules, which will subsequently automatic

    Resources
  35. OCaml Programming Guidelines

    Use Assertions

    is verified upon each execution, while a comment can quickly become obsolete, making it detrimental to understanding the program. <!-- $MDX skip --> For example, the conditions to validate a function's arguments are usefully verified by assertions. Use assertions as much as possible, as they let you avoid verbose comments while allowing a useful verification upon execution.

    Resources
  36. OCaml Programming Guidelines

    Don't use abbreviations for global names

    Global identifiers (including the names of functions) can be long because it's important to understand what purpose they serve far from their definition.

    Resources
  37. OCaml Programming Guidelines

    Subdividing into modules

    For each interface, you must document the things defined by the module: functions, types, exceptions, etc. For each module, you must explicitly write an interface. You must subdivide your programs into coherent modules.

    Resources
  38. OCaml Programming Guidelines

    Single branches

    If cond , e1 , and e2 are small, simply write them on one line: If the expressions making up a conditional are purely functional (without side effects), we advocate binding them within the conditional by using let e = ... in when they're too big to fit on a single line. Justification : This way you get back the sim

    Resources
  39. 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
  40. 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
  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. 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
  47. 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
  48. 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
  49. Comparison of Standard Containers

    Lists: Immutable Singly-Linked Lists

    Not very efficient for: random access, indexed elements Well-suited for: I/O, pattern-matching Adding an element: O(1) , cons operator :: Length: O(n) , function List.length Accessing cell i : O(i) Finding an element: O(n) Adding an element always creates a new list l from an element x List tl . tl remains unchanged, but it is not copied either.

    Resources
  50. Comparison of Standard Containers

    Arrays: Mutable Vectors

    of elements of known size, accessing elements by numeric index, and modifying in-place elements. Basic arrays have a fixed length. Adding an element (by creating a new array): O(n) Length: O(1) , function Array.length Accessing cell i : O(1) Finding an element: O(n) Arrays are mutable data structures with a fixed length and random access.

    Resources