364 search results for "function"

Showing 151 - 200
  1. OCaml Programming Guidelines

    Always give the same name to function arguments which have the same meaning

    If necessary, make this nomenclature explicit in a comment at the top of the file. If there are several arguments with the same meaning, then attach numeral suffixes to them.

    Resources
  2. OCaml Programming Guidelines

    Local identifiers can be brief and should be reused from one function to another

    A tolerated exception to the recommendation not to use capitalisation to separate words within identifiers when interfacing with existing libraries which use this naming convention. This lets OCa

    Resources
  3. OCaml Programming Guidelines

    Exceptions

    -> Handling all exceptions by try ... with _ -> is usually reserved for the program's main function. If you must catch every exception in order to [...] e system as possible. For example, every search function that fails should raise the predefined exception Not_found . Be careful to handle the exceptions

    Resources
  4. OCaml Programming Guidelines

    How to Choose Between Classes and Modules

    Use modules when the data structures are fixed and their functionality is equally fixed or it's enough to add new functions in the programs which use them. Use conventional data structures (in particular, variant type

    Resources
  5. OCaml Programming Guidelines

    Clarity of OCaml Code

    r programming paradigms): imperative programming (based on the notion of state and assignment), functional programming (based on the notion of function,

    Resources
  6. OCaml Programming Guidelines

    Function application: the same rules as those in mathematics for usage of trigonometric functions

    In mathematics you write sin x to mean sin (x) . In the same way sin x + cos x means (sin x) + (cos x) not sin (x + (cos x)) . Use the same conventions in OCaml: write f x + g x to mean

    Resources
  7. Error Handling

    Predefined Exceptions

    reexisting exceptions Raise custom exceptions When implementing a software component which exposes functions raising exceptions, a design decision must be [...] ones are intended to be raised by user-written functions: Although the last one doesn't look as an exception, it actually is. The standard library pr

    Guides
  8. Error Handling

    Printing

    own exceptions: To print an exception, the module Printexc comes in handy. For instance, the function notify_user : (unit -> 'a) -> 'a below calls a function, and if it fails, prints the exception on stderr . If stack traces are enabled, this

    Guides
  9. Error Handling

    Throwing Exceptions From option or result

    ons, pattern matching and raise must be used. From option to Invalid_argument exception, use function Option.get : From result to Invalid_argument exception, use functions Result.get_ok and Result.get_error : This is done by using the following

    Guides
  10. Error Handling

    Conversion Between option and result

    From option to result , use function Option.to_result : From result to option , use function Result.to_option : This is done by using the following

    Guides
  11. Calling Fortran Libraries

    Step 3: Compile the Shared Library

    This will create a shared object library called wrapper.so containing the fortran function and the wrapper function. The -lg2c option is required to provide the implementations of the built in fortran

    Tutorials
  12. Basic Data Types and Pattern Matching

    Constructors With Data

    gle parameter. We need to pass an inspected expression to the match … with … construct. The function … is a special form of an anonymous function that takes a parameter and forwards it to a match … with … construct, as shown above. Abov

    Introduction
  13. Monads

    Monad Laws

    e the right type to be on the right-hand side of >>= . So we have to insert an extra anonymous function fun x -> ... to make the types correct. (m >>= [...] ing the trivial effect on a value, then binding a function on it, is the same as just calling the

    Data Structures
  14. Lists

    List Searching

    elements for which the predicate is true, the second those for which it is false. The filter function again takes a predicate and tests it against ea [...] the list of all elements which test true: The function find returns the first element of a list matching a given predicate (a predicate is a testing

    Introduction
  15. Understanding the Garbage Collector

    Attaching Finalizer Functions to Values

    <div class="note"> OCaml's automatic memory management guarantees that a value will eventually be freed when it's no longer in use, either via the GC sweeping it or the program terminating. It'

    Runtime & Compiler
  16. Labelled and Optional Arguments

    Labelling Parameters

    sing the same name as label and parameter. Here is how range is used: lo and hi inside the function's body, as usual first and last when calling the function; these are the labels. The parameters of range are named Here is how to name parameters in a

    Introduction
  17. Labelled and Optional Arguments

    Passing Labelled Arguments Using the Pipe Operator

    Let's modify the range function previously defined by adding an additional parameter step . Declaring a function's unlabelled argument as the first one simplifies reading the

    Introduction
  18. Sets

    Sets With Custom Comparators

    e Insensitive String Set"). We can accomplish this by passing an ad-hoc module to the Set.Make function: Let's say we want to create a set of strings th [...] et module we created uses the built-in compare function provided by the String module. The Set.Make functor expects a module with two definitions: a t

    Data Structures
  19. Mutability and Imperative Control Flow

    References

    or more information on how unary and binary operators work in OCaml. The dereference operator is a function that takes a reference and returns its contents. [...] contents. The assignment operator := is just a function. It takes Assignment Operator The

    Introduction
  20. Mutability and Imperative Control Flow

    Remark: References Are Single Field Records

    create does the same as the ref function provided by the standard library. assign does th [...] deref does the same as the ( ! ) operator. The functions: Since references are single field records, we can define

    Introduction
  21. Mutability and Imperative Control Flow

    Evaluating Expressions in Sequence

    er containing value n Updates the reference's contents to 2 × (n + 1) Imagine we want to write a function that: In OCaml, begin … end and parentheses [...] olon is not truly an operator because it is not a function of type unit -> 'a -> 'a . It is rather a construct of the language. It allows adding a semicolo

    Introduction
  22. Sequences

    Constructing Sequences

    tains a module for sequences called Seq . It contains Seq.int , which we implemented above. The function ints n looks as if building the infinite sequen [...] in_int . We can also construct sequences using functions. Here is how to build an infinite sequence of integers: Note: The second component of each Se

    Data Structures
  23. Sequences

    Sequences for Conversions

    Similar functions are also provided for sets, maps, hash tables ( [...] , it is advised to expose to_seq and of_seq functions. Lists Arrays Strings Throughout the OCaml Standard Library, sequences are used as a bri

    Data Structures
  24. Sequences

    Miscellaneous Considerations

    ps it would be enlightening to illustrate the use of Seq.unfold by re-implementing the already seen function primes? Perhaps in an exercise rather than in the [...] accumulator, and also the fact that the producer function loops until it finds a new prime to yield, because Seq.unfold does not allow the producer to “ski

    Data Structures
  25. The Compiler Backend: Bytecode and Native code

    Executing Bytecode

    ces bytecode that targets the standard OCaml runtime by default, and so needs to know about any C functions that are referenced from other libraries that [...] s: the bytecode interpreter, GC, and a set of C functions that implement the primitive operations. The bytecode contains instructions to call these C

    Runtime & Compiler
  26. Maps

    Introduction

    StringMap , OCaml's toplevel displays the module's signature. Since it contains a large number of functions, the output copied here is shortened for brevi [...] es the keys' type to be used in the maps, and a function for comparing them. Note : The concept of a Map in this tutorial refers to a data structure that

    Data Structures
  27. Maps

    Finding Entries in a Map

    ote 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, e [...] d find_last_opt if we want to use a predicate function: find_opt returns None find throws the Not_found exceptions When the searched key is absent f

    Data Structures
  28. 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

    Data Structures
  29. 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 type t exposing the type of the map's key A function compare : t -> t -> int

    Data Structures
  30. Arrays

    Introduction

    ch as: This tutorial aims to introduce the subject of arrays in OCaml and showcase the most useful functions and use cases. Despite these differences, many of the functions readily available on arrays are similar to the ones available for lists. Please refer to the List

    Data Structures
  31. Arrays

    Creating Arrays

    Array.init generates an array of a given length by applying a function to each index of the array, starting at 0. The fo [...] array containing the first 5 even numbers using a function which doubles its argument: Alternatively, you can create an array using the Array.make

    Data Structures
  32. Arrays

    Copying Part of an Array into Another Array

    tarting at index 1 into the last part of zeroes , starting at index 3 . We can also use this function to copy part of an array onto itself: This copie [...] hin the bounds of each array. The Array.blit function efficiently copies a contiguous part of an array into an array. Similar to the array.(x) <- y ope

    Data Structures
  33. Memory Representation of Values

    Polymorphic Variants

    ts with constructors thus use one word of memory more than normal variant constructors. The hash function is designed to give the same results on 32-bit an [...] integer value is determined by applying a hash function to the name of the variant. The hash

    Runtime & Compiler
  34. Common Error Messages

    Warning: This optional argument cannot be erased

    See the Labels section for more details on functions with labelled arguments. The solution is simply to add one argument of type unit, like this: Functions with optional arguments must have at least one non-labelled argument. For instance, thi

    Resources
  35. Debugging

    Limitations

    ugger for OCaml under Unix: ocamldebug . Its use is illustrated in the next section. Stepping a functional program has a meaning which is a bit weird to d [...] ts that happen when a parameter is passed to a function, when entering a pattern matching, or selecting a clause in a pattern matching. Computation pro

    Guides
  36. Debugging

    Finding the Cause of a Spurious Exception

    pe ocamldebug a.out , then r , b , and bt gives you the backtrace. <!-- $MDX skip --> The function that calls it is in module Uncaught , file unca [...] ne 8, char 38: <!-- $MDX skip --> So the last function called is from module List on line 191, character 26, that is: But, as you know, you want the

    Guides
  37. OCaml Programming Guidelines

    How to Comment Programs

    Avoid comments in the bodies of functions. Prefer one comment at the beginning of the function that explains how a particular algorithm works. Once more, if there is no difficulty, there is no

    Resources
  38. OCaml Programming Guidelines

    Comments line by line in imperative code

    physical mutations in data structures), it is sometimes mandatory to comment inside the body of functions to explain the algorithm's implementation encode [...] low successive invariant modifications that the function must maintain. Once more, if there is some difficulty commenting is mandatory, for each program l

    Resources
  39. OCaml Programming Guidelines

    Separate words by underscores: ( int_of_string , not intOfString )

    pitalised words are reserved for constructors and module names. In contrast, regular variables (functions or identifiers) must start with a lowercase le [...] and it is forbidden to choose IntOfString as a function name.

    Resources
  40. OCaml Programming Guidelines

    Pattern-matching warnings

    to the new constructor, if warranted. On the contrary, the “catch-all” clause will make the function compile silently, and it might be thought that the function is correct, as the new constructor will be handled by the default case. Those with useless clau

    Resources
  41. OCaml Programming Guidelines

    for loops

    Justification : The recursive function lets you code any loop whatsoever simply, even [...] p is complex or returns a result, use a recursive function. <!-- $MDX skip --> To simply traverse an array or a string, use a for loop.

    Resources
  42. OCaml Programming Guidelines

    Data Structures

    r, it is very difficult to limit the range of acceptable integers. One must define construction functions that will ensure the program's mandatory invaria [...] for type_of_definition , we will use a predicate function recursivep that returns true if the definition is recursive. Answer : This method is specific

    Resources
  43. OCaml Programming Guidelines

    Height of the Page

    Justification : When a function goes beyond one screenful, it's time to divide [...] t readable and is difficult to keep correct. A function should always fit within one screenful (of about 70 lines), or in exceptional cases two, at the v

    Resources
  44. OCaml Programming Guidelines

    How to Indent Global let ... ;; Definitions

    margin too quickly. <!-- $MDX skip --> The body is justified just under the name of the defined function. Justification : The vertical bars separating t [...] ular indentation of 1 or 2 spaces: The body of a function defined globally in a module is generally indented normally. However, it's okay to treat this cas

    Resources
  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 [...] e that, indeed, List.find or String.sub are functions that might fail by raising an exception. Historically, the first way of handling errors in OCaml

    Guides
  46. Error Handling

    Turning Exceptions into option or result

    Some may like to turn this into a higher-order generic function: It would be same for result , except some data [...] or. The standard library does not provide such functions. This must be done using try ... with or match ... exception statements. For instance, here i

    Guides
  47. Basic Data Types and Pattern Matching

    Byte Sequences

    rray . Operations on bytes values are provided by the Stdlib and the Bytes modules. Only the function Bytes.get allows direct access to the character [...] bytes literally, so they must be produced by a function. <!--CR Moved intro pp to after example, as it contains the definition. Perhaps a short intro se

    Introduction
  48. Basic Data Types and Pattern Matching

    Lists

    ce with respect to lists: Operations on lists are provided by the List module. The List.append function concatenates two lists. It can be used as an oper [...] values they contain. Lists play a central role in functional programming, so they have a dedicated tutorial . As literals, lists are very much like arrays

    Introduction
  49. Basic Data Types and Pattern Matching

    Tuples

    t associative . In the standard library, both are defined using pattern matching. Here is how a function extracts the third element of the product of four types: The predefined function fst returns the first element of a pair, while snd returns the second element of a pair. This

    Introduction
  50. Basic Data Types and Pattern Matching

    Recursive Variants

    bol _ , which catches everything. It returns false on all data that is neither Array nor Object . Functions defined using pattern matching on recursive variants are often recursive too. This function checks if a name is present in a whole JSON tree: Both constructors Array and Object contain values of type json . This is the case for the following definition, which can be used to store J

    Introduction