369 search results for "function"
-
Mutability and Imperative Control Flow
Semicolon
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 -
Sequences
Constructing Sequences
tains a module for sequences called Seq . It contains Seq.int , which we implemented above. The function ints n looks as if building the infinite sequen [...] in_int . We can also construct sequences using functions. Here is how to build an infinite sequence of integers: Note: The second component of each Se
Data Structures -
Sequences
Sequences for Conversions
Similar functions are also provided for sets, maps, hash tables ( [...] , it is advised to expose to_seq and of_seq functions. Lists Arrays Strings Throughout the OCaml Standard Library, sequences are used as a bri
Data Structures -
Sequences
Miscellaneous Considerations
ps it would be enlightening to illustrate the use of Seq.unfold by re-implementing the already seen function primes? Perhaps in an exercise rather than in the [...] accumulator, and also the fact that the producer function loops until it finds a new prime to yield, because Seq.unfold does not allow the producer to “ski
Data Structures -
Arrays
Introduction
ch as: This tutorial aims to introduce the subject of arrays in OCaml and showcase the most useful functions and use cases. Despite these differences, many of the functions readily available on arrays are similar to the ones available for lists. Please refer to the List
Data Structures -
Arrays
Creating Arrays
Array.init generates an array of a given length by applying a function to each index of the array, starting at 0. The fo [...] array containing the first 5 even numbers using a function which doubles its argument: Alternatively, you can create an array using the Array.make
Data Structures -
Arrays
Copying Part of an Array into Another Array
tarting at index 1 into the last part of zeroes , starting at index 3 . We can also use this function to copy part of an array onto itself: This copie [...] hin the bounds of each array. The Array.blit function efficiently copies a contiguous part of an array into an array. Similar to the array.(x) <- y ope
Data Structures -
Labelled and Optional Arguments
Labelling Parameters
sing the same name as label and parameter. Here is how range is used: lo and hi inside the function's body, as usual first and last when calling the function; these are the labels. The parameters of range are named Here is how to name parameters in a
Introduction -
Labelled and Optional Arguments
Passing Labelled Arguments Using the Pipe Operator
Let's modify the range function previously defined by adding an additional parameter step . Declaring a function's unlabelled argument as the first one simplifies reading the
Introduction -
Lists
List Searching
elements for which the predicate is true, the second those for which it is false. The filter function again takes a predicate and tests it against ea [...] the list of all elements which test true: The function find returns the first element of a list matching a given predicate (a predicate is a testing
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 -
Understanding the Garbage Collector
Attaching Finalizer Functions to Values
<div class="note"> OCaml's automatic memory management guarantees that a value will eventually be freed when it's no longer in use, either via the GC sweeping it or the program terminating. It'
Runtime & Compiler -
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. Note : The concept of a Map in this tutorial refers to a data structure that
Data Structures -
Maps
Finding Entries in a Map
ote that find_first_opt and find_last_opt return the key-value pair, not just the value. The functions find_first and find_last behave similarly, e [...] d find_last_opt if we want to use a predicate function: find_opt returns None find throws the Not_found exception When the searched key is absent fr
Data Structures -
Maps
Changing the Value Associated With a Key
You should experiment with different update functions; several behaviors are possible. To change a key's associated value, use the update function. It takes a key, a map, and an update
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 -
Sets
Sets With Custom Comparators
e Insensitive String Set"). We can accomplish this by passing an ad-hoc module to the Set.Make function: Let's say we want to create a set of strings th [...] et module we created uses the built-in compare function provided by the String module. The Set.Make functor expects a module with two definitions: a t
Data Structures -
Error Handling
Predefined Exceptions
reexisting exceptions Raise custom exceptions When implementing a software component which exposes functions raising exceptions, a design decision must be [...] ones are intended to be raised by user-written functions: Although the last one doesn't look as an exception, it actually is. The standard library pr
Guides -
Error Handling
Printing
own exceptions: To print an exception, the module Printexc comes in handy. For instance, the function notify_user : (unit -> 'a) -> 'a below calls a function, and if it fails, prints the exception on stderr . If stack traces are enabled, this
Guides -
Error Handling
Throwing Exceptions From option or result
ons, pattern matching and raise must be used. From option to Invalid_argument exception, use function Option.get : From result to Invalid_argument exception, use functions Result.get_ok and Result.get_error : This is done by using the following
Guides -
Error Handling
Conversion Between option and result
From option to result , use function Option.to_result : From result to option , use function Result.to_option : This is done by using the following
Guides -
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 -
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 -
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 -
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 -
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 -
OCaml Programming Guidelines
How to Choose Between Classes and Modules
Use modules when the data structures are fixed and their functionality is equally fixed or it's enough to add new functions in the programs which use them. Use conventional data structures (in particular, variant type
Resources -
OCaml Programming Guidelines
Clarity of OCaml Code
r programming paradigms): imperative programming (based on the notion of state and assignment), functional programming (based on the notion of function,
Resources -
OCaml Programming Guidelines
Function application: same rules as for trigonometric functions
In mathematics you write sin x to mean sin (x) . In the same way sin x + cos x means (sin x) + (cos x) not sin (x + (cos x)) . Use the same conventions in OCaml: write f x + g x to mean
Resources -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
The Compiler Backend: Bytecode and Native code
Where Did the Bytecode Instruction Set Come From?
laid the theoretical basis for the implementation of an instruction set for a strictly evaluated functional language such as OCaml. The bytecode interpre [...] different model since it uses CPU registers for function calls instead of always passing arguments on the stack, as the bytecode interpreter does. The by
Runtime & Compiler -
The Compiler Backend: Bytecode and Native code
Accessing Stdlib Modules from Within Core
g polymorphic and monomorphic comparison, you may have noticed that we prepended the comparison functions with Stdlib . This is because the Core module [...] always recover any of the OCaml standard library functions by accessing them through the Stdlib module, as we did in our benchmark.
Runtime & Compiler -
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 -
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 -
Functors
Introduction
his tutorial are available as a Git repo . As suggested by the name, a functor is almost like a function. However, while the inputs and outputs of functions are values, functors are between modules. A functor has a module as a parameter and returns a modu
Module System -
Functors
Dependency Injection
.Make(Int) . The module IterPrint is refactored into a functor that takes a module providing the function iter as a parameter. The with type 'a t := 'a [...] cy. At its compilation time, no implementation of function iter is available yet. iterPrint.ml Here is a refactoring of the module IterPrint to use dep
Module System -
Mutability and Imperative Control Flow
Byte Sequences
char array . The former should always be preferred, except when array is required by polymorphic functions handling arrays. updatable strings that can't b [...] ces can be created from string values using the function Bytes.of_string . Individual elements in the sequence can be updated or read by their index using
Introduction -
Mutability and Imperative Control Flow
Breaking Loops Using Exceptions
d. When the ASCII Escape character is read, the Exit exception is thrown, which terminates the iteration and displays the REPL reply: - : unit = () . The following example uses the get_char function we defined earlier (in the section Example: get_char Function ). Throwing the Exit exception is a recommended way to immediately exit from a loop.
Introduction -
Mutability and Imperative Control Flow
References Inside Closures
nt value. Similarly, calling c2 () will update its own independent counter. First, we define a function named create_counter that takes no arguments. I [...] sing !counter . In the following example, the function create_counter returns a closure that “hides” a mutable reference counter . This closure cap
Introduction -
Mutability and Imperative Control Flow
Bad: Side Effects Depending on Order of Evaluation
itialising record fields. Here, it is illustrated on a tuple value: Since the evaluation order for function arguments in OCaml is not explicitly defined, the [...] rintf "%s %s %s" is applied to the results. The function id_print returns its input unchanged. However, it has a side effect: it first prints the string i
Introduction -
Sequences
Consumers vs Producers
A function with a sequence parameter consumes it; it's a sequence consumer. A function with a sequence result produces it; it's a sequence producer. In both cases, consumption and produc
Data Structures -
Sequences
Producer Example: Seq.unfold
This application of Seq.unfold has type unit -> int Seq.node , making it a function, a deferred producer. Each time this function is called, a new element is produced.
Data Structures