358 search results for "function"

Showing 101 - 150
  1. Sequences

    Filtering a Sequence

    s input incrementally. Unlike traditional recursion, which works towards a base case, corecursive functions must indefinitely produce values as a stream. The trial_div function is corecursive because it does not immediately compute the complete sequence of primes. Instead,

    Data Structures
  2. Sequences

    Unfolding Sequences

    The function Seq.uncons returns the head and tail of a seque [...] ise, it returns None . We can check our map function by applying a square

    Data Structures
  3. Loops and Recursions

    Mutable Records, References (Again!) and Arrays

    OCaml won't let you: Anyway, let's see print_name in action: Notice a strange (and very non-functional) feature of print_name : it modifies its access_count parameter. This function is not "pure." OCaml is a

    Introduction
  4. 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
  5. Memoization

    Just for Fun: Party Optimization

    We could memoize all calls, but that wouldn't improve speed much.) This requires just introducing a function `lb_mem` that looks up and records memoized forma [...] h the naive recursive implementation called the function party many times with the same arguments. Memoization saves all those calls. Further, the party o

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

    Understanding Name Mangling

    Anonymous functions are hard to predict without inspecting intermedi [...] odify the source code to let-bind the anonymous function to a variable name. The symbol is prefixed by caml and the local module name, with dots replac

    Runtime & Compiler
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  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. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. Options

    Fold an Option

    Here is the same function, using Option.fold : The Option.fold function can be used to implement a fall-back logic without writing pattern matching. For instance, here is

    Data Structures
  22. 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
  23. 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
  24. 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
  25. 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
  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. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. 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
  46. OCaml Programming Guidelines

    Factor out snippets of repeated code by defining them in separate functions

    Sharing code obtained in this way facilitates maintenance, since every correction or improvement automatically spreads throughout the program. Besides, the simple act of isolating and naming a sn

    Resources
  47. OCaml Programming Guidelines

    Never copy-paste code when programming

    ten lines of code is repeated twenty times throughout the program. By contrast, if an auxiliary function defines those ten lines, it is fairly easy to see [...] find where those lines are used: simply where the function is called. If code is copy-pasted all over the place, then the program is more difficult to und

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