352 search results for "function"

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

    Miscellaneous Considerations

    e of OCaml 4.14. Beware books and documentation written before may still mention it. Rizo I Streaming Simon Cruanes and Gabriel Radanne Iter Simon Cruanes OSeq (an extension of Seq with more functions) Jane Street Base.Sequence There are a couple of related libraries, all providing means to handle large flows of data:

    Data Structures
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. Arrays

    Length of an Array

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

    Data Structures
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. How to Work with the Garbage Collector

    The Gc Module

    .ml --> <!-- TODO: Probably write a GC example without dependencies --> Here is a program that runs and then prints out GC statistics just before quitting: The Gc module contains some useful functions for querying and calling the garbage collector from OCaml programs.

    Guides
  46. How to Work with the Garbage Collector

    Exercises

    xtend the program so it acquires a read lock on getting the record, but upgrades this to a write lock just before the user updates any field. Support a variable number of records , and add a function to create a new record (in the file). [Tip: OCaml has support for weak hashtables.] Add support for variable-length records . Make the underlying file representation a DBM-style hash . Provide

    Guides
  47. Transitioning to Multicore with ThreadSanitizer

    Address the Reported Races and Rerun the Tests, Take 2 (Steps 3 and 2)

    ml 5.x parallelism, hurrah! We can now rerun our tests under TSan to confirm the fix: Oh, wait! When raising an exception in transfer , we forgot to unlock the Mutex again. Let's adapt the function to do so:

    Guides
  48. Transitioning to Multicore with ThreadSanitizer

    Final Remarks and a Word of Warning

    l fix as follows: The programming pattern of 'always-having-to-do-something-at-the-end' that we encountered with the missing Mutex.unlock is a recurring one for which OCaml offers a dedicate function:

    Guides
  49. Error Handling

    Documentation

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

    Guides
  50. 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