364 search results for "function"

Showing 251 - 300
  1. Values and Functions

    Discarding Values Using Pattern Matching

    <!-- END Version Two --> Tuples behave differently from records; contained data is anonymous, and its position is used to access it. To discard the email value from the tuple of the contact fi

    Introduction
  2. Values and Functions

    Scopes and Environments

    <!-- With respect to the environment, there are no means to: - List its contents - Clear its contents - Remove a definition - Reset it to an earlier state --> Top-level expressions are also statemen

    Introduction
  3. Values and Functions

    Inner Shadowing

    <!-- A name-value pair in a local expression *shadows* a binding with the same name in the global environment. In other words, the local binding temporarily hides the global one, making it inaccessib

    Introduction
  4. Values and Functions

    Same-Level Shadowing

    There are now two definitions of h in the environment. The first h is unchanged. When the second h is defined, the first one becomes unreachable. Another kind of shadowing takes place when t

    Introduction
  5. Higher Order Functions

    Mapping Options

    Note that both sides of the match return the same thing: if we had a None we return None , if we have a Some we return a Some . This way, the structure is preserved. Mapping an optional valu

    Introduction
  6. Higher Order Functions

    Mapping Results

    Both of these are useful in different situations, such as wanting to change the type of errors, or only perform operations once we have an Ok value. We can map the value in the Ok value constr

    Introduction
  7. Higher Order Functions

    Mapping Custom Data Types

    Note that the structure of the tree is preserved, but every time we encounter a value , we update it with (fn value) . When working with our custom data types, such as the tree we used in the

    Introduction
  8. Higher Order Functions

    Let-ops

    This has the advantage of making code a lot more readable, without changing the behavior we've come to expect from bind calls. Thankfully, OCaml lets us redefine a subset of operators called let-

    Introduction
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. Error Handling

    Documentation

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

    Guides
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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
  48. 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
  49. 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
  50. 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