369 search results for "function"
-
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 -
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 -
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 -
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 Defining Optional Parameters Without Default Values section.
Introduction -
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 -
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 Hashtbl module that is available for each key. The Hashtbl module implements an ef
Data Structures -
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 -
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 -
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 -
Maps
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 Structures -
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 -
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 -
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 -
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 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 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 -
Basic 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
Introduction -
Basic 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
Introduction -
Basic 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
Introduction -
Basic Data Types and Pattern Matching
Recursive Variants
bol _ , 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 values of type json . This is the case for the following definition, which can be used to store J
Introduction -
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 -
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 -
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 -
Debugging
Limitations
ugger for OCaml under Unix: ocamldebug . Its use is illustrated in the next section. Stepping a functional program has a meaning which is a bit weird to d [...] ts that happen when a parameter is passed to a function, when entering a pattern matching, or selecting a clause in a pattern matching. Computation pro
Guides -
Debugging
Finding the Cause of a Spurious Exception
pe ocamldebug a.out , then r , b , and bt gives you the backtrace. <!-- $MDX skip --> The function that calls it is in module Uncaught , file unca [...] ne 8, char 38: <!-- $MDX skip --> So the last function called is from module List on line 191, character 26, that is: But, as you know, you want the
Guides -
Common Error Messages
Warning: This optional argument cannot be erased
See the Labels section for more details on functions with labelled arguments. The solution is simply to add one argument of type unit, like this: Functions with optional arguments must have at least one non-labelled argument. For instance, thi
Resources -
OCaml Programming Guidelines
How to Comment Programs
Avoid comments in the bodies of functions. Prefer one comment at the beginning of the function that explains how a particular algorithm works. Once more, if there is no difficulty, there is no
Resources -
OCaml Programming Guidelines
Comments line by line in imperative code
physical mutations in data structures), it is sometimes mandatory to comment inside the body of functions to explain the algorithm's implementation encode [...] low successive invariant modifications that the function must maintain. Once more, if there is some difficulty commenting is mandatory, for each program l
Resources -
OCaml Programming Guidelines
Separate words by underscores: ( int_of_string , not intOfString )
pitalised words are reserved for constructors and module names. In contrast, regular variables (functions or identifiers) must start with a lowercase le [...] and it is forbidden to choose IntOfString as a function name.
Resources -
OCaml Programming Guidelines
Pattern-matching warnings
to the new constructor, if warranted. On the contrary, the “catch-all” clause will make the function compile silently, and it might be thought that the function is correct, as the new constructor will be handled by the default case. Those with useless clau
Resources -
OCaml Programming Guidelines
for loops
Justification : The recursive function lets you code any loop whatsoever simply, even [...] p is complex or returns a result, use a recursive function. <!-- $MDX skip --> To simply traverse an array or a string, use a for loop.
Resources -
OCaml Programming Guidelines
Data Structures
r, it is very difficult to limit the range of acceptable integers. One must define construction functions that will ensure the program's mandatory invaria [...] for type_of_definition , we will use a predicate function recursivep that returns true if the definition is recursive. Answer : This method is specific
Resources -
OCaml Programming Guidelines
Height of the Page
Justification : When a function goes beyond one screenful, it's time to divide [...] t readable and is difficult to keep correct. A function should always fit within one screenful (of about 70 lines), or in exceptional cases two, at the v
Resources -
OCaml Programming Guidelines
How to Indent Global let ... ;; Definitions
margin too quickly. <!-- $MDX skip --> The body is justified just under the name of the defined function. Justification : The vertical bars separating t [...] ular indentation of 1 or 2 spaces: The body of a function defined globally in a module is generally indented normally. However, it's okay to treat this cas
Resources -
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 -
Values and Functions
Discarding Values Using Pattern Matching
<!-- END Version Two --> Tuples behave differently from records; contained data is anonymous, and its position is used to access it. To discard the email value from the tuple of the contact fi
Introduction