379 search results for "function"

Showing 101 - 150
  1. The Compiler Backend: Bytecode and Native code

    The Impact of Polymorphic Comparison

    the location of the minor heap in the %r15 register since it's so frequently referenced in OCaml functions. The minor heap pointer can also be changed by [...] hed on the stack (the %rsp register), and a C function call is invoked by placing a pointer to caml_greaterthan in %rax and jumping to caml_c_call

    Runtime & Compiler
  2. A Tour of OCaml

    Side-Effects and the unit Type

    Input-output is an example of something taking place when executing a function but which does not appear in the function type. This is called a side-effect and does not stop at I/O. The unit type is often used to ind

    First Steps
  3. Your First OCaml Program

    Why Isn't There a Main Function?

    ll those will take place in the same order. That's OCaml main. Although bin/main.ml 's name suggests it contains the application entry point into the project, it does not contain a dedicated main function, and there is no requirement that a project must contain a file with that name in order to produce an executable. A compiled OCaml file behaves as though that file were entered line by line into the

    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. 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
  7. 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
  8. 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
  9. Modules

    Abstract and Read-Only Types

    le to access a read-only record field's value, but creating such a record requires using a provided function. The type dalet is read-only . Pattern matchi [...] ut values can only be constructed by the provided functions, here dalet_of . Type gimel is abstract . Values can be created or manipulated, but only as

    Module System
  10. 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
  11. Sequences

    Introduction

    In OCaml, any value a of type t can be turned into a constant function by writing fun _ -> a or fun () -> a . The latter function is called a thunk . Using this terminology, Seq.t values are thunks. This explains why sequen

    Data Structures
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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 as the standard library's Option.map : Using pattern matching, it is possible to de

    Data Structures
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. Error Handling

    bind as a Binary Operator

    en using Result.bind as a binary operator: 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
  35. 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
  36. 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
  37. 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. OCaml's Standard Library also provides hash tables, another implementation of

    Data Structures
  38. 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
  39. 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
  40. Loops and Recursions

    Recursion Example: Maximum Element in a List

    the imperative for-loop solution, and (b) much more closely 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 imperative style, and therefore better and easier. Whe

    Introduction
  41. 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
  42. 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
  43. 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
  44. 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
  45. Monads

  46. 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
  47. A Tour of OCaml

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