352 search results for "function"
-
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
Options
Access the Content of an Option
In the standard library, these functions are Option.get and Option.value . However, i [...] on without the risk of raising an exception, the function value of type 'a option -> 'a -> 'a can be used: The
Data Structures -
Options
Bind an Option
Observe that the types are the same, except for the codomain of the function parameter. Here, we display the type of Optio [...] ible implementation of Option.bind . The bind function of type 'a option -> ('a -> 'b option) -> 'b option works a bit like map . But whilst map expe
Data Structures -
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 -
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 -
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 -
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 -
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 -
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