360 search results for "function"

Showing 101 - 150
  1. Lists

    List Scanning

    has evolved into its present state: pieces of frequently-used code are turned into useful general functions. This is rather clumsy, though. The standard library provides two useful functions for_all and exists for this common problem: There are more elaborate scanning

    Introduction
  2. A Tour of OCaml

    Defining a Higher-Order Function

    It is possible to pass a function as argument to another function. Functions having other

    First Steps
  3. A Tour of OCaml

    Modules and the Standard Library

    f the OCaml module system. It provides a means to separate concerns by preventing name clashes. Two functions having different type may have the same name if [...] provided by different modules. The List.map function which was used earlier in this section is also part of a module, the List module. When the optio

    First Steps
  4. OCaml Programming Guidelines

    Style dangers

    ls that the mutable keyword in the record-type definitions should be implicit. The “too much functional” danger : The programmer that adheres to this [...] systematic rewriting for loops with recursive functions, using lists in contexts where imperative data structures seem to be mandatory to anyone, pass

    Resources
  5. OCaml Programming Guidelines

    OCaml code generally considered unreadable

    atically code sequences with let in bindings. Mix computations and side effects, particularly in function calls. Recall that the evaluation order of function call arguments is unspecified, which implies that you must not mix side effects and computation

    Resources
  6. Formatting and Wrapping Text

    Most General Pretty-Printing: Using fprintf

    ng fprintf , the lambda-terms printing routines can be written as follows: We use the fprintf function to write the most versatile version of the pretty-printing functions for lambda-terms. Now, the

    Tutorials
  7. Profiling

    Tail Recursion

    then print the string, and jump back, and so on forever. It's a simple loop, not a recursive function call, so it doesn't use any stack space. Here is the assembler for just the loop function defined above: The file is called tail.ml , so following OCaml's usual procedure for naming

    Guides
  8. Profiling

    The Representation of Integers, Tag Bits, Heap-Allocated Values

    le_tag: Compare two floats. etc. It uses the following decision tree: Remember our polymorphic > function which caused us so much trouble in the previous [...] and found out that OCaml compiles a call to a C function called greaterthan whenever it sees the polymorphic form of >. This

    Guides
  9. Higher Order Functions

    Iterating over Optionals and Results

    defined in the standard library. We can do this by pattern-matching on our value and calling our function over the inner value in the Some or Ok branch. A [...] nal and result values. Normally, we want to run a function only if the option has Some value in it or if there is an Ok value . If there is no value in it,

    Introduction
  10. Higher Order Functions

    Iterating over custom data types

    Again, we iterate by pattern matching on values, applying a function to the deconstructed value and recursing over the [...] we go along: Now before we define our iteration function, its important to define what iteration means for our data type. Do we want to iterate from the bot

    Introduction
  11. Higher Order Functions

    Mapping Lists

    ct it. The main difference is that instead of throwing away the resulting value from running our function over the elements, we will reconstruct a list f [...] attern match on a list, get the head of it, run a function over it, and recurse over the body.

    Introduction
  12. Options

    Map Over an Option

    Incrementing an Integer The following are a few simple examples demonstrating how the Option.map function works with different types and transformations: Our custom map function is the same a the standard library's Option.map : Using pattern matching, it is possible to def

    Data Structures
  13. Options

    Extract the Content of an Option

    lue for Safe Extraction Since the option is None , it returns the provided default value. The function returns "hello" because the option contains a v [...] o value, Option.get raises an exception. The function successfully retrieves the value inside Some 42 . Example 1 : Extracting a Value with Option.g

    Data Structures
  14. Basic Data Types and Pattern Matching

    Unit

    The function print_endline prints the string followed by a l [...] ar with your own text and press Return . The function read_line reads an end-of-line terminated sequence of characters from standard input and returns

    Introduction
  15. Basic Data Types and Pattern Matching

    A Complete Example: Mathematical Expressions

    The factorise function above introduces another feature: guards to eac [...] e expressions' form, but they call the distrib function recursively on their subexpressions. This ensures that all its subexpressions get multiplied out

    Introduction
  16. Mutability and Imperative Control Flow

    Example: get_char Function

    to avoid an Unbound module error . We read characters from standard input using the input_char function from the OCaml standard library. Read and record [...] minal attributes (similar to assign ) We use two functions from the Unix module to read and update attributes of the terminal associated with standard inpu

    Introduction
  17. Monads

    Composition and Monad Laws

    nad laws: The monadic compose operator would enable us to compose those two into an identity function without having to write any additional code: R [...] r, imagine that we have increment and decrement functions: As the last line suggests, compose can be expressed as infix operator written >=> . We ca

    Data Structures
  18. Maps

    Merging Maps

    ond map drop drops both entries in the result map Here are examples of duplicate key resolution functions: Note : As with all the other functions of Map , the input maps are not modified. To merge two maps, use the union

    Data Structures
  19. Sequences

    Taking Parts of a Sequence

    his can be used to print integers without looping forever, as shown previously: When executed, the function begins by unfreezing seq (that is, calling seq [...] hing. It is a partial application and returns a function needing a unit to produce a result. a sequence called seq a unit value Observe the first line

    Data Structures
  20. Sequences

    Understanding the Difference

    emains a mystery, take a moment to compare the inputs to the Seq.Cons constructor and Seq.cons function. They look deceptively similar, but one takes a [...] reason, it is not possible to create a Fibonacci function using Seq.cons . Why is it so? The issue with fibs_v1 lies in the recursive call fibs_v1 n (

    Data Structures
  21. Lists

    Functions on Lists

    he pattern _ :: t the head of the list is not inspected, so its type cannot be relevant. Such a function is called polymorphic. Here is another polymorphic function, our own version of the @ operator for appending: This

    Introduction
  22. A Tour of OCaml

    Functions with Multiple Parameters and Partial Application

    The function cat_hi , which resulted from the partial applica [...] ion of cat , behaves as follows: This returns a function that expects a single string, here the b from the definition of cat . This is called a partial

    First Steps
  23. OCaml Programming Guidelines

    When to use open modules rather than leaving them closed

    l to open a module that modifies the environment and brings other versions of an important set of functions. For example, the Format module automaticall [...] rinting. This module redefines the usual printing functions print_string , print_int , print_float , etc., so when you use Format , open it systematical

    Resources
  24. Command-line Arguments

    Using the Arg Module

    The Arg module has many more actions than just Set and Set_string , and some lower-level function for parsing more complicated command lines. He [...] e , giving it our specification list, anonymous function, and usage message. Once it returns, the references will be filled with all the information requi

    Tutorials
  25. Calling Fortran Libraries

    Step 4: Now to OCaml

    And voila, we've called the fortran function from OCaml. prompt> ocamlc -o test gtd6.cmo wrap [...] rn how to do it). This tells OCaml that the temp function takes 5 parameters and returns a single floating point and calls the C

    Tutorials
  26. Functors

    Injecting Dependencies Using Functors

    t . The with type ... := ... constraint exposes that the two types t are the same. This makes functions from the injected dependency and result module u [...] into a functor that takes a module providing the function iter as a parameter. The with type 'a t := 'a Dep.t is called a "destructive type substitution"

    Module System
  27. Mutability and Imperative Control Flow

    It Depends: Module State

    has the type Hashtbl.t representing mutable data. It also exposes create , clear , and reset functions. The clear and reset functions return unit . This strongly signals the reader that they perform the side-effect of updating the

    Introduction
  28. Mutability and Imperative Control Flow

    Bad: Undocumented Side Effects

    If you're writing functions with non-obvious side effects, don't shadow existing definitions. Instead, give the function a descriptive name (for instance, Array.copy_with_analytics ) and document the fact that there's a

    Introduction
  29. The Compiler Backend: Bytecode and Native code

    Using the Frame Pointer to Get More Accurate Traces

    doesn't require adding in explicit probes to the binary, it does need to understand how to unwind function calls so that the kernel can accurately record the function backtrace for every event. Since Linux 3.9 the kernel has had support for using DWARF debug infor

    Runtime & Compiler
  30. Memoization

    Fibonacci

    imperative constructs (specifically, array update), the side effects are not visible outside the function fibm . So from a client's perspective, fibm is functional. There's no need to mention the imperative implementation (i.e., the benign side effects) that

    Data Structures
  31. Labelled and Optional Arguments

    Defining Optional Parameters With Default Values

    at -> float -> float = <fun> # let get_ok ?(exn = fun _ -> Invalid_argument "result is Error _") = function | Ok v -> v | Error e -> raise (exn e);; [...] optional parameter that defaults to 0. Inside the function, the parameter is named x . In the previous section, we've defined a

    Introduction
  32. Labelled and Optional Arguments

    Defining Optional Parameters Without Default Values

    exmplain use-case --> When an optional parameter isn't given a default value, its type inside the function is made an option . Here, len appears as ?len:int in the function signature. However, inside the body of the

    Introduction
  33. Loops and Recursions

    Recursion Example: Maximum Element in a List

    y tied to the problem specification. Functional programmers will tell you that it's because the functional style is at a much higher level than the impera [...] it's much simpler to reason logically about the functional version, which is useful if you wanted to formally prove that list_max is correct ("correct"

    Introduction
  34. Lists

    The Standard Library List Module

    In the List module documentation, functions which can raise an exception are marked. Such [...] module contains a wide range of useful utility functions, including pre-written versions of many of the

    Introduction
  35. Lists

    Maps and Iterators

    In addition, we have an imperative analogue to map , called iter . It takes an imperative function of type 'a -> unit and an 'a list and applies the function to each element in turn. A suitable

    Introduction
  36. Arrays

    Sorting an Array

    It sorts the provided array in place and in ascending order, according to the provided comparison function. Sorting performed by Array.sort modifies the c [...] numbers created above, we can use: a comparison function an array To sort an array, we can use the Array.sort

    Data Structures
  37. Error Handling

    Using the option Type for Errors

    It tends to be considered good practice nowadays when a function can fail in cases that are not bugs (i.e., not [...] r than throwing an exception. We can try those functions: Using option it is possible to write

    Guides
  38. Error Handling

    Naming Conventions

    exceptions. In such a context, the opposite convention is relatively common: the version of the function that raises exceptions is suffixed with _exn . Using the same functions, that would give the specification: This is extracted from the List module of the standard libr

    Guides
  39. Error Handling

    bind as a Binary Operator

    ten using Result.bind as a binary opeator: Writing x >>= f is very close to what is found in functionally tainted programming languages which have me [...] st. Nevertheless, it has some appeal when named functions are used. It looks a bit like good old Unix pipes: It may seem pointless. To make sense,

    Guides
  40. Higher Order Functions

    Iterating

    Iterating in OCaml means that if there is one value (or more), we'd like to apply a function to it. But in OCaml the pattern for iteration can be extended to other kinds of data types, like optional values or results, or trees and lazy sequences. loop through elements in a list go over the

    Introduction
  41. Higher Order Functions

    Mapping

    ave a list of users, maybe we want to get a list of usernames. Or if we have an optional password, we may want to encrypt it only if it is set. In contrast to iterating, sometimes we want to apply a function over some data and we want to keep the results without changing the shape of the data.

    Introduction
  42. Higher Order Functions

    Binding as early returns

    a user from a database, and only if there is a user try access the user's email, you could use Option.bind to short-circuit on the first operation: This same pattern is useful to build chains of functions that short circuit on specific values.

    Introduction
  43. Values and Functions

    What is a Value?

    er to avoid runtime type checks in binaries. In OCaml, the compiler removes type information, so it's not available at runtime. In programming theory, this is called subject reduction . Like most functional programming languages, OCaml is an expression-oriented programming language. That means programs are expressions. Actually, almost everything is an expression. In OCaml, statements don't specify

    Introduction
  44. Values and Functions

    Global Definitions

    is defined globally. This is what happens when writing a definition in UTop: If the expression can be evaluated, it is. Otherwise, the expression is turned into a value as-is. That's the case of function definition. Every value can be named. This is the purpose of the let … = … statement. The name is on the left; the expression is on the right.

    Introduction
  45. Values and Functions

    Pattern Matching on Tuples

    The List.split function turns a list of pairs into a pair of lists. Here, each resulting list is bound to a name. A common case is tuples. It allows the creation of two names with a single let .

    Introduction
  46. Values and Functions

    The Application Operator

    The @@ application operator applies an argument (on the right) to a function (on the left). It is useful when chaining several calls, as it avoids writing parentheses, which creates easier-to-read code. Here is an example with and without parentheses: The application operat

    Introduction
  47. Values and Functions

    The Pipe Operator

    This is just like a Unix shell pipe. The pipe operator ( |> ) also avoids parentheses but in reversed order: function on right, argument on left.

    Introduction
  48. 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
  49. 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
  50. 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