364 search results for "function"
-
Basic Data Types and Pattern Matching
Revisiting Predefined Types
In the end, the only type construction that does not reduce to a variant is the function arrow type. Pattern matching allows the inspection of values of any type, except functions. Even integers and floats can be seen as enumerated-like variant types, with many constructors an
Introduction -
Basic Data Types and Pattern Matching
User-Defined Polymorphic Types
ors. Here are the terms applicable to data types: In the OCaml community, as well as in the larger functional programming community, the word polymorphism [...] ssary to distinguish them. Here is how the map function can be defined in this type: It can be used to represent arbitrarily labelled binary trees. Assu
Introduction -
Monads
The Monad Signature
its second argument to the first. That requires taking the 'a value out of its box, applying the function to it, and returning the result. a boxed value, which has type 'a t , and a function that itself takes an unboxed value of type 'a as input and returns a boxed value of type '
Data Structures -
Lists
Association Lists
e able to make a list of pairs from a pair of lists and vice versa. The List module provides the functions split and combine for this purpose: Ass [...] library's Map or Hashtbl modules. But these functions from the List module are useful for lists which are generally small, and have other advantages
Introduction -
Options
Exceptions vs Options
dling for a longer discussion on error handling using options, exceptions, and other means. The function Sys.getenv : string -> string from the OCaml st [...] e variable is not defined. On the other hand, the function Sys.getenv_opt : string -> string option does the same, except it returns None if the variable
Data Structures -
Options
Peel Off Doubly Wrapped Options
itional examples demonstrating how Option.join works in different scenarios: Our custom join function is the same a the standard library's Option.join [...] in multiple options. Lets define a custom join function of type 'a option option -> 'a option that peels off one layer from a doubly wrapped option:
Data Structures -
Options
Conclusion
safe way to represent values that may be absent, avoiding the pitfalls of exceptions. By leveraging functions such as map , join , get , value , fold , a [...] red and expressive manner. These utilities enable functional-style programming while maintaining safety and composability. The Option module in the standard
Data Structures -
Hash Tables
Introduction
A hash table data structure achieves efficient reads and writes by employing a hashing function that converts the key of a key/value pair into an [...] " known as a hash. OCaml has a built-in hashing function within the Hashtabl module that is available for each key The Hashtbl module implements an ef
Data Structures -
Labelled and Optional Arguments
Forwarding an Optional Argument
?len is sufficient to forward without unwrapping. In the definitions of take and rtake , the function sub is called with optional arguments passed wi [...] ithout unwrapping. These examples reuse the sub function defined in the Optional Arguments Without Default Values section.
Introduction -
Sets
Introduction
StringSet , OCaml's toplevel displays the module's signature. Since it contains a large number of functions, the output copied here is shortened for brevity [...] e elements instead of to_list , which is a new function in OCaml 5.1, or upgrade OCaml by running opam update , then opam upgrade ocaml . Check your curr
Data Structures -
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 -
The Compiler Frontend: Parsing and Type Checking
Which Comes First: The ml or the mli?
ode by starting with an ml file and using the type inference to guide you as you build up your functions. The mli file can then be generated as described, and the exported functions documented.
Runtime & Compiler -
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 -
Sequences
Be Aware of Seq.Cons vs Seq.cons
n that both are capable of creating a new sequence: From the signature, we gather that it is a function that takes two parameters, a value and a sequen [...] wing: The other version of "cons-ing" is the function Seq.cons (with a lowercase c ) with the following value declaration: We have already been int
Data Structures -
Loops and Recursions
For Loops and While Loops
with for loops, the language doesn't provide a way to break out of a while loop, except by throwing an exception, so this means that while loops have fairly limited use. Again, remember that functional programmers like recursion, so while loops are second-class citizens in OCaml. <!-- $MDX skip --> While loops in OCaml are written: Functional programmers tend to use recursion instead
Introduction -
Loops and Recursions
Looping Over Strings
String.copy copies a string, like strdup . There is also a String.iter function which works like List.iter , except over the cha [...] e also contains dozens of useful string-related functions, and some of them are concerned with looping over strings.
Introduction -
Modules
Module Inclusion
es a module Extlib.List that has everything the standard List module has, plus a new uncons function. In order to override the default List module [...] ib at the beginning. Let's say we feel that a function is missing from the List module, but we really want it as if it were part of it. In an extlib.
Module System -
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 -
First-Class Modules
Introduction
: Modules , Functors . First-class modules let you treat modules as values. You can pass them to functions, return them from functions, and store them in data structures. This provides an alternative to functors for some use cases an
Module System -
Operators
Goals
Using operators as functions and reciprocally, using functions as operators Assign the right associativity and precedence to a custom operator Use and define cus
Advanced Topics -
Operators
Unary Operators
Unary operators are also called prefix operators. In some contexts, it can make sense to shorten a function's name into a symbol. This is often used as a way to shorten the name of a function that performs some sort of conversion over its argument.
Advanced Topics -
Operators
Operator Associativity and Precedence
at the left, therefore &^ associates to the left Although both expressions are calling the same function ( par ), they are evaluated in different orders. [...] ator associativity with an example. The following function concatenates its string arguments, surrounded by | characters and separated by a _ character.
Advanced Topics -
Arrays
Iterate on an Array
can also be made using for loops. Here is the same example using a loop: Array.iter applies a function to each element of an array, one at a time. The given function must return unit , operating by side effect. To print all the elements of the array zeroes creat
Data Structures -
Arrays
Map an Array
The Array.map function creates a new array by applying a given function to each element of an array. For example, we can get an array containing the square of each number
Data Structures -
Arrays
Conclusion
of arrays in OCaml, including how to create and manipulate them, as well as some of the most useful functions and use cases. Please refer to the standard lib [...] ary documentation to browse the complete list of functions of the Array module.
Data Structures -
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 -
Preprocessors and PPXs
Attributes and Derivers
for the fields of a given record type. Example of derivers are: Derivers are great for generating functions that depend on the structure of a defined type [...] d a "deprecated" warning, or force/check that a function is inlined. The full list of attributes that the compiler uses is available in the manual .
Advanced Topics -
Preprocessors and PPXs
Why PPXs Are Especially Useful in OCaml
the type-checker on the produced value and the familiarity of writing HTML code. So any general function that depends on the type's structure must be [...] to_string : 'a -> string or print : 'a -> () function can exist in compiled binaries (in the toplevel, types are kept). Now that we know what a PPX is
Advanced Topics -
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 -
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 -
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 -
Values and Functions
Local Definitions
In both examples, d and e are local definitions. Arbitrary combinations of chaining or nesting are allowed. e is bound to 6 inside e * 5 d is bound to 30 inside d * 7 Here is how scopin
Introduction -
Values and Functions
Forms of Pattern Matching
In the following sections, we explore matching inside let bindings, which is a special case. In the next chapter on Basic Data Types and Pattern Matching , we examine pattern matching in general c
Introduction -
Values and Functions
Pattern Matching in Definitions
<!--the example illustrates tuples::--> When pattern matching only has one case, it can be used in name definitions and in let ... = and fun ... -> expressions. In that case, less or more than
Introduction -
Values and Functions
Pattern Matching on Records
We can pattern match on records: <!--Because records are implicitly single-constructor variants,-->
Introduction -
Values and Functions
Pattern Matching on unit
<!-- user-defined single constructor variant example --> Note : In order for compiled files to only evaluate an expression for its side effects, you must write them after let () = . Above, the pa
Introduction -
Values and Functions
Pattern Matching on User-Defined Types
This also works with user-defined types.
Introduction -
Values and Functions
Nested Pattern Matching on User-Defined Types
Notice that contact is now available at the top-level as a bound variable: Next, we demonstrate the two-phase approach for accessing email and phone . This brings contact into our top-lev
Introduction