379 search results for "function"
-
Error Handling
Exceptions
Here, we add a variant Foo to the type exn and create a function that will raise this exception. Now, how do we [...] e that, indeed, List.find or String.sub are functions that might fail by raising an exception. Historically, the first way of handling errors in OCaml
Guides -
Error Handling
Turning Exceptions into option or result
Some may like to turn this into a higher-order generic function: It would be same for result , except some data [...] or. The standard library does not provide such functions. This must be done using try ... with or match ... exception statements. For instance, here i
Guides -
Preprocessors and PPXs
Attributes and Derivers
for the fields of a given record type. Examples 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 -
Mutability and Imperative Control Flow
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
IntroductionMutability and Imperative Control Flow
Breaking Loops Using Exceptions
teration 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.
IntroductionMutability 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
IntroductionMutability 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
IntroductionMaps
Maps With Custom Key Types
Note that our module has a type t and also a compare function. Now we can call the Map.Make functor to get [...] A type t exposing the type of the map's key A function compare : t -> t -> int that compares t values If you need to create a map with a custom key t
Data StructuresModules
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 SystemOperators
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 TopicsOperators
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 TopicsOperators
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 TopicsFunctors
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 SystemFunctors
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 SystemLabelled 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 Defining Optional Parameters Without Default Values section.
IntroductionHash 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 Hashtbl module that is available for each key. The Hashtbl module implements an ef
Data StructuresSets
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 StructuresFirst-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 SystemOptions
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 StructuresOptions
Peel Off Doubly Wrapped Options
itional examples demonstrating how Option.join works in different scenarios: Our custom join function is the same as the standard library's Option.joi [...] in multiple options. Let's define a custom join function of type 'a option option -> 'a option that peels off one layer from a doubly wrapped option:
Data StructuresOptions
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 StructuresBasic Data Types and Pattern Matching
Byte Sequences
rray . Operations on bytes values are provided by the Stdlib and the Bytes modules. Only the function Bytes.get allows direct access to the character [...] bytes literally, so they must be produced by a function. <!--CR Moved intro pp to after example, as it contains the definition. Perhaps a short intro se
IntroductionBasic Data Types and Pattern Matching
Lists
ce with respect to lists: Operations on lists are provided by the List module. The List.append function concatenates two lists. It can be used as an oper [...] values they contain. Lists play a central role in functional programming, so they have a dedicated tutorial . As literals, lists are very much like arrays
IntroductionBasic Data Types and Pattern Matching
Tuples
t associative . In the standard library, both are defined using pattern matching. Here is how a function extracts the third element of the product of four types: The predefined function fst returns the first element of a pair, while snd returns the second element of a pair. This
IntroductionBasic Data Types and Pattern Matching
Recursive Variants
, which catches everything. It returns false on all data that is neither Array nor Object . Functions defined using pattern matching on recursive variants are often recursive too. This function checks if a name is present in a whole JSON tree: Both constructors Array and Object contain v
IntroductionBasic 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
IntroductionLoops and Recursions
For Loops and While Loops
owing an exception, so this means that while loops have fairly limited use. Again, remember that functional programmers like recursion, so while loops [...] DX skip --> While loops in OCaml are written: Functional programmers tend to use recursion instead of explicit loops, and it's wise to regard for loop
IntroductionLoops 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.
IntroductionSequences
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 StructuresSequences
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 StructuresSequences
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 StructuresArrays
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 StructuresArrays
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 StructuresArrays
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 StructuresThe 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 & CompilerLists
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
IntroductionMonads
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 StructuresThe 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 & CompilerThe 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 & CompilerMemory 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 & CompilerMemory 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 & CompilerA 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 StepsA 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 StepsA 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 StepsA 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 StepsA 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 StepsA Tour of OCaml
Conclusion
how to write OCaml files, how to compile them, and how to kickstart a project. <!-- 1. Values and Functions 1. Functions 1. Type-Inference -->
First StepsOCaml 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