352 search results for "function"

Showing 201 - 250
  1. Labelled and Optional Arguments

    Forwarding an Optional Argument

    ?len is sufficient to forward without unwrapping. In the definitions of take and rtake , the function sub is called with optional arguments passed wi [...] ithout unwrapping. These examples reuse the sub function defined in the Optional Arguments Without Default Values section.

    Introduction
  2. Memory Representation of Values

    OCaml Types Disappear at Runtime

    trees (ASTs). The next stage is a type checking pass over the AST. In a validly typed program, a function cannot be applied with an unexpected type. For example, the print_endline function must receive a single string argument, and an int will result in a type error.

    Runtime & Compiler
  3. Memory Representation of Values

    String Values

    Care should be taken that any C library functions that receive these buffers can also cope with [...] , the C memcopy or memmove standard library functions can operate on arbitrary data, but strlen or strcpy both require a NULL -terminated buffer,

    Runtime & Compiler
  4. Operators

    Goals

    Using operators as functions and reciprocally, using functions as operators Assign the right associativity and precedence to a custom operator Use and define cus

    Advanced Topics
  5. Operators

    Unary Operators

    Unary operators are also called prefix operators. In some contexts, it can make sense to shorten a function's name into a symbol. This is often used as a way to shorten the name of a function that performs some sort of conversion over its argument.

    Advanced Topics
  6. Operators

    Operator Associativity and Precedence

    at the left, therefore &^ associates to the left Although both expressions are calling the same function ( par ), they are evaluated in different orders. [...] ator associativity with an example. The following function concatenates its string arguments, surrounded by | characters and separated by a _ character.

    Advanced Topics
  7. Loops and Recursions

    For Loops and While Loops

    with for loops, the language doesn't provide a way to break out of a while loop, except by throwing an exception, so this means that while loops have fairly limited use. Again, remember that functional programmers like recursion, so while loops are second-class citizens in OCaml. <!-- $MDX skip --> While loops in OCaml are written: Functional programmers tend to use recursion instead

    Introduction
  8. Loops and Recursions

    Looping Over Strings

    String.copy copies a string, like strdup . There is also a String.iter function which works like List.iter , except over the cha [...] e also contains dozens of useful string-related functions, and some of them are concerned with looping over strings.

    Introduction
  9. Lists

    Association Lists

    e able to make a list of pairs from a pair of lists and vice versa. The List module provides the functions split and combine for this purpose: Ass [...] library's Map or Hashtbl modules. But these functions from the List module are useful for lists which are generally small, and have other advantages

    Introduction
  10. Arrays

    Iterate on an Array

    can also be made using for loops. Here is the same example using a loop: Array.iter applies a function to each element of an array, one at a time. The given function must return unit , operating by side effect. To print all the elements of the array zeroes creat

    Data Structures
  11. Arrays

    Map an Array

    The Array.map function creates a new array by applying a given function to each element of an array. For example, we can get an array containing the square of each number

    Data Structures
  12. Arrays

    Conclusion

    of arrays in OCaml, including how to create and manipulate them, as well as some of the most useful functions and use cases. Please refer to the standard lib [...] ary documentation to browse the complete list of functions of the Array module.

    Data Structures
  13. A Tour of OCaml

    Lists

    st of the list. In OCaml, pattern matching provides a means to inspect data of any kind, except functions. In this section, it is introduced on lists, and [...] attern matching can be used to define a recursive function that computes the sum of a list of integers: Lists are defined as being either empty, written [

    First Steps
  14. 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 [...] ng pattern matching. For instance, the predefined function snd returns the second component of a pair: Tuples are fixed-length collections of elements of

    First Steps
  15. A Tour of OCaml

    Variant Types

    As previously shown, sum , length , and map functions provide examples of pattern matching over the list variant type. Like a function, a variant can be recursive if it refers to itself in its own definition. The predefined type list

    First Steps
  16. A Tour of OCaml

    Exceptions

    ptions are caught using the try … with … construction: Note that exceptions do not appear in function types. Exceptions are raised using the raise function. When a computation is interrupted, an exception is thrown. For instance:

    First Steps
  17. A Tour of OCaml

    Working with Mutable State

    This behaviour is the same as in an imperative language. However, although ; is not defined as a function, it behaves as if it were a function of type unit -> unit -> unit . Display the contents of the reference text on standard output Up

    First Steps
  18. A Tour of OCaml

    Conclusion

    In this tutorial, OCaml was used interactively. The next tutorial, Your First OCaml Program , shows you how to write OCaml files, how to compile them, and how to kickstart a project. <!-- 1. Values

    First Steps
  19. OCaml on Windows

    Installing Opam on Windows

    You should now have a functioning OCaml environment ready for development. If yo [...] onment. opam requires a Unix-like environment to function. By default, opam relies on Cygwin and is also compatible with MSYS2. You will notice that the r

    Resources
  20. Your First OCaml Program

    Modules and the Standard Library, Cont'd

    This replaces the function print_endline with the function printf from the Printf module in the standard library. Building and executing this modified ver

    First Steps
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. Values and Functions

    Local Definitions

    In both examples, d and e are local definitions. Arbitrary combinations of chaining or nesting are allowed. e is bound to 6 inside e * 5 d is bound to 30 inside d * 7 Here is how scopin

    Introduction
  39. Values and Functions

    Forms of Pattern Matching

    In the following sections, we explore matching inside let bindings, which is a special case. In the next chapter on Basic Data Types and Pattern Matching , we examine pattern matching in general c

    Introduction
  40. Values and Functions

    Pattern Matching in Definitions

    <!--the example illustrates tuples::--> When pattern matching only has one case, it can be used in name definitions and in let ... = and fun ... -> expressions. In that case, less or more than

    Introduction
  41. Values and Functions

    Pattern Matching on Records

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

    Introduction
  42. Values and Functions

    Pattern Matching on unit

    <!-- user-defined single constructor variant example --> Note : In order for compiled files to only evaluate an expression for its side effects, you must write them after let () = . Above, the pa

    Introduction
  43. Values and Functions

    Pattern Matching on User-Defined Types

    This also works with user-defined types.

    Introduction
  44. Values and Functions

    Nested Pattern Matching on User-Defined Types

    Notice that contact is now available at the top-level as a bound variable: Next, we demonstrate the two-phase approach for accessing email and phone . This brings contact into our top-lev

    Introduction
  45. 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
  46. 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
  47. 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
  48. 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
  49. The Compiler Frontend: Parsing and Type Checking

    Generating Documentation from Interfaces

    some source code that's been annotated with docstring comments: OCaml uses specially formatted comments in the source code to generate documentation bundles. These comments are combined with the function definitions and signatures, and output as structured documentation in a variety of formats. Tools such as odoc and ocamldoc can generate HTML pages, LaTeX and PDF documents, UNIX manual p

    Runtime & Compiler
  50. The Compiler Frontend: Parsing and Type Checking

    Adding Type Annotations to Find Errors

    her verbose and with a line number that doesn't point to the exact location of the incorrect variant name. The best the compiler can do is to point you in the general direction of the algebra function application. There's a single character typo in the code so that it uses Nu instead of Num . The resulting type error is impressive: For instance, consider this broken example that expresse

    Runtime & Compiler