code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
ocaml Module Str Module Str
==========
```
module Str: sig .. end
```
Regular expressions and high-level string processing
Regular expressions
-------------------
```
type regexp
```
The type of compiled regular expressions.
```
val regexp : string -> regexp
```
Compile a regular expression. The following constructs are recognized:
* `.` Matches any character except newline.
* `*` (postfix) Matches the preceding expression zero, one or several times
* `+` (postfix) Matches the preceding expression one or several times
* `?` (postfix) Matches the preceding expression once or not at all
* `[..]` Character set. Ranges are denoted with `-`, as in `[a-z]`. An initial `^`, as in `[^0-9]`, complements the set. To include a `]` character in a set, make it the first character of the set. To include a `-` character in a set, make it the first or the last character of the set.
* `^` Matches at beginning of line: either at the beginning of the matched string, or just after a '\n' character.
* `$` Matches at end of line: either at the end of the matched string, or just before a '\n' character.
* `\|` (infix) Alternative between two expressions.
* `\(..\)` Grouping and naming of the enclosed expression.
* `\1` The text matched by the first `\(...\)` expression (`\2` for the second expression, and so on up to `\9`).
* `\b` Matches word boundaries.
* `\` Quotes special characters. The special characters are `$^\.*+?[]`.
In regular expressions you will often use backslash characters; it's easier to use a quoted string literal `{|...|}` to avoid having to escape backslashes.
For example, the following expression:
```
let r = Str.regexp {|hello \([A-Za-z]+\)|} in
Str.replace_first r {|\1|} "hello world"
```
returns the string `"world"`.
If you want a regular expression that matches a literal backslash character, you need to double it: `Str.regexp {|\\|}`.
You can use regular string literals `"..."` too, however you will have to escape backslashes. The example above can be rewritten with a regular string literal as:
```
let r = Str.regexp "hello \\([A-Za-z]+\\)" in
Str.replace_first r "\\1" "hello world"
```
And the regular expression for matching a backslash becomes a quadruple backslash: `Str.regexp "\\\\"`.
```
val regexp_case_fold : string -> regexp
```
Same as `regexp`, but the compiled expression will match text in a case-insensitive way: uppercase and lowercase letters will be considered equivalent.
```
val quote : string -> string
```
`Str.quote s` returns a regexp string that matches exactly `s` and nothing else.
```
val regexp_string : string -> regexp
```
`Str.regexp_string s` returns a regular expression that matches exactly `s` and nothing else.
```
val regexp_string_case_fold : string -> regexp
```
`Str.regexp_string_case_fold` is similar to [`Str.regexp_string`](str#VALregexp_string), but the regexp matches in a case-insensitive way.
String matching and searching
-----------------------------
```
val string_match : regexp -> string -> int -> bool
```
`string_match r s start` tests whether a substring of `s` that starts at position `start` matches the regular expression `r`. The first character of a string has position `0`, as usual.
```
val search_forward : regexp -> string -> int -> int
```
`search_forward r s start` searches the string `s` for a substring matching the regular expression `r`. The search starts at position `start` and proceeds towards the end of the string. Return the position of the first character of the matched substring.
* **Raises** `Not_found` if no substring matches.
```
val search_backward : regexp -> string -> int -> int
```
`search_backward r s last` searches the string `s` for a substring matching the regular expression `r`. The search first considers substrings that start at position `last` and proceeds towards the beginning of string. Return the position of the first character of the matched substring.
* **Raises** `Not_found` if no substring matches.
```
val string_partial_match : regexp -> string -> int -> bool
```
Similar to [`Str.string_match`](str#VALstring_match), but also returns true if the argument string is a prefix of a string that matches. This includes the case of a true complete match.
```
val matched_string : string -> string
```
`matched_string s` returns the substring of `s` that was matched by the last call to one of the following matching or searching functions:
* [`Str.string_match`](str#VALstring_match)
* [`Str.search_forward`](str#VALsearch_forward)
* [`Str.search_backward`](str#VALsearch_backward)
* [`Str.string_partial_match`](str#VALstring_partial_match)
* [`Str.global_substitute`](str#VALglobal_substitute)
* [`Str.substitute_first`](str#VALsubstitute_first)
provided that none of the following functions was called in between:
* [`Str.global_replace`](str#VALglobal_replace)
* [`Str.replace_first`](str#VALreplace_first)
* [`Str.split`](str#VALsplit)
* [`Str.bounded_split`](str#VALbounded_split)
* [`Str.split_delim`](str#VALsplit_delim)
* [`Str.bounded_split_delim`](str#VALbounded_split_delim)
* [`Str.full_split`](str#VALfull_split)
* [`Str.bounded_full_split`](str#VALbounded_full_split)
Note: in the case of `global_substitute` and `substitute_first`, a call to `matched_string` is only valid within the `subst` argument, not after `global_substitute` or `substitute_first` returns.
The user must make sure that the parameter `s` is the same string that was passed to the matching or searching function.
```
val match_beginning : unit -> int
```
`match_beginning()` returns the position of the first character of the substring that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details).
```
val match_end : unit -> int
```
`match_end()` returns the position of the character following the last character of the substring that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details).
```
val matched_group : int -> string -> string
```
`matched_group n s` returns the substring of `s` that was matched by the `n`th group `\(...\)` of the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). When `n` is `0`, it returns the substring matched by the whole regular expression. The user must make sure that the parameter `s` is the same string that was passed to the matching or searching function.
* **Raises** `Not_found` if the `n`th group of the regular expression was not matched. This can happen with groups inside alternatives `\|`, options `?` or repetitions `*`. For instance, the empty string will match `\(a\)*`, but `matched_group 1 ""` will raise `Not\_found` because the first group itself was not matched.
```
val group_beginning : int -> int
```
`group_beginning n` returns the position of the first character of the substring that was matched by the `n`th group of the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details).
* **Raises**
+ `Not_found` if the `n`th group of the regular expression was not matched.
+ `Invalid_argument` if there are fewer than `n` groups in the regular expression.
```
val group_end : int -> int
```
`group_end n` returns the position of the character following the last character of substring that was matched by the `n`th group of the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details).
* **Raises**
+ `Not_found` if the `n`th group of the regular expression was not matched.
+ `Invalid_argument` if there are fewer than `n` groups in the regular expression.
Replacement
-----------
```
val global_replace : regexp -> string -> string -> string
```
`global_replace regexp templ s` returns a string identical to `s`, except that all substrings of `s` that match `regexp` have been replaced by `templ`. The replacement template `templ` can contain `\1`, `\2`, etc; these sequences will be replaced by the text matched by the corresponding group in the regular expression. `\0` stands for the text matched by the whole regular expression.
```
val replace_first : regexp -> string -> string -> string
```
Same as [`Str.global_replace`](str#VALglobal_replace), except that only the first substring matching the regular expression is replaced.
```
val global_substitute : regexp -> (string -> string) -> string -> string
```
`global_substitute regexp subst s` returns a string identical to `s`, except that all substrings of `s` that match `regexp` have been replaced by the result of function `subst`. The function `subst` is called once for each matching substring, and receives `s` (the whole text) as argument.
```
val substitute_first : regexp -> (string -> string) -> string -> string
```
Same as [`Str.global_substitute`](str#VALglobal_substitute), except that only the first substring matching the regular expression is replaced.
```
val replace_matched : string -> string -> string
```
`replace_matched repl s` returns the replacement text `repl` in which `\1`, `\2`, etc. have been replaced by the text matched by the corresponding groups in the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). `s` must be the same string that was passed to the matching or searching function.
Splitting
---------
```
val split : regexp -> string -> string list
```
`split r s` splits `s` into substrings, taking as delimiters the substrings that match `r`, and returns the list of substrings. For instance, `split (regexp "[ \t]+") s` splits `s` into blank-separated words. An occurrence of the delimiter at the beginning or at the end of the string is ignored.
```
val bounded_split : regexp -> string -> int -> string list
```
Same as [`Str.split`](str#VALsplit), but splits into at most `n` substrings, where `n` is the extra integer parameter.
```
val split_delim : regexp -> string -> string list
```
Same as [`Str.split`](str#VALsplit) but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. For instance, `split_delim (regexp " ") " abc "` returns `[""; "abc"; ""]`, while `split` with the same arguments returns `["abc"]`.
```
val bounded_split_delim : regexp -> string -> int -> string list
```
Same as [`Str.bounded_split`](str#VALbounded_split), but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result.
```
type split_result =
```
| | |
| --- | --- |
| `|` | `Text of `string`` |
| `|` | `Delim of `string`` |
```
val full_split : regexp -> string -> split_result list
```
Same as [`Str.split_delim`](str#VALsplit_delim), but returns the delimiters as well as the substrings contained between delimiters. The former are tagged `Delim` in the result list; the latter are tagged `Text`. For instance, `full_split (regexp "[{}]") "{ab}"` returns `[Delim "{"; Text "ab"; Delim "}"]`.
```
val bounded_full_split : regexp -> string -> int -> split_result list
```
Same as [`Str.bounded_split_delim`](str#VALbounded_split_delim), but returns the delimiters as well as the substrings contained between delimiters. The former are tagged `Delim` in the result list; the latter are tagged `Text`.
Extracting substrings
---------------------
```
val string_before : string -> int -> string
```
`string_before s n` returns the substring of all characters of `s` that precede position `n` (excluding the character at position `n`).
```
val string_after : string -> int -> string
```
`string_after s n` returns the substring of all characters of `s` that follow position `n` (including the character at position `n`).
```
val first_chars : string -> int -> string
```
`first_chars s n` returns the first `n` characters of `s`. This is the same function as [`Str.string_before`](str#VALstring_before).
```
val last_chars : string -> int -> string
```
`last_chars s n` returns the last `n` characters of `s`.
ocaml Module BytesLabels Module BytesLabels
==================
```
module BytesLabels: sig .. end
```
Byte sequence operations.
A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing.
Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`.
Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`.
Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](string)), which are almost the same data structure, but cannot be modified in place.
Bytes are represented by the OCaml type `char`.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
* **Since** 4.02.0
```
val length : bytes -> int
```
Return the length (number of bytes) of the argument.
```
val get : bytes -> int -> char
```
`get s n` returns the byte at index `n` in argument `s`.
* **Raises** `Invalid_argument` if `n` is not a valid index in `s`.
```
val set : bytes -> int -> char -> unit
```
`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`.
* **Raises** `Invalid_argument` if `n` is not a valid index in `s`.
```
val create : int -> bytes
```
`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val make : int -> char -> bytes
```
`make n c` returns a new byte sequence of length `n`, filled with the byte `c`.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val init : int -> f:(int -> char) -> bytes
```
`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order).
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val empty : bytes
```
A byte sequence of size 0.
```
val copy : bytes -> bytes
```
Return a new byte sequence that contains the same bytes as the argument.
```
val of_string : string -> bytes
```
Return a new byte sequence that contains the same bytes as the given string.
```
val to_string : bytes -> string
```
Return a new string that contains the same bytes as the given byte sequence.
```
val sub : bytes -> pos:int -> len:int -> bytes
```
`sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `s`.
```
val sub_string : bytes -> pos:int -> len:int -> string
```
Same as [`BytesLabels.sub`](byteslabels#VALsub) but return a string instead of a byte sequence.
```
val extend : bytes -> left:int -> right:int -> bytes
```
`extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if the result length is negative or longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val fill : bytes -> pos:int -> len:int -> char -> unit
```
`fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `s`.
```
val blit : src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from sequence `src`, starting at index `src_pos`, to sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
```
val blit_string : src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
```
val concat : sep:bytes -> bytes list -> bytes
```
`concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val cat : bytes -> bytes -> bytes
```
`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val iter : f:(char -> unit) -> bytes -> unit
```
`iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s
(length s - 1)); ()`.
```
val iteri : f:(int -> char -> unit) -> bytes -> unit
```
Same as [`BytesLabels.iter`](byteslabels#VALiter), but the function is applied to the index of the byte as first argument and the byte itself as second argument.
```
val map : f:(char -> char) -> bytes -> bytes
```
`map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
```
val mapi : f:(int -> char -> char) -> bytes -> bytes
```
`mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
```
val fold_left : f:('a -> char -> 'a) -> init:'a -> bytes -> 'a
```
`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`.
* **Since** 4.13.0
```
val fold_right : f:(char -> 'a -> 'a) -> bytes -> init:'a -> 'a
```
`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`.
* **Since** 4.13.0
```
val for_all : f:(char -> bool) -> bytes -> bool
```
`for_all p s` checks if all characters in `s` satisfy the predicate `p`.
* **Since** 4.13.0
```
val exists : f:(char -> bool) -> bytes -> bool
```
`exists p s` checks if at least one character of `s` satisfies the predicate `p`.
* **Since** 4.13.0
```
val trim : bytes -> bytes
```
Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`.
```
val escaped : bytes -> bytes
```
Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val index : bytes -> char -> int
```
`index s c` returns the index of the first occurrence of byte `c` in `s`.
* **Raises** `Not_found` if `c` does not occur in `s`.
```
val index_opt : bytes -> char -> int option
```
`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`.
* **Since** 4.05
```
val rindex : bytes -> char -> int
```
`rindex s c` returns the index of the last occurrence of byte `c` in `s`.
* **Raises** `Not_found` if `c` does not occur in `s`.
```
val rindex_opt : bytes -> char -> int option
```
`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`.
* **Since** 4.05
```
val index_from : bytes -> int -> char -> int
```
`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`.
* **Raises**
+ `Invalid_argument` if `i` is not a valid position in `s`.
+ `Not_found` if `c` does not occur in `s` after position `i`.
```
val index_from_opt : bytes -> int -> char -> int option
```
`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`.
* **Since** 4.05
* **Raises** `Invalid_argument` if `i` is not a valid position in `s`.
```
val rindex_from : bytes -> int -> char -> int
```
`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`.
* **Raises**
+ `Invalid_argument` if `i+1` is not a valid position in `s`.
+ `Not_found` if `c` does not occur in `s` before position `i+1`.
```
val rindex_from_opt : bytes -> int -> char -> int option
```
`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`.
* **Since** 4.05
* **Raises** `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val contains : bytes -> char -> bool
```
`contains s c` tests if byte `c` appears in `s`.
```
val contains_from : bytes -> int -> char -> bool
```
`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from
s 0 c`.
* **Raises** `Invalid_argument` if `start` is not a valid position in `s`.
```
val rcontains_from : bytes -> int -> char -> bool
```
`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`.
* **Raises** `Invalid_argument` if `stop < 0` or `stop+1` is not a valid position in `s`.
```
val uppercase_ascii : bytes -> bytes
```
Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val lowercase_ascii : bytes -> bytes
```
Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val capitalize_ascii : bytes -> bytes
```
Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val uncapitalize_ascii : bytes -> bytes
```
Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
```
type t = bytes
```
An alias for the type of byte sequences.
```
val compare : t -> t -> int
```
The comparison function for byte sequences, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val equal : t -> t -> bool
```
The equality function for byte sequences.
* **Since** 4.05.0
```
val starts_with : prefix:bytes -> bytes -> bool
```
`starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`.
* **Since** 4.13.0
```
val ends_with : suffix:bytes -> bytes -> bool
```
`ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`.
* **Since** 4.13.0
Unsafe conversions (for advanced users)
---------------------------------------
This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings provided by the `-safe-string` option. They are available for expert library authors, but for most purposes you should use the always-correct [`BytesLabels.to_string`](byteslabels#VALto_string) and [`BytesLabels.of_string`](byteslabels#VALof_string) instead.
```
val unsafe_to_string : bytes -> string
```
Unsafely convert a byte sequence into a string.
To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including:
* Unique ownership: the data may be accessed and mutated
* Shared ownership: the data has several owners, that may only access it, not mutate it.
Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again.
`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` -- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string.
There are two valid use-cases that respect this ownership discipline:
1. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed.
```
let string_init len f : string =
let s = Bytes.create len in
for i = 0 to len - 1 do Bytes.set s i (f i) done;
Bytes.unsafe_to_string s
```
This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller.
Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future -- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely.
We have provided the [`String.init`](string#VALinit), [`String.map`](string#VALmap) and [`String.mapi`](string#VALmapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable.
2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended.
```
let bytes_length (s : bytes) =
String.length (Bytes.unsafe_to_string s)
```
In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](string#VALlength) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](string#VALlength) does not capture its argument -- it could escape by a side-channel such as a memoization combinator.
The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](string#VALlength) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership.
```
val unsafe_of_string : string -> bytes
```
Unsafely convert a shared string to a byte sequence that should not be mutated.
The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode.
In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned.
For example, string literals are implicitly shared by the compiler, so you never uniquely own them.
```
let incorrect = Bytes.unsafe_of_string "hello"
let s = Bytes.of_string "hello"
```
The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct.
Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` -- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`.
The only case we have reasonable confidence is safe is if the produced `bytes` is shared -- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](marshal#VALfrom_bytes)) and previously used the `string` type for this purpose.
```
val split_on_char : sep:char -> bytes -> bytes list
```
`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character.
The function's output is specified by the following invariants:
* The list is not empty.
* Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep)
(Bytes.split_on_char sep s) = s`).
* No byte sequence in the result contains the `sep` character.
* **Since** 4.13.0
Iterators
---------
```
val to_seq : t -> char Seq.t
```
Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
Iterate on the string, in increasing order, yielding indices along chars
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
Create a string from the generator
* **Since** 4.07
UTF codecs and validations
--------------------------
### UTF-8
```
val get_utf_8_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`.
```
val set_utf_8_uchar : t -> int -> Uchar.t -> int
```
`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_8 : t -> bool
```
`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data.
### UTF-16BE
```
val get_utf_16be_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`.
```
val set_utf_16be_uchar : t -> int -> Uchar.t -> int
```
`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_16be : t -> bool
```
`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data.
### UTF-16LE
```
val get_utf_16le_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`.
```
val set_utf_16le_uchar : t -> int -> Uchar.t -> int
```
`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_16le : t -> bool
```
`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data.
Binary encoding/decoding of integers
------------------------------------
The functions in this section binary encode and decode integers to and from byte sequences.
All following functions raise `Invalid\_argument` if the space needed at index `i` to decode or encode the integer is not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows:
* Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result.
* Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes.
```
val get_uint8 : bytes -> int -> int
```
`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int8 : bytes -> int -> int
```
`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_ne : bytes -> int -> int
```
`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_be : bytes -> int -> int
```
`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_le : bytes -> int -> int
```
`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_ne : bytes -> int -> int
```
`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_be : bytes -> int -> int
```
`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_le : bytes -> int -> int
```
`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_ne : bytes -> int -> int32
```
`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_be : bytes -> int -> int32
```
`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_le : bytes -> int -> int32
```
`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_ne : bytes -> int -> int64
```
`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_be : bytes -> int -> int64
```
`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_le : bytes -> int -> int64
```
`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val set_uint8 : bytes -> int -> int -> unit
```
`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int8 : bytes -> int -> int -> unit
```
`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_ne : bytes -> int -> int -> unit
```
`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_be : bytes -> int -> int -> unit
```
`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_le : bytes -> int -> int -> unit
```
`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_ne : bytes -> int -> int -> unit
```
`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_be : bytes -> int -> int -> unit
```
`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_le : bytes -> int -> int -> unit
```
`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_ne : bytes -> int -> int32 -> unit
```
`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_be : bytes -> int -> int32 -> unit
```
`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_le : bytes -> int -> int32 -> unit
```
`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_ne : bytes -> int -> int64 -> unit
```
`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_be : bytes -> int -> int64 -> unit
```
`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_le : bytes -> int -> int64 -> unit
```
`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
Byte sequences and concurrency safety
-------------------------------------
Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning.
For example, consider the following program:
```
let size = 100_000_000
let b = Bytes.make size ' '
let update b f () =
Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b
let d1 = Domain.spawn (update b (fun x -> x + 1))
let d2 = Domain.spawn (update b (fun x -> 2 * x + 1))
let () = Domain.join d1; Domain.join d2
```
the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values.
After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location.
### Mixed-size accesses
Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index
```
let b = Bytes.make 10 '\000'
let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' )
```
In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`.
| programming_docs |
ocaml Module In_channel Module In\_channel
==================
```
module In_channel: sig .. end
```
Input channels.
* **Since** 4.14.0
```
type t = in_channel
```
The type of input channel.
```
type open_flag = open_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `Open\_rdonly` | `(*` | open for reading. | `*)` |
| `|` | `Open\_wronly` | `(*` | open for writing. | `*)` |
| `|` | `Open\_append` | `(*` | open for appending: always write at end of file. | `*)` |
| `|` | `Open\_creat` | `(*` | create the file if it does not exist. | `*)` |
| `|` | `Open\_trunc` | `(*` | empty the file if it already exists. | `*)` |
| `|` | `Open\_excl` | `(*` | fail if Open\_creat and the file already exists. | `*)` |
| `|` | `Open\_binary` | `(*` | open in binary mode (no conversion). | `*)` |
| `|` | `Open\_text` | `(*` | open in text mode (may perform conversions). | `*)` |
| `|` | `Open\_nonblock` | `(*` | open in non-blocking mode. | `*)` |
Opening modes for [`In\_channel.open_gen`](in_channel#VALopen_gen).
```
val stdin : t
```
The standard input for the process.
```
val open_bin : string -> t
```
Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file.
```
val open_text : string -> t
```
Same as [`In\_channel.open_bin`](in_channel#VALopen_bin), but the file is opened in text mode, so that newline translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`In\_channel.open_bin`](in_channel#VALopen_bin).
```
val open_gen : open_flag list -> int -> string -> t
```
`open_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`In\_channel.open_text`](in_channel#VALopen_text) and [`In\_channel.open_bin`](in_channel#VALopen_bin) are special cases of this function.
```
val with_open_bin : string -> (t -> 'a) -> 'a
```
`with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f
ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed.
```
val with_open_text : string -> (t -> 'a) -> 'a
```
Like [`In\_channel.with_open_bin`](in_channel#VALwith_open_bin), but the channel is opened in text mode (see [`In\_channel.open_text`](in_channel#VALopen_text)).
```
val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a
```
Like [`In\_channel.with_open_bin`](in_channel#VALwith_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`In\_channel.open_gen`](in_channel#VALopen_gen)).
```
val seek : t -> int64 -> unit
```
`seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified.
```
val pos : t -> int64
```
Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`In\_channel.pos`](in_channel#VALpos), then going back to this position using [`In\_channel.seek`](in_channel#VALseek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
```
val length : t -> int64
```
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode.
```
val close : t -> unit
```
Close the given channel. Input functions raise a `Sys\_error` exception when they are applied to a closed input channel, except [`In\_channel.close`](in_channel#VALclose), which does nothing when applied to an already closed channel.
```
val close_noerr : t -> unit
```
Same as [`In\_channel.close`](in_channel#VALclose), but ignore all errors.
```
val input_char : t -> char option
```
Read one character from the given input channel. Returns `None` if there are no more characters to read.
```
val input_byte : t -> int option
```
Same as [`In\_channel.input_char`](in_channel#VALinput_char), but return the 8-bit integer representing the character. Returns `None` if the end of file was reached.
```
val input_line : t -> string option
```
`input_line ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty.
A newline is the character `\n` unless the file is open in text mode and [`Sys.win32`](sys#VALwin32) is `true` in which case it is the sequence of characters `\r\n`.
```
val input : t -> bytes -> int -> int -> int
```
`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached.
Use [`In\_channel.really_input`](in_channel#VALreally_input) to read exactly `len` characters.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
```
val really_input : t -> bytes -> int -> int -> unit option
```
`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`.
Returns `None` if the end of file is reached before `len` characters have been read.
If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
```
val really_input_string : t -> int -> string option
```
`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read.
If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input.
```
val input_all : t -> string
```
`input_all ic` reads all remaining data from `ic`.
If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input.
```
val set_binary_mode : t -> bool -> unit
```
`set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input.
`set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`.
This function has no effect under operating systems that do not distinguish between text mode and binary mode.
ocaml Module Ephemeron.K2.Bucket Module Ephemeron.K2.Bucket
==========================
```
module Bucket: sig .. end
```
```
type ('k1, 'k2, 'd) t
```
A bucket is a mutable "list" of ephemerons.
```
val make : unit -> ('k1, 'k2, 'd) t
```
Create a new bucket.
```
val add : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd -> unit
```
Add an ephemeron to the bucket.
```
val remove : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> unit
```
`remove b k1 k2` removes from `b` the most-recently added ephemeron with keys `k1` and `k2`, or does nothing if there is no such ephemeron.
```
val find : ('k1, 'k2, 'd) t -> 'k1 -> 'k2 -> 'd option
```
Returns the data of the most-recently added ephemeron with the given keys, or `None` if there is no such ephemeron.
```
val length : ('k1, 'k2, 'd) t -> int
```
Returns an upper bound on the length of the bucket.
```
val clear : ('k1, 'k2, 'd) t -> unit
```
Remove all ephemerons from the bucket.
ocaml Module CamlinternalMod Module CamlinternalMod
======================
```
module CamlinternalMod: sig .. end
```
Run-time support for recursive modules. All functions in this module are for system use only, not for the casual user.
```
type shape =
```
| | |
| --- | --- |
| `|` | `Function` |
| `|` | `Lazy` |
| `|` | `Class` |
| `|` | `Module of `[shape](camlinternalmod#TYPEshape) array`` |
| `|` | `Value of `[Obj.t](obj#TYPEt)`` |
```
val init_mod : string * int * int -> shape -> Obj.t
```
```
val update_mod : shape -> Obj.t -> Obj.t -> unit
```
ocaml Module Parsing Module Parsing
==============
```
module Parsing: sig .. end
```
The run-time library for parsers generated by `ocamlyacc`.
```
val symbol_start : unit -> int
```
`symbol_start` and [`Parsing.symbol_end`](parsing#VALsymbol_end) are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: `symbol_start()` returns the offset of the first character; `symbol_end()` returns the offset after the last character. The first character in a file is at offset 0.
```
val symbol_end : unit -> int
```
See [`Parsing.symbol_start`](parsing#VALsymbol_start).
```
val rhs_start : int -> int
```
Same as [`Parsing.symbol_start`](parsing#VALsymbol_start) and [`Parsing.symbol_end`](parsing#VALsymbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. `n` is 1 for the leftmost item.
```
val rhs_end : int -> int
```
See [`Parsing.rhs_start`](parsing#VALrhs_start).
```
val symbol_start_pos : unit -> Lexing.position
```
Same as `symbol_start`, but return a `position` instead of an offset.
```
val symbol_end_pos : unit -> Lexing.position
```
Same as `symbol_end`, but return a `position` instead of an offset.
```
val rhs_start_pos : int -> Lexing.position
```
Same as `rhs_start`, but return a `position` instead of an offset.
```
val rhs_end_pos : int -> Lexing.position
```
Same as `rhs_end`, but return a `position` instead of an offset.
```
val clear_parser : unit -> unit
```
Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs.
```
exception Parse_error
```
Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery.
```
val set_trace : bool -> bool
```
Control debugging support for `ocamlyacc`-generated parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag.
* **Since** 3.11.0
ocaml Module type MoreLabels.Set.S Module type MoreLabels.Set.S
============================
```
module type S = sig .. end
```
Output signature of the functor [`MoreLabels.Set.Make`](morelabels.set.make).
```
type elt
```
The type of the set elements.
```
type t
```
The type of sets.
```
val empty : t
```
The empty set.
```
val is_empty : t -> bool
```
Test whether a set is empty or not.
```
val mem : elt -> t -> bool
```
`mem x s` tests whether `x` belongs to the set `s`.
```
val add : elt -> t -> t
```
`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val singleton : elt -> t
```
`singleton x` returns the one-element set containing only `x`.
```
val remove : elt -> t -> t
```
`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val union : t -> t -> t
```
Set union.
```
val inter : t -> t -> t
```
Set intersection.
```
val disjoint : t -> t -> bool
```
Test if two sets are disjoint.
* **Since** 4.08.0
```
val diff : t -> t -> t
```
Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`.
```
val compare : t -> t -> int
```
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
```
val equal : t -> t -> bool
```
`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements.
```
val subset : t -> t -> bool
```
`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`.
```
val iter : f:(elt -> unit) -> t -> unit
```
`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements.
```
val map : f:(elt -> elt) -> t -> t
```
`map ~f s` is the set whose elements are `f a0`,`f a1`... `f
aN`, where `a0`,`a1`...`aN` are the elements of `s`.
The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements.
If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.)
* **Since** 4.04.0
```
val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
```
`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order.
```
val for_all : f:(elt -> bool) -> t -> bool
```
`for_all ~f s` checks if all elements of the set satisfy the predicate `f`.
```
val exists : f:(elt -> bool) -> t -> bool
```
`exists ~f s` checks if at least one element of the set satisfies the predicate `f`.
```
val filter : f:(elt -> bool) -> t -> t
```
`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val filter_map : f:(elt -> elt option) -> t -> t
```
`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`.
For example,
```
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
```
is the set of halves of the even elements of `s`.
If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`.
* **Since** 4.11.0
```
val partition : f:(elt -> bool) -> t -> t * t
```
`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`.
```
val cardinal : t -> int
```
Return the number of elements of a set.
```
val elements : t -> elt list
```
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`MoreLabels.Set.Make`](morelabels.set.make).
```
val min_elt : t -> elt
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the set is empty.
```
val min_elt_opt : t -> elt option
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty.
* **Since** 4.05
```
val max_elt : t -> elt
```
Same as [`MoreLabels.Set.S.min_elt`](morelabels.set.s#VALmin_elt), but returns the largest element of the given set.
```
val max_elt_opt : t -> elt option
```
Same as [`MoreLabels.Set.S.min_elt_opt`](morelabels.set.s#VALmin_elt_opt), but returns the largest element of the given set.
* **Since** 4.05
```
val choose : t -> elt
```
Return one element of the given set, or raise `Not\_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
```
val choose_opt : t -> elt option
```
Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
* **Since** 4.05
```
val split : elt -> t -> t * bool * t
```
`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`.
```
val find : elt -> t -> elt
```
`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not\_found` if no such element exists.
* **Since** 4.01.0
```
val find_opt : elt -> t -> elt option
```
`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists.
* **Since** 4.05
```
val find_first : f:(elt -> bool) -> t -> elt
```
`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not\_found` if `x` is greater than any element of `s`.
* **Since** 4.05
```
val find_first_opt : f:(elt -> bool) -> t -> elt option
```
`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val find_last : f:(elt -> bool) -> t -> elt
```
`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
* **Since** 4.05
```
val find_last_opt : f:(elt -> bool) -> t -> elt option
```
`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val of_list : elt list -> t
```
`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements.
* **Since** 4.02.0
Iterators
---------
```
val to_seq_from : elt -> t -> elt Seq.t
```
`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above.
* **Since** 4.07
```
val to_seq : t -> elt Seq.t
```
Iterate on the whole set, in ascending order
* **Since** 4.07
```
val to_rev_seq : t -> elt Seq.t
```
Iterate on the whole set, in descending order
* **Since** 4.12
```
val add_seq : elt Seq.t -> t -> t
```
Add the given elements to the set, in order.
* **Since** 4.07
```
val of_seq : elt Seq.t -> t
```
Build a set from the given bindings
* **Since** 4.07
| programming_docs |
ocaml Module Oo Module Oo
=========
```
module Oo: sig .. end
```
Operations on objects
```
val copy : (< .. > as 'a) -> 'a
```
`Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`.
* **Alert unsynchronized\_access.** Unsynchronized accesses to mutable objects are a programming error.
```
val id : < .. > -> int
```
Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures.
ocaml Module Ephemeron.Kn Module Ephemeron.Kn
===================
```
module Kn: sig .. end
```
Ephemerons with arbitrary number of keys of the same type.
```
type ('k, 'd) t
```
an ephemeron with an arbitrary number of keys of the same type
```
val make : 'k array -> 'd -> ('k, 'd) t
```
Same as [`Ephemeron.K1.make`](ephemeron.k1#VALmake)
```
val query : ('k, 'd) t -> 'k array -> 'd option
```
Same as [`Ephemeron.K1.query`](ephemeron.k1#VALquery)
```
module Make: functor (H : Hashtbl.HashedType) -> Ephemeron.S with type key = H.t array
```
Functor building an implementation of a weak hash table
```
module MakeSeeded: functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H.t array
```
Functor building an implementation of a weak hash table.
```
module Bucket: sig .. end
```
ocaml Module type Hashtbl.S Module type Hashtbl.S
=====================
```
module type S = sig .. end
```
The output signature of the functor [`Hashtbl.Make`](hashtbl.make).
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
* **Since** 4.00.0
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : (key -> 'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
* **Since** 4.00.0
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Functor Set.Make Functor Set.Make
================
```
module Make: functor (Ord : OrderedType) -> S with type elt = Ord.t
```
Functor building an implementation of the set structure given a totally ordered type.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `Ord` | : | `[OrderedType](set.orderedtype)` |
|
```
type elt
```
The type of the set elements.
```
type t
```
The type of sets.
```
val empty : t
```
The empty set.
```
val is_empty : t -> bool
```
Test whether a set is empty or not.
```
val mem : elt -> t -> bool
```
`mem x s` tests whether `x` belongs to the set `s`.
```
val add : elt -> t -> t
```
`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val singleton : elt -> t
```
`singleton x` returns the one-element set containing only `x`.
```
val remove : elt -> t -> t
```
`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val union : t -> t -> t
```
Set union.
```
val inter : t -> t -> t
```
Set intersection.
```
val disjoint : t -> t -> bool
```
Test if two sets are disjoint.
* **Since** 4.08.0
```
val diff : t -> t -> t
```
Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`.
```
val compare : t -> t -> int
```
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
```
val equal : t -> t -> bool
```
`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements.
```
val subset : t -> t -> bool
```
`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`.
```
val iter : (elt -> unit) -> t -> unit
```
`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements.
```
val map : (elt -> elt) -> t -> t
```
`map f s` is the set whose elements are `f a0`,`f a1`... `f
aN`, where `a0`,`a1`...`aN` are the elements of `s`.
The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements.
If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.)
* **Since** 4.04.0
```
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
```
`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order.
```
val for_all : (elt -> bool) -> t -> bool
```
`for_all f s` checks if all elements of the set satisfy the predicate `f`.
```
val exists : (elt -> bool) -> t -> bool
```
`exists f s` checks if at least one element of the set satisfies the predicate `f`.
```
val filter : (elt -> bool) -> t -> t
```
`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val filter_map : (elt -> elt option) -> t -> t
```
`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`.
For example,
```
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
```
is the set of halves of the even elements of `s`.
If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`.
* **Since** 4.11.0
```
val partition : (elt -> bool) -> t -> t * t
```
`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`.
```
val cardinal : t -> int
```
Return the number of elements of a set.
```
val elements : t -> elt list
```
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](set.make).
```
val min_elt : t -> elt
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the set is empty.
```
val min_elt_opt : t -> elt option
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty.
* **Since** 4.05
```
val max_elt : t -> elt
```
Same as [`Set.S.min_elt`](set.s#VALmin_elt), but returns the largest element of the given set.
```
val max_elt_opt : t -> elt option
```
Same as [`Set.S.min_elt_opt`](set.s#VALmin_elt_opt), but returns the largest element of the given set.
* **Since** 4.05
```
val choose : t -> elt
```
Return one element of the given set, or raise `Not\_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
```
val choose_opt : t -> elt option
```
Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
* **Since** 4.05
```
val split : elt -> t -> t * bool * t
```
`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`.
```
val find : elt -> t -> elt
```
`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not\_found` if no such element exists.
* **Since** 4.01.0
```
val find_opt : elt -> t -> elt option
```
`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists.
* **Since** 4.05
```
val find_first : (elt -> bool) -> t -> elt
```
`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not\_found` if `x` is greater than any element of `s`.
* **Since** 4.05
```
val find_first_opt : (elt -> bool) -> t -> elt option
```
`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val find_last : (elt -> bool) -> t -> elt
```
`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
* **Since** 4.05
```
val find_last_opt : (elt -> bool) -> t -> elt option
```
`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val of_list : elt list -> t
```
`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements.
* **Since** 4.02.0
Iterators
---------
```
val to_seq_from : elt -> t -> elt Seq.t
```
`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above.
* **Since** 4.07
```
val to_seq : t -> elt Seq.t
```
Iterate on the whole set, in ascending order
* **Since** 4.07
```
val to_rev_seq : t -> elt Seq.t
```
Iterate on the whole set, in descending order
* **Since** 4.12
```
val add_seq : elt Seq.t -> t -> t
```
Add the given elements to the set, in order.
* **Since** 4.07
```
val of_seq : elt Seq.t -> t
```
Build a set from the given bindings
* **Since** 4.07
ocaml Module ArrayLabels Module ArrayLabels
==================
```
module ArrayLabels: sig .. end
```
Array operations.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
```
type 'a t = 'a array
```
An alias for the type of arrays.
```
val length : 'a array -> int
```
Return the length (number of elements) of the given array.
```
val get : 'a array -> int -> 'a
```
`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val set : 'a array -> int -> 'a -> unit
```
`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `length a - 1`.
```
val make : int -> 'a -> 'a array
```
`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the value of `x` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.
```
val create_float : int -> float array
```
`create_float n` returns a fresh float array of length `n`, with uninitialized data.
* **Since** 4.03
```
val init : int -> f:(int -> 'a) -> 'a array
```
`init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied to the integers `0` to `n-1`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.
```
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
```
`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`.
* **Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than [`Sys.max_array_length`](sys#VALmax_array_length). If the value of `e` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.
```
val append : 'a array -> 'a array -> 'a array
```
`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`.
* **Raises** `Invalid_argument` if `length v1 + length v2 > Sys.max_array_length`.
```
val concat : 'a array list -> 'a array
```
Same as [`ArrayLabels.append`](arraylabels#VALappend), but concatenates a list of arrays.
```
val sub : 'a array -> pos:int -> len:int -> 'a array
```
`sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.
```
val copy : 'a array -> 'a array
```
`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`.
```
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
```
`fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.
```
val blit : src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.
```
val to_list : 'a array -> 'a list
```
`to_list a` returns the list of all the elements of `a`.
```
val of_list : 'a list -> 'a array
```
`of_list l` returns a fresh array containing the elements of `l`.
* **Raises** `Invalid_argument` if the length of `l` is greater than `Sys.max_array_length`.
Iterators
---------
```
val iter : f:('a -> unit) -> 'a array -> unit
```
`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`.
```
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
```
Same as [`ArrayLabels.iter`](arraylabels#VALiter), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val map : f:('a -> 'b) -> 'a array -> 'b array
```
`map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.
```
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
```
Same as [`ArrayLabels.map`](arraylabels#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
```
`fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`.
```
val fold_left_map : f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b array -> 'a * 'c array
```
`fold_left_map` is a combination of [`ArrayLabels.fold_left`](arraylabels#VALfold_left) and [`ArrayLabels.map`](arraylabels#VALmap) that threads an accumulator through calls to `f`.
* **Since** 4.13.0
```
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
```
`fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`.
Iterators on two arrays
-----------------------
```
val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit
```
`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`.
* **Since** 4.05.0
* **Raises** `Invalid_argument` if the arrays are not the same size.
```
val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
```
`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.
* **Since** 4.05.0
* **Raises** `Invalid_argument` if the arrays are not the same size.
Array scanning
--------------
```
val for_all : f:('a -> bool) -> 'a array -> bool
```
`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.
* **Since** 4.03.0
```
val exists : f:('a -> bool) -> 'a array -> bool
```
`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.
* **Since** 4.03.0
```
val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
```
Same as [`ArrayLabels.for_all`](arraylabels#VALfor_all), but for a two-argument predicate.
* **Since** 4.11.0
* **Raises** `Invalid_argument` if the two arrays have different lengths.
```
val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
```
Same as [`ArrayLabels.exists`](arraylabels#VALexists), but for a two-argument predicate.
* **Since** 4.11.0
* **Raises** `Invalid_argument` if the two arrays have different lengths.
```
val mem : 'a -> set:'a array -> bool
```
`mem a ~set` is true if and only if `a` is structurally equal to an element of `l` (i.e. there is an `x` in `l` such that `compare a x = 0`).
* **Since** 4.03.0
```
val memq : 'a -> set:'a array -> bool
```
Same as [`ArrayLabels.mem`](arraylabels#VALmem), but uses physical equality instead of structural equality to compare list elements.
* **Since** 4.03.0
```
val find_opt : f:('a -> bool) -> 'a array -> 'a option
```
`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`.
* **Since** 4.13.0
```
val find_map : f:('a -> 'b option) -> 'a array -> 'b option
```
`find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist.
* **Since** 4.13.0
Arrays of pairs
---------------
```
val split : ('a * 'b) array -> 'a array * 'b array
```
`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`.
* **Since** 4.13.0
```
val combine : 'a array -> 'b array -> ('a * 'b) array
```
`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid\_argument` if the two arrays have different lengths.
* **Since** 4.13.0
Sorting
-------
```
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
```
Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` :
* `cmp x y` > 0 if and only if `cmp y x` < 0
* if `cmp x y` >= 0 and `cmp y z` >= 0 then `cmp x z` >= 0
When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` :
* `cmp a.(i) a.(j)` >= 0 if and only if i >= j
```
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
```
Same as [`ArrayLabels.sort`](arraylabels#VALsort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`ArrayLabels.sort`](arraylabels#VALsort).
```
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
```
Same as [`ArrayLabels.sort`](arraylabels#VALsort) or [`ArrayLabels.stable_sort`](arraylabels#VALstable_sort), whichever is faster on typical input.
Arrays and Sequences
--------------------
```
val to_seq : 'a array -> 'a Seq.t
```
Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : 'a array -> (int * 'a) Seq.t
```
Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a array
```
Create an array from the generator
* **Since** 4.07
Arrays and concurrency safety
-----------------------------
Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
```
let size = 100_000_000
let a = ArrayLabels.make size 1
let d1 = Domain.spawn (fun () ->
ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a
)
let d2 = Domain.spawn (fun () ->
ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a
)
let () = Domain.join d1; Domain.join d2
```
After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays).
### Float arrays
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
```
let zeros = Array.make size 0.
let max_floats = Array.make size Float.max_float
let res = Array.copy zeros
let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```
the `res` array might contain values that are neither `0.` nor `max_float`.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
| programming_docs |
ocaml Functor MoreLabels.Hashtbl.MakeSeeded Functor MoreLabels.Hashtbl.MakeSeeded
=====================================
```
module MakeSeeded: functor (H : SeededHashedType) -> SeededS
with type key = H.t
and type 'a t = 'a Hashtbl.MakeSeeded(H).t
```
Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`MoreLabels.Hashtbl.randomize`](morelabels.hashtbl#VALrandomize)).
* **Since** 4.00.0
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[SeededHashedType](morelabels.hashtbl.seededhashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key:key -> data:'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key:key -> data:'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> MoreLabels.Hashtbl.statistics
```
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Module type Ephemeron.SeededS Module type Ephemeron.SeededS
=============================
```
module type SeededS = sig .. end
```
The output signature of the functors [`Ephemeron.K1.MakeSeeded`](ephemeron.k1.makeseeded) and [`Ephemeron.K2.MakeSeeded`](ephemeron.k2.makeseeded).
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module Bigarray.Genarray Module Bigarray.Genarray
========================
```
module Genarray: sig .. end
```
```
type ('a, 'b, 'c) t
```
The type `Genarray.t` is the type of Bigarrays with variable numbers of dimensions. Any number of dimensions between 0 and 16 is supported.
The three type parameters to `Genarray.t` identify the array element kind and layout, as follows:
* the first parameter, `'a`, is the OCaml type for accessing array elements (`float`, `int`, `int32`, `int64`, `nativeint`);
* the second parameter, `'b`, is the actual kind of array elements (`float32_elt`, `float64_elt`, `int8_signed_elt`, `int8_unsigned_elt`, etc);
* the third parameter, `'c`, identifies the array layout (`c_layout` or `fortran_layout`).
For instance, `(float, float32_elt, fortran_layout) Genarray.t` is the type of generic Bigarrays containing 32-bit floats in Fortran layout; reads and writes in this array use the OCaml type `float`.
```
val create : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int array -> ('a, 'b, 'c) t
```
`Genarray.create kind layout dimensions` returns a new Bigarray whose element kind is determined by the parameter `kind` (one of `float32`, `float64`, `int8_signed`, etc) and whose layout is determined by the parameter `layout` (one of `c_layout` or `fortran_layout`). The `dimensions` parameter is an array of integers that indicate the size of the Bigarray in each dimension. The length of `dimensions` determines the number of dimensions of the Bigarray.
For instance, `Genarray.create int32 c_layout [|4;6;8|]` returns a fresh Bigarray of 32-bit integers, in C layout, having three dimensions, the three dimensions being 4, 6 and 8 respectively.
Bigarrays returned by `Genarray.create` are not initialized: the initial values of array elements is unspecified.
`Genarray.create` raises `Invalid\_argument` if the number of dimensions is not in the range 0 to 16 inclusive, or if one of the dimensions is negative.
```
val init : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int array -> (int array -> 'a) -> ('a, 'b, 'c) t
```
`Genarray.init kind layout dimensions f` returns a new Bigarray `b` whose element kind is determined by the parameter `kind` (one of `float32`, `float64`, `int8_signed`, etc) and whose layout is determined by the parameter `layout` (one of `c_layout` or `fortran_layout`). The `dimensions` parameter is an array of integers that indicate the size of the Bigarray in each dimension. The length of `dimensions` determines the number of dimensions of the Bigarray.
Each element `Genarray.get b i` is initialized to the result of `f i`. In other words, `Genarray.init kind layout dimensions f` tabulates the results of `f` applied to the indices of a new Bigarray whose layout is described by `kind`, `layout` and `dimensions`. The index array `i` may be shared and mutated between calls to f.
For instance, `Genarray.init int c_layout [|2; 1; 3|]
(Array.fold_left (+) 0)` returns a fresh Bigarray of integers, in C layout, having three dimensions (2, 1, 3, respectively), with the element values 0, 1, 2, 1, 2, 3.
`Genarray.init` raises `Invalid\_argument` if the number of dimensions is not in the range 0 to 16 inclusive, or if one of the dimensions is negative.
* **Since** 4.12.0
```
val num_dims : ('a, 'b, 'c) t -> int
```
Return the number of dimensions of the given Bigarray.
```
val dims : ('a, 'b, 'c) t -> int array
```
`Genarray.dims a` returns all dimensions of the Bigarray `a`, as an array of integers of length `Genarray.num_dims a`.
```
val nth_dim : ('a, 'b, 'c) t -> int -> int
```
`Genarray.nth_dim a n` returns the `n`-th dimension of the Bigarray `a`. The first dimension corresponds to `n = 0`; the second dimension corresponds to `n = 1`; the last dimension, to `n = Genarray.num_dims a - 1`.
* **Raises** `Invalid_argument` if `n` is less than 0 or greater or equal than `Genarray.num_dims a`.
```
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```
Return the kind of the given Bigarray.
```
val layout : ('a, 'b, 'c) t -> 'c Bigarray.layout
```
Return the layout of the given Bigarray.
```
val change_layout : ('a, 'b, 'c) t -> 'd Bigarray.layout -> ('a, 'b, 'd) t
```
`Genarray.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). No copying of elements is involved: the new array and the original array share the same storage space. The dimensions are reversed, such that `get v [| a; b |]` in C layout becomes `get v [| b+1; a+1 |]` in Fortran layout.
* **Since** 4.04.0
```
val size_in_bytes : ('a, 'b, 'c) t -> int
```
`size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes).
* **Since** 4.03.0
```
val get : ('a, 'b, 'c) t -> int array -> 'a
```
Read an element of a generic Bigarray. `Genarray.get a [|i1; ...; iN|]` returns the element of `a` whose coordinates are `i1` in the first dimension, `i2` in the second dimension, ..., `iN` in the `N`-th dimension.
If `a` has C layout, the coordinates must be greater or equal than 0 and strictly less than the corresponding dimensions of `a`. If `a` has Fortran layout, the coordinates must be greater or equal than 1 and less or equal than the corresponding dimensions of `a`.
If `N > 3`, alternate syntax is provided: you can write `a.{i1, i2, ..., iN}` instead of `Genarray.get a [|i1; ...; iN|]`. (The syntax `a.{...}` with one, two or three coordinates is reserved for accessing one-, two- and three-dimensional arrays as described below.)
* **Raises** `Invalid_argument` if the array `a` does not have exactly `N` dimensions, or if the coordinates are outside the array bounds.
```
val set : ('a, 'b, 'c) t -> int array -> 'a -> unit
```
Assign an element of a generic Bigarray. `Genarray.set a [|i1; ...; iN|] v` stores the value `v` in the element of `a` whose coordinates are `i1` in the first dimension, `i2` in the second dimension, ..., `iN` in the `N`-th dimension.
The array `a` must have exactly `N` dimensions, and all coordinates must lie inside the array bounds, as described for `Genarray.get`; otherwise, `Invalid\_argument` is raised.
If `N > 3`, alternate syntax is provided: you can write `a.{i1, i2, ..., iN} <- v` instead of `Genarray.set a [|i1; ...; iN|] v`. (The syntax `a.{...} <- v` with one, two or three coordinates is reserved for updating one-, two- and three-dimensional arrays as described below.)
```
val sub_left : ('a, 'b, Bigarray.c_layout) t -> int -> int -> ('a, 'b, Bigarray.c_layout) t
```
Extract a sub-array of the given Bigarray by restricting the first (left-most) dimension. `Genarray.sub_left a ofs len` returns a Bigarray with the same number of dimensions as `a`, and the same dimensions as `a`, except the first dimension, which corresponds to the interval `[ofs ... ofs + len - 1]` of the first dimension of `a`. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates `[|i1; ...; iN|]` of the sub-array is identical to the element at coordinates `[|i1+ofs; ...; iN|]` of the original array `a`.
`Genarray.sub_left` applies only to Bigarrays in C layout.
* **Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid sub-array of `a`, that is, if `ofs < 0`, or `len < 0`, or `ofs + len > Genarray.nth_dim a 0`.
```
val sub_right : ('a, 'b, Bigarray.fortran_layout) t -> int -> int -> ('a, 'b, Bigarray.fortran_layout) t
```
Extract a sub-array of the given Bigarray by restricting the last (right-most) dimension. `Genarray.sub_right a ofs len` returns a Bigarray with the same number of dimensions as `a`, and the same dimensions as `a`, except the last dimension, which corresponds to the interval `[ofs ... ofs + len - 1]` of the last dimension of `a`. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates `[|i1; ...; iN|]` of the sub-array is identical to the element at coordinates `[|i1; ...; iN+ofs|]` of the original array `a`.
`Genarray.sub_right` applies only to Bigarrays in Fortran layout.
* **Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid sub-array of `a`, that is, if `ofs < 1`, or `len < 0`, or `ofs + len > Genarray.nth_dim a (Genarray.num_dims a - 1)`.
```
val slice_left : ('a, 'b, Bigarray.c_layout) t -> int array -> ('a, 'b, Bigarray.c_layout) t
```
Extract a sub-array of lower dimension from the given Bigarray by fixing one or several of the first (left-most) coordinates. `Genarray.slice_left a [|i1; ... ; iM|]` returns the 'slice' of `a` obtained by setting the first `M` coordinates to `i1`, ..., `iM`. If `a` has `N` dimensions, the slice has dimension `N - M`, and the element at coordinates `[|j1; ...; j(N-M)|]` in the slice is identical to the element at coordinates `[|i1; ...; iM; j1; ...; j(N-M)|]` in the original array `a`. No copying of elements is involved: the slice and the original array share the same storage space.
`Genarray.slice_left` applies only to Bigarrays in C layout.
* **Raises** `Invalid_argument` if `M >= N`, or if `[|i1; ... ; iM|]` is outside the bounds of `a`.
```
val slice_right : ('a, 'b, Bigarray.fortran_layout) t -> int array -> ('a, 'b, Bigarray.fortran_layout) t
```
Extract a sub-array of lower dimension from the given Bigarray by fixing one or several of the last (right-most) coordinates. `Genarray.slice_right a [|i1; ... ; iM|]` returns the 'slice' of `a` obtained by setting the last `M` coordinates to `i1`, ..., `iM`. If `a` has `N` dimensions, the slice has dimension `N - M`, and the element at coordinates `[|j1; ...; j(N-M)|]` in the slice is identical to the element at coordinates `[|j1; ...; j(N-M); i1; ...; iM|]` in the original array `a`. No copying of elements is involved: the slice and the original array share the same storage space.
`Genarray.slice_right` applies only to Bigarrays in Fortran layout.
* **Raises** `Invalid_argument` if `M >= N`, or if `[|i1; ... ; iM|]` is outside the bounds of `a`.
```
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```
Copy all elements of a Bigarray in another Bigarray. `Genarray.blit src dst` copies all elements of `src` into `dst`. Both arrays `src` and `dst` must have the same number of dimensions and equal dimensions. Copying a sub-array of `src` to a sub-array of `dst` can be achieved by applying `Genarray.blit` to sub-array or slices of `src` and `dst`.
```
val fill : ('a, 'b, 'c) t -> 'a -> unit
```
Set all elements of a Bigarray to a given value. `Genarray.fill a v` stores the value `v` in all elements of the Bigarray `a`. Setting only some elements of `a` to `v` can be achieved by applying `Genarray.fill` to a sub-array or a slice of `a`.
ocaml Module Effect.Shallow Module Effect.Shallow
=====================
```
module Shallow: sig .. end
```
```
type ('a, 'b) continuation
```
`('a,'b) continuation` is a delimited continuation that expects a `'a` value and returns a `'b` value.
```
val fiber : ('a -> 'b) -> ('a, 'b) continuation
```
`fiber f` constructs a continuation that runs the computation `f`.
```
type ('a, 'b) handler = {
```
| | |
| --- | --- |
| | `retc : `'a -> 'b`;` |
| | `exnc : `exn -> 'b`;` |
| | `effc : `'c. 'c [Effect.t](effect#TYPEt) -> (('c, 'a) [continuation](effect.shallow#TYPEcontinuation) -> 'b) option`;` |
`}` `('a,'b) handler` is a handler record with three fields -- `retc` is the value handler, `exnc` handles exceptions, and `effc` handles the effects performed by the computation enclosed by the handler.
```
val continue_with : ('c, 'a) continuation -> 'c -> ('a, 'b) handler -> 'b
```
`continue_with k v h` resumes the continuation `k` with value `v` with the handler `h`.
* **Raises** `Continuation_already_resumed` if the continuation has already been resumed.
```
val discontinue_with : ('c, 'a) continuation -> exn -> ('a, 'b) handler -> 'b
```
`discontinue_with k e h` resumes the continuation `k` by raising the exception `e` with the handler `h`.
* **Raises** `Continuation_already_resumed` if the continuation has already been resumed.
```
val discontinue_with_backtrace : ('a, 'b) continuation -> exn -> Printexc.raw_backtrace -> ('b, 'c) handler -> 'c
```
`discontinue_with k e bt h` resumes the continuation `k` by raising the exception `e` with the handler `h` using the raw backtrace `bt` as the origin of the exception.
* **Raises** `Continuation_already_resumed` if the continuation has already been resumed.
```
val get_callstack : ('a, 'b) continuation -> int -> Printexc.raw_backtrace
```
`get_callstack c n` returns a description of the top of the call stack on the continuation `c`, with at most `n` entries.
ocaml Module Int64 Module Int64
============
```
module Int64: sig .. end
```
64-bit integers.
This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo 264
Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic.
Literals for 64-bit integers are suffixed by L:
```
let zero: int64 = 0L
let one: int64 = 1L
let m_one: int64 = -1L
```
```
val zero : int64
```
The 64-bit integer 0.
```
val one : int64
```
The 64-bit integer 1.
```
val minus_one : int64
```
The 64-bit integer -1.
```
val neg : int64 -> int64
```
Unary negation.
```
val add : int64 -> int64 -> int64
```
Addition.
```
val sub : int64 -> int64 -> int64
```
Subtraction.
```
val mul : int64 -> int64 -> int64
```
Multiplication.
```
val div : int64 -> int64 -> int64
```
Integer division.
* **Raises** `Division_by_zero` if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for [`(/)`](stdlib#VAL(/)).
```
val unsigned_div : int64 -> int64 -> int64
```
Same as [`Int64.div`](int64#VALdiv), except that arguments and result are interpreted as *unsigned* 64-bit integers.
* **Since** 4.08.0
```
val rem : int64 -> int64 -> int64
```
Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division\_by\_zero`.
```
val unsigned_rem : int64 -> int64 -> int64
```
Same as [`Int64.rem`](int64#VALrem), except that arguments and result are interpreted as *unsigned* 64-bit integers.
* **Since** 4.08.0
```
val succ : int64 -> int64
```
Successor. `Int64.succ x` is `Int64.add x Int64.one`.
```
val pred : int64 -> int64
```
Predecessor. `Int64.pred x` is `Int64.sub x Int64.one`.
```
val abs : int64 -> int64
```
`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.
```
val max_int : int64
```
The greatest representable 64-bit integer, 263 - 1.
```
val min_int : int64
```
The smallest representable 64-bit integer, -263.
```
val logand : int64 -> int64 -> int64
```
Bitwise logical and.
```
val logor : int64 -> int64 -> int64
```
Bitwise logical or.
```
val logxor : int64 -> int64 -> int64
```
Bitwise logical exclusive or.
```
val lognot : int64 -> int64
```
Bitwise logical negation.
```
val shift_left : int64 -> int -> int64
```
`Int64.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 64`.
```
val shift_right : int64 -> int -> int64
```
`Int64.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 64`.
```
val shift_right_logical : int64 -> int -> int64
```
`Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 64`.
```
val of_int : int -> int64
```
Convert the given integer (type `int`) to a 64-bit integer (type `int64`).
```
val to_int : int64 -> int
```
Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo 263, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo 231, i.e. the top 33 bits are lost during the conversion.
```
val unsigned_to_int : int64 -> int option
```
Same as [`Int64.to_int`](int64#VALto_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`.
* **Since** 4.08.0
```
val of_float : float -> int64
```
Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range [[`Int64.min_int`](int64#VALmin_int), [`Int64.max_int`](int64#VALmax_int)], no exception is raised, and an unspecified, platform-dependent integer is returned.
```
val to_float : int64 -> float
```
Convert the given 64-bit integer to a floating-point number.
```
val of_int32 : int32 -> int64
```
Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`).
```
val to_int32 : int64 -> int32
```
Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo 232, i.e. the top 32 bits are lost during the conversion.
```
val of_nativeint : nativeint -> int64
```
Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`).
```
val to_nativeint : int64 -> nativeint
```
Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo 232. On 64-bit platforms, the conversion is exact.
```
val of_string : string -> int64
```
Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.
The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds [`Int64.max_int`](int64#VALmax_int) it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`.
The `_` (underscore) character can appear anywhere in the string and is ignored.
* **Raises** `Failure` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int64`.
```
val of_string_opt : string -> int64 option
```
Same as `of_string`, but return `None` instead of raising.
* **Since** 4.05
```
val to_string : int64 -> string
```
Return the string representation of its argument, in decimal.
```
val bits_of_float : float -> int64
```
Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa.
```
val float_of_bits : int64 -> float
```
Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`.
```
type t = int64
```
An alias for the type of 64-bit integers.
```
val compare : t -> t -> int
```
The comparison function for 64-bit integers, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val unsigned_compare : t -> t -> int
```
Same as [`Int64.compare`](int64#VALcompare), except that arguments are interpreted as *unsigned* 64-bit integers.
* **Since** 4.08.0
```
val equal : t -> t -> bool
```
The equal function for int64s.
* **Since** 4.03.0
```
val min : t -> t -> t
```
Return the smaller of the two arguments.
* **Since** 4.13.0
```
val max : t -> t -> t
```
Return the greater of the two arguments.
* **Since** 4.13.0
| programming_docs |
ocaml Module Obj.Closure Module Obj.Closure
==================
```
module Closure: sig .. end
```
```
type info = {
```
| | |
| --- | --- |
| | `arity : `int`;` |
| | `start\_env : `int`;` |
`}`
```
val info : Obj.t -> info
```
ocaml Module String Module String
=============
```
module String: sig .. end
```
Strings.
A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters.
The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows.
```
positions 0 1 2 3 4 n-1 n
+---+---+---+---+ +-----+
indices | 0 | 1 | 2 | 3 | ... | n-1 |
+---+---+---+---+ +-----+
```
* An *index* `i` of `s` is an integer in the range [`0`;`n-1`]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`.
* A *position* `i` of `s` is an integer in the range [`0`;`n`]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`.
Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`.
**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B.
**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](bytes#TYPEt) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
Strings
-------
```
type t = string
```
The type for strings.
```
val make : int -> char -> string
```
`make n c` is a string of length `n` with each index holding the character `c`.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val init : int -> (int -> char) -> string
```
`init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order).
* **Since** 4.02.0
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val empty : string
```
The empty string.
* **Since** 4.13.0
```
val of_bytes : bytes -> string
```
Return a new string that contains the same bytes as the given byte sequence.
* **Since** 4.13.0
```
val to_bytes : string -> bytes
```
Return a new byte sequence that contains the same bytes as the given string.
* **Since** 4.13.0
```
val length : string -> int
```
`length s` is the length (number of bytes/characters) of `s`.
```
val get : string -> int -> char
```
`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`.
* **Raises** `Invalid_argument` if `i` not an index of `s`.
Concatenating
-------------
**Note.** The [`(^)`](#) binary operator concatenates two strings.
```
val concat : string -> string list -> string
```
`concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val cat : string -> string -> string
```
`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`).
* **Since** 4.13.0
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
Predicates and comparisons
--------------------------
```
val equal : t -> t -> bool
```
`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal.
* **Since** 4.03.0 (4.05.0 in StringLabels)
```
val compare : t -> t -> int
```
`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`compare`](stdlib#VALcompare) on strings but may be more efficient.
```
val starts_with : prefix:string -> string -> bool
```
`starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`.
* **Since** 4.13.0
```
val ends_with : suffix:string -> string -> bool
```
`ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`.
* **Since** 4.13.0
```
val contains_from : string -> int -> char -> bool
```
`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`.
* **Raises** `Invalid_argument` if `start` is not a valid position in `s`.
```
val rcontains_from : string -> int -> char -> bool
```
`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`.
* **Raises** `Invalid_argument` if `stop < 0` or `stop+1` is not a valid position in `s`.
```
val contains : string -> char -> bool
```
`contains s c` is [`String.contains_from`](string#VALcontains_from)`s 0 c`.
Extracting substrings
---------------------
```
val sub : string -> int -> int -> string
```
`sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid substring of `s`.
```
val split_on_char : char -> string -> string list
```
`split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`.
The function's result is specified by the following invariants:
* The list is not empty.
* Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep)
(split_on_char sep s) = s`).
* No string in the result contains the `sep` character.
* **Since** 4.04.0 (4.05.0 in StringLabels)
Transforming
------------
```
val map : (char -> char) -> string -> string
```
`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order.
* **Since** 4.00.0
```
val mapi : (int -> char -> char) -> string -> string
```
`mapi f s` is like [`String.map`](string#VALmap) but the index of the character is also passed to `f`.
* **Since** 4.02.0
```
val fold_left : ('a -> char -> 'a) -> 'a -> string -> 'a
```
`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`.
* **Since** 4.13.0
```
val fold_right : (char -> 'a -> 'a) -> string -> 'a -> 'a
```
`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`.
* **Since** 4.13.0
```
val for_all : (char -> bool) -> string -> bool
```
`for_all p s` checks if all characters in `s` satisfy the predicate `p`.
* **Since** 4.13.0
```
val exists : (char -> bool) -> string -> bool
```
`exists p s` checks if at least one character of `s` satisfies the predicate `p`.
* **Since** 4.13.0
```
val trim : string -> string
```
`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`.
* **Since** 4.00.0
```
val escaped : string -> string
```
`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function [`Scanf.unescaped`](scanf#VALunescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails).
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val uppercase_ascii : string -> string
```
`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in StringLabels)
```
val lowercase_ascii : string -> string
```
`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in StringLabels)
```
val capitalize_ascii : string -> string
```
`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in StringLabels)
```
val uncapitalize_ascii : string -> string
```
`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set.
* **Since** 4.03.0 (4.05.0 in StringLabels)
Traversing
----------
```
val iter : (char -> unit) -> string -> unit
```
`iter f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`.
```
val iteri : (int -> char -> unit) -> string -> unit
```
`iteri` is like [`String.iter`](string#VALiter), but the function is also given the corresponding character index.
* **Since** 4.00.0
Searching
---------
```
val index_from : string -> int -> char -> int
```
`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`.
* **Raises**
+ `Not_found` if `c` does not occur in `s` after position `i`.
+ `Invalid_argument` if `i` is not a valid position in `s`.
```
val index_from_opt : string -> int -> char -> int option
```
`index_from_opt s i c` is the index of the first occurrence of `c` in `s` after position `i` (if any).
* **Since** 4.05
* **Raises** `Invalid_argument` if `i` is not a valid position in `s`.
```
val rindex_from : string -> int -> char -> int
```
`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`.
* **Raises**
+ `Not_found` if `c` does not occur in `s` before position `i+1`.
+ `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val rindex_from_opt : string -> int -> char -> int option
```
`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any).
* **Since** 4.05
* **Raises** `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val index : string -> char -> int
```
`index s c` is [`String.index_from`](string#VALindex_from)`s 0 c`.
```
val index_opt : string -> char -> int option
```
`index_opt s c` is [`String.index_from_opt`](string#VALindex_from_opt)`s 0 c`.
* **Since** 4.05
```
val rindex : string -> char -> int
```
`rindex s c` is [`String.rindex_from`](string#VALrindex_from)`s (length s - 1) c`.
```
val rindex_opt : string -> char -> int option
```
`rindex_opt s c` is [`String.rindex_from_opt`](string#VALrindex_from_opt)`s (length s - 1) c`.
* **Since** 4.05
Strings and Sequences
---------------------
```
val to_seq : t -> char Seq.t
```
`to_seq s` is a sequence made of the string's characters in increasing order. In `"unsafe-string"` mode, modifications of the string during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
`to_seqi s` is like [`String.to_seq`](string#VALto_seq) but also tuples the corresponding index.
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
`of_seq s` is a string made of the sequence's characters.
* **Since** 4.07
UTF decoding and validations
----------------------------
### UTF-8
```
val get_utf_8_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`.
```
val is_valid_utf_8 : t -> bool
```
`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data.
### UTF-16BE
```
val get_utf_16be_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`.
```
val is_valid_utf_16be : t -> bool
```
`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data.
### UTF-16LE
```
val get_utf_16le_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`.
```
val is_valid_utf_16le : t -> bool
```
`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data.
```
val blit : string -> int -> bytes -> int -> int -> unit
```
`blit src src_pos dst dst_pos len` copies `len` bytes from the string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at character number `dst_pos`.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
Binary decoding of integers
---------------------------
The functions in this section binary decode integers from strings.
All following functions raise `Invalid\_argument` if the characters needed at index `i` to decode the integer are not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values.
```
val get_uint8 : string -> int -> int
```
`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int8 : string -> int -> int
```
`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_ne : string -> int -> int
```
`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_be : string -> int -> int
```
`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_le : string -> int -> int
```
`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_ne : string -> int -> int
```
`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_be : string -> int -> int
```
`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_le : string -> int -> int
```
`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int32_ne : string -> int -> int32
```
`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val hash : t -> int
```
An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](hashtbl#VALhash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](hashtbl.make).
* **Since** 5.0.0
```
val seeded_hash : int -> t -> int
```
A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
* **Since** 5.0.0
```
val get_int32_be : string -> int -> int32
```
`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int32_le : string -> int -> int32
```
`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_ne : string -> int -> int64
```
`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_be : string -> int -> int64
```
`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_le : string -> int -> int64
```
`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
ocaml Module CamlinternalFormatBasics Module CamlinternalFormatBasics
===============================
```
module CamlinternalFormatBasics: sig .. end
```
```
type padty =
```
| | |
| --- | --- |
| `|` | `Left` |
| `|` | `Right` |
| `|` | `Zeros` |
```
type int_conv =
```
| | |
| --- | --- |
| `|` | `Int\_d` |
| `|` | `Int\_pd` |
| `|` | `Int\_sd` |
| `|` | `Int\_i` |
| `|` | `Int\_pi` |
| `|` | `Int\_si` |
| `|` | `Int\_x` |
| `|` | `Int\_Cx` |
| `|` | `Int\_X` |
| `|` | `Int\_CX` |
| `|` | `Int\_o` |
| `|` | `Int\_Co` |
| `|` | `Int\_u` |
| `|` | `Int\_Cd` |
| `|` | `Int\_Ci` |
| `|` | `Int\_Cu` |
```
type float_flag_conv =
```
| | |
| --- | --- |
| `|` | `Float\_flag\_` |
| `|` | `Float\_flag\_p` |
| `|` | `Float\_flag\_s` |
```
type float_kind_conv =
```
| | |
| --- | --- |
| `|` | `Float\_f` |
| `|` | `Float\_e` |
| `|` | `Float\_E` |
| `|` | `Float\_g` |
| `|` | `Float\_G` |
| `|` | `Float\_F` |
| `|` | `Float\_h` |
| `|` | `Float\_H` |
| `|` | `Float\_CF` |
```
type float_conv = float_flag_conv * float_kind_conv
```
```
type char_set = string
```
```
type counter =
```
| | |
| --- | --- |
| `|` | `Line\_counter` |
| `|` | `Char\_counter` |
| `|` | `Token\_counter` |
```
type ('a, 'b) padding =
```
| | |
| --- | --- |
| `|` | `No\_padding : `('a0, 'a0) [padding](camlinternalformatbasics#TYPEpadding)`` |
| `|` | `Lit\_padding : `[padty](camlinternalformatbasics#TYPEpadty) * int` -> `('a1, 'a1) [padding](camlinternalformatbasics#TYPEpadding)`` |
| `|` | `Arg\_padding : `[padty](camlinternalformatbasics#TYPEpadty)` -> `(int -> 'a2, 'a2) [padding](camlinternalformatbasics#TYPEpadding)`` |
```
type pad_option = int option
```
```
type ('a, 'b) precision =
```
| | |
| --- | --- |
| `|` | `No\_precision : `('a0, 'a0) [precision](camlinternalformatbasics#TYPEprecision)`` |
| `|` | `Lit\_precision : `int` -> `('a1, 'a1) [precision](camlinternalformatbasics#TYPEprecision)`` |
| `|` | `Arg\_precision : `(int -> 'a2, 'a2) [precision](camlinternalformatbasics#TYPEprecision)`` |
```
type prec_option = int option
```
```
type ('a, 'b, 'c) custom_arity =
```
| | |
| --- | --- |
| `|` | `Custom\_zero : `('a0, string, 'a0) [custom\_arity](camlinternalformatbasics#TYPEcustom_arity)`` |
| `|` | `Custom\_succ : `('a1, 'b0, 'c0) [custom\_arity](camlinternalformatbasics#TYPEcustom_arity)` -> `('a1, 'x -> 'b0, 'x -> 'c0) [custom\_arity](camlinternalformatbasics#TYPEcustom_arity)`` |
```
type block_type =
```
| | |
| --- | --- |
| `|` | `Pp\_hbox` |
| `|` | `Pp\_vbox` |
| `|` | `Pp\_hvbox` |
| `|` | `Pp\_hovbox` |
| `|` | `Pp\_box` |
| `|` | `Pp\_fits` |
```
type formatting_lit =
```
| | |
| --- | --- |
| `|` | `Close\_box` |
| `|` | `Close\_tag` |
| `|` | `Break of `string * int * int`` |
| `|` | `FFlush` |
| `|` | `Force\_newline` |
| `|` | `Flush\_newline` |
| `|` | `Magic\_size of `string * int`` |
| `|` | `Escaped\_at` |
| `|` | `Escaped\_percent` |
| `|` | `Scan\_indic of `char`` |
```
type ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen =
```
| | |
| --- | --- |
| `|` | `Open\_tag : `('a0, 'b0, 'c0, 'd0, 'e0, 'f0) [format6](camlinternalformatbasics#TYPEformat6)` -> `('a0, 'b0, 'c0, 'd0, 'e0, 'f0) [formatting\_gen](camlinternalformatbasics#TYPEformatting_gen)`` |
| `|` | `Open\_box : `('a1, 'b1, 'c1, 'd1, 'e1, 'f1) [format6](camlinternalformatbasics#TYPEformat6)` -> `('a1, 'b1, 'c1, 'd1, 'e1, 'f1) [formatting\_gen](camlinternalformatbasics#TYPEformatting_gen)`` |
```
type ('a, 'b, 'c, 'd, 'e, 'f) fmtty = ('a, 'b, 'c, 'd, 'e, 'f, 'a, 'b, 'c, 'd, 'e, 'f) fmtty_rel
```
```
type ('a1, 'b1, 'c1, 'd1, 'e1, 'f1, 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel =
```
| | |
| --- | --- |
| `|` | `Char\_ty : `('a10, 'b10, 'c10, 'd10, 'e10, 'f10, 'a20, 'b20, 'c20, 'd20, 'e20, 'f20) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(char -> 'a10, 'b10, 'c10, 'd10, 'e10, 'f10, char -> 'a20, 'b20, 'c20, 'd20, 'e20, 'f20) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `String\_ty : `('a11, 'b11, 'c11, 'd11, 'e11, 'f11, 'a21, 'b21, 'c21, 'd21, 'e21, 'f21) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(string -> 'a11, 'b11, 'c11, 'd11, 'e11, 'f11, string -> 'a21, 'b21, 'c21, 'd21, 'e21, 'f21) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Int\_ty : `('a12, 'b12, 'c12, 'd12, 'e12, 'f12, 'a22, 'b22, 'c22, 'd22, 'e22, 'f22) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(int -> 'a12, 'b12, 'c12, 'd12, 'e12, 'f12, int -> 'a22, 'b22, 'c22, 'd22, 'e22, 'f22) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Int32\_ty : `('a13, 'b13, 'c13, 'd13, 'e13, 'f13, 'a23, 'b23, 'c23, 'd23, 'e23, 'f23) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(int32 -> 'a13, 'b13, 'c13, 'd13, 'e13, 'f13, int32 -> 'a23, 'b23, 'c23, 'd23, 'e23, 'f23) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Nativeint\_ty : `('a14, 'b14, 'c14, 'd14, 'e14, 'f14, 'a24, 'b24, 'c24, 'd24, 'e24, 'f24) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(nativeint -> 'a14, 'b14, 'c14, 'd14, 'e14, 'f14, nativeint -> 'a24, 'b24, 'c24, 'd24, 'e24, 'f24) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Int64\_ty : `('a15, 'b15, 'c15, 'd15, 'e15, 'f15, 'a25, 'b25, 'c25, 'd25, 'e25, 'f25) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(int64 -> 'a15, 'b15, 'c15, 'd15, 'e15, 'f15, int64 -> 'a25, 'b25, 'c25, 'd25, 'e25, 'f25) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Float\_ty : `('a16, 'b16, 'c16, 'd16, 'e16, 'f16, 'a26, 'b26, 'c26, 'd26, 'e26, 'f26) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(float -> 'a16, 'b16, 'c16, 'd16, 'e16, 'f16, float -> 'a26, 'b26, 'c26, 'd26, 'e26, 'f26) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Bool\_ty : `('a17, 'b17, 'c17, 'd17, 'e17, 'f17, 'a27, 'b27, 'c27, 'd27, 'e27, 'f27) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(bool -> 'a17, 'b17, 'c17, 'd17, 'e17, 'f17, bool -> 'a27, 'b27, 'c27, 'd27, 'e27, 'f27) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Format\_arg\_ty : `('g, 'h, 'i, 'j, 'k, 'l) [fmtty](camlinternalformatbasics#TYPEfmtty) * ('a18, 'b18, 'c18, 'd18, 'e18, 'f18, 'a28, 'b28, 'c28, 'd28, 'e28, 'f28) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(('g, 'h, 'i, 'j, 'k, 'l) [format6](camlinternalformatbasics#TYPEformat6) -> 'a18, 'b18, 'c18, 'd18, 'e18, 'f18, ('g, 'h, 'i, 'j, 'k, 'l) [format6](camlinternalformatbasics#TYPEformat6) -> 'a28, 'b28, 'c28, 'd28, 'e28, 'f28) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Format\_subst\_ty : `('g0, 'h0, 'i0, 'j0, 'k0, 'l0, 'g1, 'b19, 'c19, 'j1, 'd19, 'a19) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel) * ('g0, 'h0, 'i0, 'j0, 'k0, 'l0, 'g2, 'b29, 'c29, 'j2, 'd29, 'a29) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel) * ('a19, 'b19, 'c19, 'd19, 'e19, 'f19, 'a29, 'b29, 'c29, 'd29, 'e29, 'f29) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(('g0, 'h0, 'i0, 'j0, 'k0, 'l0) [format6](camlinternalformatbasics#TYPEformat6) -> 'g1, 'b19, 'c19, 'j1, 'e19, 'f19, ('g0, 'h0, 'i0, 'j0, 'k0, 'l0) [format6](camlinternalformatbasics#TYPEformat6) -> 'g2, 'b29, 'c29, 'j2, 'e29, 'f29) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Alpha\_ty : `('a110, 'b110, 'c110, 'd110, 'e110, 'f110, 'a210, 'b210, 'c210, 'd210, 'e210, 'f210) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(('b110 -> 'x -> 'c110) -> 'x -> 'a110, 'b110, 'c110, 'd110, 'e110, 'f110, ('b210 -> 'x -> 'c210) -> 'x -> 'a210, 'b210, 'c210, 'd210, 'e210, 'f210) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Theta\_ty : `('a111, 'b111, 'c111, 'd111, 'e111, 'f111, 'a211, 'b211, 'c211, 'd211, 'e211, 'f211) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `(('b111 -> 'c111) -> 'a111, 'b111, 'c111, 'd111, 'e111, 'f111, ('b211 -> 'c211) -> 'a211, 'b211, 'c211, 'd211, 'e211, 'f211) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Any\_ty : `('a112, 'b112, 'c112, 'd112, 'e112, 'f112, 'a212, 'b212, 'c212, 'd212, 'e212, 'f212) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `('x0 -> 'a112, 'b112, 'c112, 'd112, 'e112, 'f112, 'x0 -> 'a212, 'b212, 'c212, 'd212, 'e212, 'f212) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Reader\_ty : `('a113, 'b113, 'c113, 'd113, 'e113, 'f113, 'a213, 'b213, 'c213, 'd213, 'e213, 'f213) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `('x1 -> 'a113, 'b113, 'c113, ('b113 -> 'x1) -> 'd113, 'e113, 'f113, 'x1 -> 'a213, 'b213, 'c213, ('b213 -> 'x1) -> 'd213, 'e213, 'f213) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `Ignored\_reader\_ty : `('a114, 'b114, 'c114, 'd114, 'e114, 'f114, 'a214, 'b214, 'c214, 'd214, 'e214, 'f214) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)` -> `('a114, 'b114, 'c114, ('b114 -> 'x2) -> 'd114, 'e114, 'f114, 'a214, 'b214, 'c214, ('b214 -> 'x2) -> 'd214, 'e214, 'f214) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
| `|` | `End\_of\_fmtty : `('f115, 'b115, 'c115, 'd115, 'd115, 'f115, 'f215, 'b215, 'c215, 'd215, 'd215, 'f215) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel)`` |
```
type ('a, 'b, 'c, 'd, 'e, 'f) fmt =
```
| | |
| --- | --- |
| `|` | `Char : `('a0, 'b0, 'c0, 'd0, 'e0, 'f0) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(char -> 'a0, 'b0, 'c0, 'd0, 'e0, 'f0) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Caml\_char : `('a1, 'b1, 'c1, 'd1, 'e1, 'f1) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(char -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `String : `('x, string -> 'a2) [padding](camlinternalformatbasics#TYPEpadding) * ('a2, 'b2, 'c2, 'd2, 'e2, 'f2) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x, 'b2, 'c2, 'd2, 'e2, 'f2) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Caml\_string : `('x0, string -> 'a3) [padding](camlinternalformatbasics#TYPEpadding) * ('a3, 'b3, 'c3, 'd3, 'e3, 'f3) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x0, 'b3, 'c3, 'd3, 'e3, 'f3) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Int : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * ('x1, 'y) [padding](camlinternalformatbasics#TYPEpadding) * ('y, int -> 'a4) [precision](camlinternalformatbasics#TYPEprecision) * ('a4, 'b4, 'c4, 'd4, 'e4, 'f4) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x1, 'b4, 'c4, 'd4, 'e4, 'f4) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Int32 : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * ('x2, 'y0) [padding](camlinternalformatbasics#TYPEpadding) * ('y0, int32 -> 'a5) [precision](camlinternalformatbasics#TYPEprecision) * ('a5, 'b5, 'c5, 'd5, 'e5, 'f5) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x2, 'b5, 'c5, 'd5, 'e5, 'f5) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Nativeint : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * ('x3, 'y1) [padding](camlinternalformatbasics#TYPEpadding) * ('y1, nativeint -> 'a6) [precision](camlinternalformatbasics#TYPEprecision) * ('a6, 'b6, 'c6, 'd6, 'e6, 'f6) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x3, 'b6, 'c6, 'd6, 'e6, 'f6) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Int64 : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * ('x4, 'y2) [padding](camlinternalformatbasics#TYPEpadding) * ('y2, int64 -> 'a7) [precision](camlinternalformatbasics#TYPEprecision) * ('a7, 'b7, 'c7, 'd7, 'e7, 'f7) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x4, 'b7, 'c7, 'd7, 'e7, 'f7) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Float : `[float\_conv](camlinternalformatbasics#TYPEfloat_conv) * ('x5, 'y3) [padding](camlinternalformatbasics#TYPEpadding) * ('y3, float -> 'a8) [precision](camlinternalformatbasics#TYPEprecision) * ('a8, 'b8, 'c8, 'd8, 'e8, 'f8) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x5, 'b8, 'c8, 'd8, 'e8, 'f8) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Bool : `('x6, bool -> 'a9) [padding](camlinternalformatbasics#TYPEpadding) * ('a9, 'b9, 'c9, 'd9, 'e9, 'f9) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x6, 'b9, 'c9, 'd9, 'e9, 'f9) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Flush : `('a10, 'b10, 'c10, 'd10, 'e10, 'f10) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('a10, 'b10, 'c10, 'd10, 'e10, 'f10) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `String\_literal : `string * ('a11, 'b11, 'c11, 'd11, 'e11, 'f11) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('a11, 'b11, 'c11, 'd11, 'e11, 'f11) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Char\_literal : `char * ('a12, 'b12, 'c12, 'd12, 'e12, 'f12) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('a12, 'b12, 'c12, 'd12, 'e12, 'f12) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Format\_arg : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * ('g, 'h, 'i, 'j, 'k, 'l) [fmtty](camlinternalformatbasics#TYPEfmtty) * ('a13, 'b13, 'c13, 'd13, 'e13, 'f13) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(('g, 'h, 'i, 'j, 'k, 'l) [format6](camlinternalformatbasics#TYPEformat6) -> 'a13, 'b13, 'c13, 'd13, 'e13, 'f13) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Format\_subst : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * ('g0, 'h0, 'i0, 'j0, 'k0, 'l0, 'g2, 'b14, 'c14, 'j2, 'd14, 'a14) [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel) * ('a14, 'b14, 'c14, 'd14, 'e14, 'f14) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(('g0, 'h0, 'i0, 'j0, 'k0, 'l0) [format6](camlinternalformatbasics#TYPEformat6) -> 'g2, 'b14, 'c14, 'j2, 'e14, 'f14) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Alpha : `('a15, 'b15, 'c15, 'd15, 'e15, 'f15) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(('b15 -> 'x7 -> 'c15) -> 'x7 -> 'a15, 'b15, 'c15, 'd15, 'e15, 'f15) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Theta : `('a16, 'b16, 'c16, 'd16, 'e16, 'f16) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(('b16 -> 'c16) -> 'a16, 'b16, 'c16, 'd16, 'e16, 'f16) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Formatting\_lit : `[formatting\_lit](camlinternalformatbasics#TYPEformatting_lit) * ('a17, 'b17, 'c17, 'd17, 'e17, 'f17) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('a17, 'b17, 'c17, 'd17, 'e17, 'f17) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Formatting\_gen : `('a18, 'b18, 'c18, 'd18, 'e18, 'f18) [formatting\_gen](camlinternalformatbasics#TYPEformatting_gen) * ('f18, 'b18, 'c18, 'e18, 'e20, 'f20) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('a18, 'b18, 'c18, 'd18, 'e20, 'f20) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Reader : `('a19, 'b19, 'c19, 'd19, 'e19, 'f19) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('x8 -> 'a19, 'b19, 'c19, ('b19 -> 'x8) -> 'd19, 'e19, 'f19) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Scan\_char\_set : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * [char\_set](camlinternalformatbasics#TYPEchar_set) * ('a20, 'b20, 'c20, 'd20, 'e21, 'f21) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(string -> 'a20, 'b20, 'c20, 'd20, 'e21, 'f21) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Scan\_get\_counter : `[counter](camlinternalformatbasics#TYPEcounter) * ('a21, 'b21, 'c21, 'd21, 'e22, 'f22) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(int -> 'a21, 'b21, 'c21, 'd21, 'e22, 'f22) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Scan\_next\_char : `('a22, 'b22, 'c22, 'd22, 'e23, 'f23) [fmt](camlinternalformatbasics#TYPEfmt)` -> `(char -> 'a22, 'b22, 'c22, 'd22, 'e23, 'f23) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Ignored\_param : `('a23, 'b23, 'c23, 'd23, 'y4, 'x9) [ignored](camlinternalformatbasics#TYPEignored) * ('x9, 'b23, 'c23, 'y4, 'e24, 'f24) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('a23, 'b23, 'c23, 'd23, 'e24, 'f24) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `Custom : `('a24, 'x10, 'y5) [custom\_arity](camlinternalformatbasics#TYPEcustom_arity) * (unit -> 'x10) * ('a24, 'b24, 'c24, 'd24, 'e25, 'f25) [fmt](camlinternalformatbasics#TYPEfmt)` -> `('y5, 'b24, 'c24, 'd24, 'e25, 'f25) [fmt](camlinternalformatbasics#TYPEfmt)`` |
| `|` | `End\_of\_format : `('f26, 'b25, 'c25, 'e26, 'e26, 'f26) [fmt](camlinternalformatbasics#TYPEfmt)`` |
List of format elements.
```
type ('a, 'b, 'c, 'd, 'e, 'f) ignored =
```
| | |
| --- | --- |
| `|` | `Ignored\_char : `('a0, 'b0, 'c0, 'd0, 'd0, 'a0) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_caml\_char : `('a1, 'b1, 'c1, 'd1, 'd1, 'a1) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_string : `[pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a2, 'b2, 'c2, 'd2, 'd2, 'a2) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_caml\_string : `[pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a3, 'b3, 'c3, 'd3, 'd3, 'a3) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_int : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * [pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a4, 'b4, 'c4, 'd4, 'd4, 'a4) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_int32 : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * [pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a5, 'b5, 'c5, 'd5, 'd5, 'a5) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_nativeint : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * [pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a6, 'b6, 'c6, 'd6, 'd6, 'a6) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_int64 : `[int\_conv](camlinternalformatbasics#TYPEint_conv) * [pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a7, 'b7, 'c7, 'd7, 'd7, 'a7) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_float : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * [prec\_option](camlinternalformatbasics#TYPEprec_option)` -> `('a8, 'b8, 'c8, 'd8, 'd8, 'a8) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_bool : `[pad\_option](camlinternalformatbasics#TYPEpad_option)` -> `('a9, 'b9, 'c9, 'd9, 'd9, 'a9) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_format\_arg : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * ('g, 'h, 'i, 'j, 'k, 'l) [fmtty](camlinternalformatbasics#TYPEfmtty)` -> `('a10, 'b10, 'c10, 'd10, 'd10, 'a10) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_format\_subst : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * ('a11, 'b11, 'c11, 'd11, 'e0, 'f0) [fmtty](camlinternalformatbasics#TYPEfmtty)` -> `('a11, 'b11, 'c11, 'd11, 'e0, 'f0) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_reader : `('a12, 'b12, 'c12, ('b12 -> 'x) -> 'd12, 'd12, 'a12) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_scan\_char\_set : `[pad\_option](camlinternalformatbasics#TYPEpad_option) * [char\_set](camlinternalformatbasics#TYPEchar_set)` -> `('a13, 'b13, 'c13, 'd13, 'd13, 'a13) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_scan\_get\_counter : `[counter](camlinternalformatbasics#TYPEcounter)` -> `('a14, 'b14, 'c14, 'd14, 'd14, 'a14) [ignored](camlinternalformatbasics#TYPEignored)`` |
| `|` | `Ignored\_scan\_next\_char : `('a15, 'b15, 'c15, 'd15, 'd15, 'a15) [ignored](camlinternalformatbasics#TYPEignored)`` |
```
type ('a, 'b, 'c, 'd, 'e, 'f) format6 =
```
| | |
| --- | --- |
| `|` | `Format of `('a, 'b, 'c, 'd, 'e, 'f) [fmt](camlinternalformatbasics#TYPEfmt) * string`` |
```
val concat_fmtty : ('g1, 'b1, 'c1, 'j1, 'd1, 'a1, 'g2, 'b2, 'c2, 'j2, 'd2, 'a2) fmtty_rel -> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1, 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel -> ('g1, 'b1, 'c1, 'j1, 'e1, 'f1, 'g2, 'b2, 'c2, 'j2, 'e2, 'f2) fmtty_rel
```
```
val erase_rel : ('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l) fmtty_rel -> ('a, 'b, 'c, 'd, 'e, 'f) fmtty
```
```
val concat_fmt : ('a, 'b, 'c, 'd, 'e, 'f) fmt -> ('f, 'b, 'c, 'e, 'g, 'h) fmt -> ('a, 'b, 'c, 'd, 'g, 'h) fmt
```
| programming_docs |
ocaml Module Obj Module Obj
==========
```
module Obj: sig .. end
```
Operations on internal representations of values.
Not for the casual user.
```
type t
```
```
type raw_data = nativeint
```
```
val repr : 'a -> t
```
```
val obj : t -> 'a
```
```
val magic : 'a -> 'b
```
```
val is_block : t -> bool
```
```
val is_int : t -> bool
```
```
val tag : t -> int
```
```
val size : t -> int
```
```
val reachable_words : t -> int
```
Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. Statically allocated blocks are included.
* **Since** 4.04
```
val field : t -> int -> t
```
```
val set_field : t -> int -> t -> unit
```
When using flambda:
`set_field` MUST NOT be called on immutable blocks. (Blocks allocated in C stubs, or with `new_block` below, are always considered mutable.)
The same goes for `set_double_field`.
For experts only: `set_field` et al can be made safe by first wrapping the block in [`Sys.opaque_identity`](sys#VALopaque_identity), so any information about its contents will not be propagated.
```
val compare_and_swap_field : t -> int -> t -> t -> bool
```
```
val is_shared : t -> bool
```
```
val double_field : t -> int -> float
```
```
val set_double_field : t -> int -> float -> unit
```
```
val raw_field : t -> int -> raw_data
```
```
val set_raw_field : t -> int -> raw_data -> unit
```
```
val new_block : int -> int -> t
```
```
val dup : t -> t
```
```
val add_offset : t -> Int32.t -> t
```
```
val with_tag : int -> t -> t
```
```
val first_non_constant_constructor_tag : int
```
```
val last_non_constant_constructor_tag : int
```
```
val forcing_tag : int
```
```
val cont_tag : int
```
```
val lazy_tag : int
```
```
val closure_tag : int
```
```
val object_tag : int
```
```
val infix_tag : int
```
```
val forward_tag : int
```
```
val no_scan_tag : int
```
```
val abstract_tag : int
```
```
val string_tag : int
```
```
val double_tag : int
```
```
val double_array_tag : int
```
```
val custom_tag : int
```
```
val int_tag : int
```
```
val out_of_heap_tag : int
```
```
val unaligned_tag : int
```
```
module Closure: sig .. end
```
```
module Extension_constructor: sig .. end
```
```
module Ephemeron: sig .. end
```
ocaml Module Either Module Either
=============
```
module Either: sig .. end
```
Either type.
Either is the simplest and most generic sum/variant type: a value of `('a, 'b) Either.t` is either a `Left (v : 'a)` or a `Right (v : 'b)`.
It is a natural choice in the API of generic functions where values could fall in two different cases, possibly at different types, without assigning a specific meaning to what each case should be.
For example:
```
List.partition_map:
('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
```
If you are looking for a parametrized type where one alternative means success and the other means failure, you should use the more specific type [`Result.t`](result#TYPEt).
* **Since** 4.12
```
type ('a, 'b) t =
```
| | |
| --- | --- |
| `|` | `Left of `'a`` |
| `|` | `Right of `'b`` |
A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b`
```
val left : 'a -> ('a, 'b) t
```
`left v` is `Left v`.
```
val right : 'b -> ('a, 'b) t
```
`right v` is `Right v`.
```
val is_left : ('a, 'b) t -> bool
```
`is_left (Left v)` is `true`, `is_left (Right v)` is `false`.
```
val is_right : ('a, 'b) t -> bool
```
`is_right (Left v)` is `false`, `is_right (Right v)` is `true`.
```
val find_left : ('a, 'b) t -> 'a option
```
`find_left (Left v)` is `Some v`, `find_left (Right _)` is `None`
```
val find_right : ('a, 'b) t -> 'b option
```
`find_right (Right v)` is `Some v`, `find_right (Left _)` is `None`
```
val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t
```
`map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`.
```
val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t
```
`map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`.
```
val map : left:('a1 -> 'a2) -> right:('b1 -> 'b2) -> ('a1, 'b1) t -> ('a2, 'b2) t
```
`map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`.
```
val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c
```
`fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`.
```
val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit
```
`iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`.
```
val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool
```
`for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`.
```
val equal : left:('a -> 'a -> bool) -> right:('b -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t -> bool
```
`equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`.
```
val compare : left:('a -> 'a -> int) -> right:('b -> 'b -> int) -> ('a, 'b) t -> ('a, 'b) t -> int
```
`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. `Left _` values are smaller than `Right _` values.
ocaml Functor MoreLabels.Set.Make Functor MoreLabels.Set.Make
===========================
```
module Make: functor (Ord : OrderedType) -> S
with type elt = Ord.t
and type t = Set.Make(Ord).t
```
Functor building an implementation of the set structure given a totally ordered type.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `Ord` | : | `[OrderedType](morelabels.set.orderedtype)` |
|
```
type elt
```
The type of the set elements.
```
type t
```
The type of sets.
```
val empty : t
```
The empty set.
```
val is_empty : t -> bool
```
Test whether a set is empty or not.
```
val mem : elt -> t -> bool
```
`mem x s` tests whether `x` belongs to the set `s`.
```
val add : elt -> t -> t
```
`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val singleton : elt -> t
```
`singleton x` returns the one-element set containing only `x`.
```
val remove : elt -> t -> t
```
`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val union : t -> t -> t
```
Set union.
```
val inter : t -> t -> t
```
Set intersection.
```
val disjoint : t -> t -> bool
```
Test if two sets are disjoint.
* **Since** 4.08.0
```
val diff : t -> t -> t
```
Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`.
```
val compare : t -> t -> int
```
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
```
val equal : t -> t -> bool
```
`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements.
```
val subset : t -> t -> bool
```
`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`.
```
val iter : f:(elt -> unit) -> t -> unit
```
`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements.
```
val map : f:(elt -> elt) -> t -> t
```
`map ~f s` is the set whose elements are `f a0`,`f a1`... `f
aN`, where `a0`,`a1`...`aN` are the elements of `s`.
The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements.
If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.)
* **Since** 4.04.0
```
val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
```
`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order.
```
val for_all : f:(elt -> bool) -> t -> bool
```
`for_all ~f s` checks if all elements of the set satisfy the predicate `f`.
```
val exists : f:(elt -> bool) -> t -> bool
```
`exists ~f s` checks if at least one element of the set satisfies the predicate `f`.
```
val filter : f:(elt -> bool) -> t -> t
```
`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).
* **Before 4.03** Physical equality was not ensured.
```
val filter_map : f:(elt -> elt option) -> t -> t
```
`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`.
For example,
```
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
```
is the set of halves of the even elements of `s`.
If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`.
* **Since** 4.11.0
```
val partition : f:(elt -> bool) -> t -> t * t
```
`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`.
```
val cardinal : t -> int
```
Return the number of elements of a set.
```
val elements : t -> elt list
```
Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`MoreLabels.Set.Make`](morelabels.set.make).
```
val min_elt : t -> elt
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the set is empty.
```
val min_elt_opt : t -> elt option
```
Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty.
* **Since** 4.05
```
val max_elt : t -> elt
```
Same as [`MoreLabels.Set.S.min_elt`](morelabels.set.s#VALmin_elt), but returns the largest element of the given set.
```
val max_elt_opt : t -> elt option
```
Same as [`MoreLabels.Set.S.min_elt_opt`](morelabels.set.s#VALmin_elt_opt), but returns the largest element of the given set.
* **Since** 4.05
```
val choose : t -> elt
```
Return one element of the given set, or raise `Not\_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
```
val choose_opt : t -> elt option
```
Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.
* **Since** 4.05
```
val split : elt -> t -> t * bool * t
```
`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`.
```
val find : elt -> t -> elt
```
`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not\_found` if no such element exists.
* **Since** 4.01.0
```
val find_opt : elt -> t -> elt option
```
`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists.
* **Since** 4.05
```
val find_first : f:(elt -> bool) -> t -> elt
```
`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not\_found` if `x` is greater than any element of `s`.
* **Since** 4.05
```
val find_first_opt : f:(elt -> bool) -> t -> elt option
```
`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val find_last : f:(elt -> bool) -> t -> elt
```
`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists.
* **Since** 4.05
```
val find_last_opt : f:(elt -> bool) -> t -> elt option
```
`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists.
* **Since** 4.05
```
val of_list : elt list -> t
```
`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements.
* **Since** 4.02.0
Iterators
---------
```
val to_seq_from : elt -> t -> elt Seq.t
```
`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above.
* **Since** 4.07
```
val to_seq : t -> elt Seq.t
```
Iterate on the whole set, in ascending order
* **Since** 4.07
```
val to_rev_seq : t -> elt Seq.t
```
Iterate on the whole set, in descending order
* **Since** 4.12
```
val add_seq : elt Seq.t -> t -> t
```
Add the given elements to the set, in order.
* **Since** 4.07
```
val of_seq : elt Seq.t -> t
```
Build a set from the given bindings
* **Since** 4.07
ocaml Module type Map.S Module type Map.S
=================
```
module type S = sig .. end
```
Output signature of the functor [`Map.Make`](map.make).
```
type key
```
The type of the map keys.
```
type +'a t
```
The type of maps from type `key` to type `'a`.
```
val empty : 'a t
```
The empty map.
```
val is_empty : 'a t -> bool
```
Test whether a map is empty or not.
```
val mem : key -> 'a t -> bool
```
`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise.
```
val add : key -> 'a -> 'a t -> 'a t
```
`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears.
* **Before 4.03** Physical equality was not ensured.
```
val update : key -> ('a option -> 'a option) -> 'a t -> 'a t
```
`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Since** 4.06.0
```
val singleton : key -> 'a -> 'a t
```
`singleton x y` returns the one-element map that contains a binding `y` for `x`.
* **Since** 3.12.0
```
val remove : key -> 'a t -> 'a t
```
`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Before 4.03** Physical equality was not ensured.
```
val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
```
`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`.
* **Since** 3.12.0
```
val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
```
`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where
* `f' _key None None = None`
* `f' _key (Some v) None = Some v`
* `f' _key None (Some v) = Some v`
* `f' key (Some v1) (Some v2) = f key v1 v2`
* **Since** 4.03.0
```
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
```
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
```
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
```
`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys.
```
val iter : (key -> 'a -> unit) -> 'a t -> unit
```
`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
```
`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data.
```
val for_all : (key -> 'a -> bool) -> 'a t -> bool
```
`for_all f m` checks if all the bindings of the map satisfy the predicate `f`.
* **Since** 3.12.0
```
val exists : (key -> 'a -> bool) -> 'a t -> bool
```
`exists f m` checks if at least one binding of the map satisfies the predicate `f`.
* **Since** 3.12.0
```
val filter : (key -> 'a -> bool) -> 'a t -> 'a t
```
`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`)
* **Before 4.03** Physical equality was not ensured.
* **Since** 3.12.0
```
val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t
```
`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map:
* if `f k v` is `None` then `k` is not in the result,
* if `f k v` is `Some v'` then the binding `(k, v')` is in the output map.
For example, the following function on maps whose values are lists
```
filter_map
(fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
```
drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty.
* **Since** 4.11.0
```
val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
```
`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`.
* **Since** 3.12.0
```
val cardinal : 'a t -> int
```
Return the number of bindings of a map.
* **Since** 3.12.0
```
val bindings : 'a t -> (key * 'a) list
```
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](map.make).
* **Since** 3.12.0
```
val min_binding : 'a t -> key * 'a
```
Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the map is empty.
* **Since** 3.12.0
```
val min_binding_opt : 'a t -> (key * 'a) option
```
Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty.
* **Since** 4.05
```
val max_binding : 'a t -> key * 'a
```
Same as [`Map.S.min_binding`](map.s#VALmin_binding), but returns the binding with the largest key in the given map.
* **Since** 3.12.0
```
val max_binding_opt : 'a t -> (key * 'a) option
```
Same as [`Map.S.min_binding_opt`](map.s#VALmin_binding_opt), but returns the binding with the largest key in the given map.
* **Since** 4.05
```
val choose : 'a t -> key * 'a
```
Return one binding of the given map, or raise `Not\_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 3.12.0
```
val choose_opt : 'a t -> (key * 'a) option
```
Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 4.05
```
val split : key -> 'a t -> 'a t * 'a option * 'a t
```
`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`.
* **Since** 3.12.0
```
val find : key -> 'a t -> 'a
```
`find x m` returns the current value of `x` in `m`, or raises `Not\_found` if no binding for `x` exists.
```
val find_opt : key -> 'a t -> 'a option
```
`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists.
* **Since** 4.05
```
val find_first : (key -> bool) -> 'a t -> key * 'a
```
`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not\_found` if `x` is greater than any element of `m`.
* **Since** 4.05
```
val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option
```
`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val find_last : (key -> bool) -> 'a t -> key * 'a
```
`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
* **Since** 4.05
```
val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option
```
`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val map : ('a -> 'b) -> 'a t -> 'b t
```
`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
```
Same as [`Map.S.map`](map.s#VALmap), but the function receives as arguments both the key and the associated value for each binding of the map.
Maps and Sequences
------------------
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in ascending order of keys
* **Since** 4.07
```
val to_rev_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in descending order of keys
* **Since** 4.12
```
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
```
`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above.
* **Since** 4.07
```
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
```
Add the given bindings to the map, in order.
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
Build a map from the given bindings
* **Since** 4.07
| programming_docs |
ocaml Module Event Module Event
============
```
module Event: sig .. end
```
First-class synchronous communication.
This module implements synchronous inter-thread communications over channels. As in John Reppy's Concurrent ML system, the communication events are first-class values: they can be built and combined independently before being offered for communication.
```
type 'a channel
```
The type of communication channels carrying values of type `'a`.
```
val new_channel : unit -> 'a channel
```
Return a new channel.
```
type +'a event
```
The type of communication events returning a result of type `'a`.
```
val send : 'a channel -> 'a -> unit event
```
`send ch v` returns the event consisting in sending the value `v` over the channel `ch`. The result value of this event is `()`.
```
val receive : 'a channel -> 'a event
```
`receive ch` returns the event consisting in receiving a value from the channel `ch`. The result value of this event is the value received.
```
val always : 'a -> 'a event
```
`always v` returns an event that is always ready for synchronization. The result value of this event is `v`.
```
val choose : 'a event list -> 'a event
```
`choose evl` returns the event that is the alternative of all the events in the list `evl`.
```
val wrap : 'a event -> ('a -> 'b) -> 'b event
```
`wrap ev fn` returns the event that performs the same communications as `ev`, then applies the post-processing function `fn` on the return value.
```
val wrap_abort : 'a event -> (unit -> unit) -> 'a event
```
`wrap_abort ev fn` returns the event that performs the same communications as `ev`, but if it is not selected the function `fn` is called after the synchronization.
```
val guard : (unit -> 'a event) -> 'a event
```
`guard fn` returns the event that, when synchronized, computes `fn()` and behaves as the resulting event. This enables computing events with side-effects at the time of the synchronization operation.
```
val sync : 'a event -> 'a
```
'Synchronize' on an event: offer all the communication possibilities specified in the event to the outside world, and block until one of the communications succeed. The result value of that communication is returned.
```
val select : 'a event list -> 'a
```
'Synchronize' on an alternative of events. `select evl` is shorthand for `sync(choose evl)`.
```
val poll : 'a event -> 'a option
```
Non-blocking version of [`Event.sync`](event#VALsync): offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return `Some r` where `r` is the result value of that communication. Otherwise, return `None` without blocking.
ocaml Module type MoreLabels.Set.OrderedType Module type MoreLabels.Set.OrderedType
======================================
```
module type OrderedType = sig .. end
```
Input signature of the functor [`MoreLabels.Set.Make`](morelabels.set.make).
```
type t
```
The type of the set elements.
```
val compare : t -> t -> int
```
A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`compare`](stdlib#VALcompare).
ocaml Module Float.Array Module Float.Array
==================
```
module Array: sig .. end
```
Float arrays with packed representation.
```
type t = floatarray
```
The type of float arrays with packed representation.
* **Since** 4.08.0
```
val length : t -> int
```
Return the length (number of elements) of the given floatarray.
```
val get : t -> int -> float
```
`get a n` returns the element number `n` of floatarray `a`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val set : t -> int -> float -> unit
```
`set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val make : int -> float -> t
```
`make n x` returns a fresh floatarray of length `n`, initialized with `x`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_floatarray_length`.
```
val create : int -> t
```
`create n` returns a fresh floatarray of length `n`, with uninitialized data.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_floatarray_length`.
```
val init : int -> (int -> float) -> t
```
`init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_floatarray_length`.
```
val append : t -> t -> t
```
`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`.
* **Raises** `Invalid_argument` if `length v1 + length v2 > Sys.max_floatarray_length`.
```
val concat : t list -> t
```
Same as [`Float.Array.append`](float.array#VALappend), but concatenates a list of floatarrays.
```
val sub : t -> int -> int -> t
```
`sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.
```
val copy : t -> t
```
`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`.
```
val fill : t -> int -> int -> float -> unit
```
`fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.
```
val blit : t -> int -> t -> int -> int -> unit
```
`blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.
```
val to_list : t -> float list
```
`to_list a` returns the list of all the elements of `a`.
```
val of_list : float list -> t
```
`of_list l` returns a fresh floatarray containing the elements of `l`.
* **Raises** `Invalid_argument` if the length of `l` is greater than `Sys.max_floatarray_length`.
### Iterators
```
val iter : (float -> unit) -> t -> unit
```
`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`.
```
val iteri : (int -> float -> unit) -> t -> unit
```
Same as [`Float.Array.iter`](float.array#VALiter), but the function is applied with the index of the element as first argument, and the element itself as second argument.
```
val map : (float -> float) -> t -> t
```
`map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`.
```
val mapi : (int -> float -> float) -> t -> t
```
Same as [`Float.Array.map`](float.array#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val fold_left : ('a -> float -> 'a) -> 'a -> t -> 'a
```
`fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`.
```
val fold_right : (float -> 'a -> 'a) -> t -> 'a -> 'a
```
`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`.
### Iterators on two arrays
```
val iter2 : (float -> float -> unit) -> t -> t -> unit
```
`Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`.
* **Raises** `Invalid_argument` if the floatarrays are not the same size.
```
val map2 : (float -> float -> float) -> t -> t -> t
```
`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.
* **Raises** `Invalid_argument` if the floatarrays are not the same size.
### Array scanning
```
val for_all : (float -> bool) -> t -> bool
```
`for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.
```
val exists : (float -> bool) -> t -> bool
```
`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.
```
val mem : float -> t -> bool
```
`mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`.
```
val mem_ieee : float -> t -> bool
```
Same as [`Float.Array.mem`](float.array#VALmem), but uses IEEE equality instead of structural equality.
### Sorting
```
val sort : (float -> float -> int) -> t -> unit
```
Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` :
* `cmp x y` > 0 if and only if `cmp y x` < 0
* if `cmp x y` >= 0 and `cmp y z` >= 0 then `cmp x z` >= 0
When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` :
* `cmp a.(i) a.(j)` >= 0 if and only if i >= j
```
val stable_sort : (float -> float -> int) -> t -> unit
```
Same as [`Float.Array.sort`](float.array#VALsort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`Float.Array.sort`](float.array#VALsort).
```
val fast_sort : (float -> float -> int) -> t -> unit
```
Same as [`Float.Array.sort`](float.array#VALsort) or [`Float.Array.stable_sort`](float.array#VALstable_sort), whichever is faster on typical input.
### Float arrays and Sequences
```
val to_seq : t -> float Seq.t
```
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.
```
val to_seqi : t -> (int * float) Seq.t
```
Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
```
val of_seq : float Seq.t -> t
```
Create an array from the generator.
```
val map_to_array : (float -> 'a) -> t -> 'a array
```
`map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.
```
val map_from_array : ('a -> float) -> 'a array -> t
```
`map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`.
Arrays and concurrency safety
-----------------------------
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
```
let size = 100_000_000
let a = Float.Array.make size 1.
let update a f () =
Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a
let d1 = Domain.spawn (update a (fun x -> x +. 1.))
let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
let () = Domain.join d1; Domain.join d2
```
After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.
### Tearing
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
```
let zeros = Float.Array.make size 0.
let max_floats = Float.Array.make size Float.max_float
let res = Float.Array.copy zeros
let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```
the `res` float array might contain values that are neither `0.` nor `max_float`.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
ocaml Module Random Module Random
=============
```
module Random: sig .. end
```
Pseudo-random number generators (PRNG).
With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain.
In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the [`Random.split`](random#VALsplit) function and used with the functions from the [`Random.State`](random.state) module.
Basic functions
---------------
```
val init : int -> unit
```
Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers.
```
val full_init : int array -> unit
```
Same as [`Random.init`](random#VALinit) but takes more data as seed.
```
val self_init : unit -> unit
```
Initialize the domain-local generator with a random seed chosen in a system-dependent way. If `/dev/urandom` is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state).
```
val bits : unit -> int
```
Return 30 random bits in a nonnegative integer.
* **Before 5.0.0** used a different algorithm (affects all the following functions)
```
val int : int -> int
```
`Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than 230.
```
val full_int : int -> int
```
`Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer.
If `bound` is less than 230, `Random.full_int bound` is equal to [`Random.int`](random#VALint)`bound`. If `bound` is greater than 230 (on 64-bit systems or non-standard environments, such as JavaScript), `Random.full_int` returns a value, where [`Random.int`](random#VALint) raises [`Invalid\_argument`](stdlib#EXCEPTIONInvalid_argument).
* **Since** 4.13.0
```
val int32 : Int32.t -> Int32.t
```
`Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0.
```
val nativeint : Nativeint.t -> Nativeint.t
```
`Random.nativeint bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0.
```
val int64 : Int64.t -> Int64.t
```
`Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0.
```
val float : float -> float
```
`Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). If `bound` is negative, the result is negative or zero. If `bound` is 0, the result is 0.
```
val bool : unit -> bool
```
`Random.bool ()` returns `true` or `false` with probability 0.5 each.
```
val bits32 : unit -> Int32.t
```
`Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](int32#VALmin_int) and [`Int32.max_int`](int32#VALmax_int).
* **Since** 4.14.0
```
val bits64 : unit -> Int64.t
```
`Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](int64#VALmin_int) and [`Int64.max_int`](int64#VALmax_int).
* **Since** 4.14.0
```
val nativebits : unit -> Nativeint.t
```
`Random.nativebits ()` returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between [`Nativeint.min_int`](nativeint#VALmin_int) and [`Nativeint.max_int`](nativeint#VALmax_int).
* **Since** 4.14.0
Advanced functions
------------------
The functions from module [`Random.State`](random.state) manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program.
```
module State: sig .. end
```
```
val get_state : unit -> State.t
```
`get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions).
```
val set_state : State.t -> unit
```
`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it.
```
val split : unit -> State.t
```
Draw a fresh PRNG state from the current state of the domain-local generator used by the default functions. (The state of the domain-local generator is modified.) See [`Random.State.split`](random.state#VALsplit).
* **Since** 5.0.0
| programming_docs |
ocaml Module Sys.Immediate64 Module Sys.Immediate64
======================
```
module Immediate64: sig .. end
```
This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate.
```
module type Non_immediate = sig .. end
```
```
module type Immediate = sig .. end
```
```
module Make: functor (Immediate : Immediate) -> functor (Non_immediate : Non_immediate) -> sig .. end
```
ocaml Module Out_channel Module Out\_channel
===================
```
module Out_channel: sig .. end
```
Output channels.
* **Since** 4.14.0
```
type t = out_channel
```
The type of output channel.
```
type open_flag = open_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `Open\_rdonly` | `(*` | open for reading. | `*)` |
| `|` | `Open\_wronly` | `(*` | open for writing. | `*)` |
| `|` | `Open\_append` | `(*` | open for appending: always write at end of file. | `*)` |
| `|` | `Open\_creat` | `(*` | create the file if it does not exist. | `*)` |
| `|` | `Open\_trunc` | `(*` | empty the file if it already exists. | `*)` |
| `|` | `Open\_excl` | `(*` | fail if Open\_creat and the file already exists. | `*)` |
| `|` | `Open\_binary` | `(*` | open in binary mode (no conversion). | `*)` |
| `|` | `Open\_text` | `(*` | open in text mode (may perform conversions). | `*)` |
| `|` | `Open\_nonblock` | `(*` | open in non-blocking mode. | `*)` |
Opening modes for [`Out\_channel.open_gen`](out_channel#VALopen_gen).
```
val stdout : t
```
The standard output for the process.
```
val stderr : t
```
The standard error output for the process.
```
val open_bin : string -> t
```
Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.
```
val open_text : string -> t
```
Same as [`Out\_channel.open_bin`](out_channel#VALopen_bin), but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Out\_channel.open_bin`](out_channel#VALopen_bin).
```
val open_gen : open_flag list -> int -> string -> t
```
`open_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`Out\_channel.open_text`](out_channel#VALopen_text) and [`Out\_channel.open_bin`](out_channel#VALopen_bin) are special cases of this function.
```
val with_open_bin : string -> (t -> 'a) -> 'a
```
`with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f
oc`. After `f` returns, either with a value or by raising an exception, `oc` is guaranteed to be closed.
```
val with_open_text : string -> (t -> 'a) -> 'a
```
Like [`Out\_channel.with_open_bin`](out_channel#VALwith_open_bin), but the channel is opened in text mode (see [`Out\_channel.open_text`](out_channel#VALopen_text)).
```
val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a
```
Like [`Out\_channel.with_open_bin`](out_channel#VALwith_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`Out\_channel.open_gen`](out_channel#VALopen_gen)).
```
val seek : t -> int64 -> unit
```
`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.
```
val pos : t -> int64
```
Return the current writing position for the given channel. Does not work on channels opened with the `Open\_append` flag (returns unspecified results).
For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`Out\_channel.pos`](out_channel#VALpos), then going back to this position using [`Out\_channel.seek`](out_channel#VALseek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.
```
val length : t -> int64
```
Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.
```
val close : t -> unit
```
Close the given channel, flushing all buffered write operations. Output functions raise a `Sys\_error` exception when they are applied to a closed output channel, except [`Out\_channel.close`](out_channel#VALclose) and [`Out\_channel.flush`](out_channel#VALflush), which do nothing when applied to an already closed channel. Note that [`Out\_channel.close`](out_channel#VALclose) may raise `Sys\_error` if the operating system signals an error when flushing or closing.
```
val close_noerr : t -> unit
```
Same as [`Out\_channel.close`](out_channel#VALclose), but ignore all errors.
```
val flush : t -> unit
```
Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.
```
val flush_all : unit -> unit
```
Flush all open output channels; ignore errors.
```
val output_char : t -> char -> unit
```
Write the character on the given output channel.
```
val output_byte : t -> int -> unit
```
Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.
```
val output_string : t -> string -> unit
```
Write the string on the given output channel.
```
val output_bytes : t -> bytes -> unit
```
Write the byte sequence on the given output channel.
```
val output : t -> bytes -> int -> int -> unit
```
`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
```
val output_substring : t -> string -> int -> int -> unit
```
Same as [`Out\_channel.output`](out_channel#VALoutput) but take a string as argument instead of a byte sequence.
```
val set_binary_mode : t -> bool -> unit
```
`set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output.
`set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`.
This function has no effect under operating systems that do not distinguish between text mode and binary mode.
```
val set_buffered : t -> bool -> unit
```
`set_buffered oc true` sets the channel `oc` to *buffered* mode. In this mode, data output on `oc` will be buffered until either the internal buffer is full or the function [`Out\_channel.flush`](out_channel#VALflush) or [`Out\_channel.flush_all`](out_channel#VALflush_all) is called, at which point it will be sent to the output device.
`set_buffered oc false` sets the channel `oc` to *unbuffered* mode. In this mode, data output on `oc` will be sent to the output device immediately.
All channels are open in *buffered* mode by default.
```
val is_buffered : t -> bool
```
`is_buffered oc` returns whether the channel `oc` is buffered (see [`Out\_channel.set_buffered`](out_channel#VALset_buffered)).
ocaml Module Domain.DLS Module Domain.DLS
=================
```
module DLS: sig .. end
```
Domain-local Storage
```
type 'a key
```
Type of a DLS key
```
val new_key : ?split_from_parent:('a -> 'a) -> (unit -> 'a) -> 'a key
```
`new_key f` returns a new key bound to initialiser `f` for accessing , domain-local variables.
If `split_from_parent` is not provided, the value for a new domain will be computed on-demand by the new domain: the first `get` call will call the initializer `f` and store that value.
If `split_from_parent` is provided, spawning a domain will derive the child value (for this key) from the parent value. This computation happens in the parent domain and it always happens, regardless of whether the child domain will use it. If the splitting function is expensive or requires child-side computation, consider using `'a Lazy.t key`:
```
let init () = ...
let split_from_parent parent_value =
... parent-side computation ...;
lazy (
... child-side computation ...
)
let key = Domain.DLS.new_key ~split_from_parent init
let get () = Lazy.force (Domain.DLS.get key)
```
In this case a part of the computation happens on the child domain; in particular, it can access `parent_value` concurrently with the parent domain, which may require explicit synchronization to avoid data races.
```
val get : 'a key -> 'a
```
`get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. Sets `k`'s value with its initialiser and returns it otherwise.
```
val set : 'a key -> 'a -> unit
```
`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later.
ocaml Module Callback Module Callback
===============
```
module Callback: sig .. end
```
Registering OCaml values with the C runtime.
This module allows OCaml values to be registered with the C runtime under a symbolic name, so that C code can later call back registered OCaml functions, or raise registered OCaml exceptions.
```
val register : string -> 'a -> unit
```
`Callback.register n v` registers the value `v` under the name `n`. C code can later retrieve a handle to `v` by calling `caml_named_value(n)`.
```
val register_exception : string -> exn -> unit
```
`Callback.register_exception n exn` registers the exception contained in the exception value `exn` under the name `n`. C code can later retrieve a handle to the exception by calling `caml_named_value(n)`. The exception value thus obtained is suitable for passing as first argument to `raise_constant` or `raise_with_arg`.
ocaml Functor Ephemeron.Kn.Make Functor Ephemeron.Kn.Make
=========================
```
module Make: functor (H : Hashtbl.HashedType) -> Ephemeron.S with type key = H.t array
```
Functor building an implementation of a weak hash table
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[Hashtbl.HashedType](hashtbl.hashedtype)` |
|
Propose the same interface as usual hash table. However since the bindings are weak, even if `mem h k` is true, a subsequent `find h k` may raise `Not\_found` because the garbage collector can run between the two.
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Functor Ephemeron.K2.Make Functor Ephemeron.K2.Make
=========================
```
module Make: functor (H1 : Hashtbl.HashedType) -> functor (H2 : Hashtbl.HashedType) -> Ephemeron.S with type key = H1.t * H2.t
```
Functor building an implementation of a weak hash table
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H1` | : | `[Hashtbl.HashedType](hashtbl.hashedtype)` |
| `H2` | : | `[Hashtbl.HashedType](hashtbl.hashedtype)` |
|
Propose the same interface as usual hash table. However since the bindings are weak, even if `mem h k` is true, a subsequent `find h k` may raise `Not\_found` because the garbage collector can run between the two.
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module Scanf.Scanning Module Scanf.Scanning
=====================
```
module Scanning: sig .. end
```
```
type in_channel
```
The notion of input channel for the [`Scanf`](scanf) module: those channels provide all the machinery necessary to read from any source of characters, including a [`in_channel`](stdlib#TYPEin_channel) value. A Scanf.Scanning.in\_channel value is also called a *formatted input channel* or equivalently a *scanning buffer*. The type [`Scanf.Scanning.scanbuf`](scanf.scanning#TYPEscanbuf) below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions.
* **Since** 3.12.0
```
type scanbuf = in_channel
```
The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far.
Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read.
```
val stdin : in_channel
```
The standard input notion for the [`Scanf`](scanf) module. `Scanning.stdin` is the [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel attached to [`stdin`](stdlib#VALstdin).
Note: in the interactive system, when input is read from [`stdin`](stdlib#VALstdin), the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string).
* **Since** 3.12.0
```
type file_name = string
```
A convenient alias to designate a file name.
* **Since** 4.00.0
```
val open_in : file_name -> in_channel
```
`Scanning.open_in fname` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel for bufferized reading in text mode from file `fname`.
Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate.
* **Since** 3.12.0
```
val open_in_bin : file_name -> in_channel
```
`Scanning.open_in_bin fname` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel for bufferized reading in binary mode from file `fname`.
* **Since** 3.12.0
```
val close_in : in_channel -> unit
```
Closes the [`in_channel`](stdlib#TYPEin_channel) associated with the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel.
* **Since** 3.12.0
```
val from_file : file_name -> in_channel
```
An alias for [`Scanf.Scanning.open_in`](scanf.scanning#VALopen_in) above.
```
val from_file_bin : string -> in_channel
```
An alias for [`Scanf.Scanning.open_in_bin`](scanf.scanning#VALopen_in_bin) above.
```
val from_string : string -> in_channel
```
`Scanning.from_string s` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel which reads from the given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached.
```
val from_function : (unit -> char) -> in_channel
```
`Scanning.from_function f` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel with the given function as its reading method.
When scanning needs one more character, the given function is called.
When the function has no more character to provide, it *must* signal an end-of-input condition by raising the exception `End\_of\_file`.
```
val from_channel : in_channel -> in_channel
```
`Scanning.from_channel ic` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel which reads from the regular [`in_channel`](stdlib#TYPEin_channel) input channel `ic` argument. Reading starts at current reading position of `ic`.
```
val end_of_input : in_channel -> bool
```
`Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel.
```
val beginning_of_input : in_channel -> bool
```
`Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel.
```
val name_of_input : in_channel -> string
```
`Scanning.name_of_input ic` returns the name of the character source for the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel.
* **Since** 3.09.0
ocaml Module UnixLabels.LargeFile Module UnixLabels.LargeFile
===========================
```
module LargeFile: sig .. end
```
File operations on large files. This sub-module provides 64-bit variants of the functions [`UnixLabels.LargeFile.lseek`](unixlabels.largefile#VALlseek) (for positioning a file descriptor), [`UnixLabels.LargeFile.truncate`](unixlabels.largefile#VALtruncate) and [`UnixLabels.LargeFile.ftruncate`](unixlabels.largefile#VALftruncate) (for changing the size of a file), and [`UnixLabels.LargeFile.stat`](unixlabels.largefile#VALstat), [`UnixLabels.LargeFile.lstat`](unixlabels.largefile#VALlstat) and [`UnixLabels.LargeFile.fstat`](unixlabels.largefile#VALfstat) (for obtaining information on files). These alternate functions represent positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), thus allowing operating on files whose sizes are greater than `max_int`.
```
val lseek : UnixLabels.file_descr -> int64 -> mode:UnixLabels.seek_command -> int64
```
See `lseek`.
```
val truncate : string -> len:int64 -> unit
```
See `truncate`.
```
val ftruncate : UnixLabels.file_descr -> len:int64 -> unit
```
See `ftruncate`.
```
type stats = Unix.LargeFile.stats = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `st\_dev : `int`;` | `(*` | Device number | `*)` |
| | `st\_ino : `int`;` | `(*` | Inode number | `*)` |
| | `st\_kind : `[UnixLabels.file\_kind](unixlabels#TYPEfile_kind)`;` | `(*` | Kind of the file | `*)` |
| | `st\_perm : `[UnixLabels.file\_perm](unixlabels#TYPEfile_perm)`;` | `(*` | Access rights | `*)` |
| | `st\_nlink : `int`;` | `(*` | Number of links | `*)` |
| | `st\_uid : `int`;` | `(*` | User id of the owner | `*)` |
| | `st\_gid : `int`;` | `(*` | Group ID of the file's group | `*)` |
| | `st\_rdev : `int`;` | `(*` | Device ID (if special file) | `*)` |
| | `st\_size : `int64`;` | `(*` | Size in bytes | `*)` |
| | `st\_atime : `float`;` | `(*` | Last access time | `*)` |
| | `st\_mtime : `float`;` | `(*` | Last modification time | `*)` |
| | `st\_ctime : `float`;` | `(*` | Last status change time | `*)` |
`}`
```
val stat : string -> stats
```
```
val lstat : string -> stats
```
```
val fstat : UnixLabels.file_descr -> stats
```
| programming_docs |
ocaml Module Lazy Module Lazy
===========
```
module Lazy: sig .. end
```
Deferred computations.
```
type 'a t = 'a CamlinternalLazy.t
```
A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy (expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazy(pattern)` also computes the underlying expression and tries to bind it to `pattern`:
```
let lazy_option_map f x =
match x with
| lazy (Some x) -> Some (Lazy.force f x)
| _ -> None
```
Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed.
Note: `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead.
Note: `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, systhreads or domains, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified.
Note: if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(...(lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker.
```
exception Undefined
```
Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively.
```
val force : 'a t -> 'a
```
`force x` forces the suspension `x` and returns its result. If `x` has already been forced, `Lazy.force x` returns the same value again without recomputing it. If it raised an exception, the same exception is raised again.
* **Raises** `Undefined` (see [`Lazy.Undefined`](lazy#EXCEPTIONUndefined)).
Iterators
---------
```
val map : ('a -> 'b) -> 'a t -> 'b t
```
`map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value.
It is equivalent to `lazy (f (Lazy.force x))`.
* **Since** 4.13.0
Reasoning on already-forced suspensions
---------------------------------------
```
val is_val : 'a t -> bool
```
`is_val x` returns `true` if `x` has already been forced and did not raise an exception.
* **Since** 4.00.0
```
val from_val : 'a -> 'a t
```
`from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases.
* **Since** 4.00.0
```
val map_val : ('a -> 'b) -> 'a t -> 'b t
```
`map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`.
When `x` is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result.
If `f` raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the thunk otherwise.
If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`.
* **Since** 4.13.0
Advanced
--------
The following definitions are for advanced uses only; they require familiary with the lazy compilation scheme to be used appropriately.
```
val from_fun : (unit -> 'a) -> 'a t
```
`from_fun f` is the same as `lazy (f ())` but slightly more efficient.
It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from_fun (fun () -> expr)` than `lazy expr`.
* **Since** 4.00.0
```
val force_val : 'a t -> 'a
```
`force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it.
If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or [`Lazy.Undefined`](lazy#EXCEPTIONUndefined).
* **Raises**
+ `Undefined` if the forcing of `x` tries to force `x` itself recursively.
+ `Undefined` (see [`Lazy.Undefined`](lazy#EXCEPTIONUndefined)).
ocaml Module CamlinternalOO Module CamlinternalOO
=====================
```
module CamlinternalOO: sig .. end
```
Run-time support for objects and classes. All functions in this module are for system use only, not for the casual user.
Classes
-------
```
type tag
```
```
type label
```
```
type table
```
```
type meth
```
```
type t
```
```
type obj
```
```
type closure
```
```
val public_method_label : string -> tag
```
```
val new_method : table -> label
```
```
val new_variable : table -> string -> int
```
```
val new_methods_variables : table -> string array -> string array -> label array
```
```
val get_variable : table -> string -> int
```
```
val get_variables : table -> string array -> int array
```
```
val get_method_label : table -> string -> label
```
```
val get_method_labels : table -> string array -> label array
```
```
val get_method : table -> label -> meth
```
```
val set_method : table -> label -> meth -> unit
```
```
val set_methods : table -> label array -> unit
```
```
val narrow : table -> string array -> string array -> string array -> unit
```
```
val widen : table -> unit
```
```
val add_initializer : table -> (obj -> unit) -> unit
```
```
val dummy_table : table
```
```
val create_table : string array -> table
```
```
val init_class : table -> unit
```
```
val inherits : table -> string array -> string array -> string array -> t * (table -> obj -> Obj.t) * t * obj -> bool -> Obj.t array
```
```
val make_class : string array -> (table -> Obj.t -> t) -> t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t
```
```
type init_table
```
```
val make_class_store : string array -> (table -> t) -> init_table -> unit
```
```
val dummy_class : string * int * int -> t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t
```
Objects
-------
```
val copy : (< .. > as 'a) -> 'a
```
```
val create_object : table -> obj
```
```
val create_object_opt : obj -> table -> obj
```
```
val run_initializers : obj -> table -> unit
```
```
val run_initializers_opt : obj -> obj -> table -> obj
```
```
val create_object_and_run_initializers : obj -> table -> obj
```
```
val send : obj -> tag -> t
```
```
val sendcache : obj -> tag -> t -> int -> t
```
```
val sendself : obj -> label -> t
```
```
val get_public_method : obj -> tag -> closure
```
Table cache
-----------
```
type tables
```
```
val lookup_tables : tables -> closure array -> tables
```
Builtins to reduce code size
----------------------------
```
type impl =
```
| | |
| --- | --- |
| `|` | `GetConst` |
| `|` | `GetVar` |
| `|` | `GetEnv` |
| `|` | `GetMeth` |
| `|` | `SetVar` |
| `|` | `AppConst` |
| `|` | `AppVar` |
| `|` | `AppEnv` |
| `|` | `AppMeth` |
| `|` | `AppConstConst` |
| `|` | `AppConstVar` |
| `|` | `AppConstEnv` |
| `|` | `AppConstMeth` |
| `|` | `AppVarConst` |
| `|` | `AppEnvConst` |
| `|` | `AppMethConst` |
| `|` | `MethAppConst` |
| `|` | `MethAppVar` |
| `|` | `MethAppEnv` |
| `|` | `MethAppMeth` |
| `|` | `SendConst` |
| `|` | `SendVar` |
| `|` | `SendEnv` |
| `|` | `SendMeth` |
| `|` | `Closure of `[closure](camlinternaloo#TYPEclosure)`` |
Parameters
----------
```
type params = {
```
| | |
| --- | --- |
| | `mutable compact\_table : `bool`;` |
| | `mutable copy\_parent : `bool`;` |
| | `mutable clean\_when\_copying : `bool`;` |
| | `mutable retry\_count : `int`;` |
| | `mutable bucket\_small\_size : `int`;` |
`}`
```
val params : params
```
Statistics
----------
```
type stats = {
```
| | |
| --- | --- |
| | `classes : `int`;` |
| | `methods : `int`;` |
| | `inst\_vars : `int`;` |
`}`
```
val stats : unit -> stats
```
ocaml Module Gc Module Gc
=========
```
module Gc: sig .. end
```
Memory management control and statistics; finalised values.
```
type stat = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `minor\_words : `float`;` | `(*` | Number of words allocated in the minor heap since the program was started. | `*)` |
| | `promoted\_words : `float`;` | `(*` | Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started. | `*)` |
| | `major\_words : `float`;` | `(*` | Number of words allocated in the major heap, including the promoted words, since the program was started. | `*)` |
| | `minor\_collections : `int`;` | `(*` | Number of minor collections since the program was started. | `*)` |
| | `major\_collections : `int`;` | `(*` | Number of major collection cycles completed since the program was started. | `*)` |
| | `heap\_words : `int`;` | `(*` | Total size of the major heap, in words. | `*)` |
| | `heap\_chunks : `int`;` | `(*` | Number of contiguous pieces of memory that make up the major heap. | `*)` |
| | `live\_words : `int`;` | `(*` | Number of words of live data in the major heap, including the header words. Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call [`Gc.full_major`](gc#VALfull_major) (or [`Gc.compact`](gc#VALcompact)) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to [`Gc.full_major`](gc#VALfull_major) will not reclaim values that have a finaliser from [`Gc.finalise`](gc#VALfinalise) (this does not apply to [`Gc.finalise_last`](gc#VALfinalise_last)). If this caveat matters, simply call [`Gc.full_major`](gc#VALfull_major) twice instead of once. | `*)` |
| | `live\_blocks : `int`;` | `(*` | Number of live blocks in the major heap. See `live_words` for a caveat about what "live" means. | `*)` |
| | `free\_words : `int`;` | `(*` | Number of words in the free list. | `*)` |
| | `free\_blocks : `int`;` | `(*` | Number of blocks in the free list. | `*)` |
| | `largest\_free : `int`;` | `(*` | Size (in words) of the largest block in the free list. | `*)` |
| | `fragments : `int`;` | `(*` | Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live blocks. They are not available for allocation. | `*)` |
| | `compactions : `int`;` | `(*` | Number of heap compactions since the program was started. | `*)` |
| | `top\_heap\_words : `int`;` | `(*` | Maximum size reached by the major heap, in words. | `*)` |
| | `stack\_size : `int`;` | `(*` | Current size of the stack, in words. * **Since** 3.12.0
| `*)` |
| | `forced\_major\_collections : `int`;` | `(*` | Number of forced full major collections completed since the program was started. * **Since** 4.12.0
| `*)` |
`}` The memory management counters are returned in a `stat` record. These counters give values for the whole program.
The total amount of memory allocated by the program since it was started is (in words) `minor_words + major_words - promoted_words`. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes.
```
type control = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `minor\_heap\_size : `int`;` | `(*` | The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. The total size of the minor heap used by this program is the sum of the heap sizes of the active domains. Default: 256k. | `*)` |
| | `major\_heap\_increment : `int`;` | `(*` | How much to add to the major heap when increasing it. If this number is less than or equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will double the heap size at each increase). If it is more than 1000, it is a fixed number of words that will be added to the heap. Default: 15. | `*)` |
| | `space\_overhead : `int`;` | `(*` | The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120. | `*)` |
| | `verbose : `int`;` | `(*` | This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events: * `0x001` Start and end of major GC cycle.
* `0x002` Minor collection and major GC slice.
* `0x004` Growing and shrinking of the heap.
* `0x008` Resizing of stacks and memory manager tables.
* `0x010` Heap compaction.
* `0x020` Change of GC parameters.
* `0x040` Computation of major GC slice size.
* `0x080` Calling of finalisation functions.
* `0x100` Bytecode executable and shared library search at start-up.
* `0x200` Computation of compaction-triggering condition.
* `0x400` Output GC statistics at program exit. Default: 0.
| `*)` |
| | `max\_overhead : `int`;` | `(*` | Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead >= 1000000`, compaction is never triggered. If compaction is permanently disabled, it is strongly suggested to set `allocation_policy` to 2. Default: 500. | `*)` |
| | `stack\_limit : `int`;` | `(*` | The maximum size of the fiber stacks (in words). Default: 1024k. | `*)` |
| | `allocation\_policy : `int`;` | `(*` | The policy used for allocating in the major heap. Possible values are 0, 1 and 2. * 0 is the next-fit policy, which is usually fast but can result in fragmentation, increasing memory consumption.
* 1 is the first-fit policy, which avoids fragmentation but has corner cases (in certain realistic workloads) where it is sensibly slower.
* 2 is the best-fit policy, which is fast and avoids fragmentation. In our experiments it is faster and uses less memory than both next-fit and first-fit. (since OCaml 4.10)
The default is best-fit. On one example that was known to be bad for next-fit and first-fit, next-fit takes 28s using 855Mio of memory, first-fit takes 47s using 566Mio of memory, best-fit takes 27s using 545Mio of memory. Note: If you change to next-fit, you may need to reduce the `space_overhead` setting, for example using `80` instead of the default `120` which is tuned for best-fit. Otherwise, your program will need more memory. Note: changing the allocation policy at run-time forces a heap compaction, which is a lengthy operation unless the heap is small (e.g. at the start of the program). Default: 2. * **Since** 3.11.0
| `*)` |
| | `window\_size : `int`;` | `(*` | The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50. Default: 1. * **Since** 4.03.0
| `*)` |
| | `custom\_major\_ratio : `int`;` | `(*` | Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44. * **Since** 4.08.0
| `*)` |
| | `custom\_minor\_ratio : `int`;` | `(*` | Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100. * **Since** 4.08.0
| `*)` |
| | `custom\_minor\_max\_size : `int`;` | `(*` | Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. When a custom value is allocated on the minor heap and holds more than this many bytes, only this value is counted against `custom_minor_ratio` and the rest is directly counted against `custom_major_ratio`. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 8192 bytes. * **Since** 4.08.0
| `*)` |
`}` The GC parameters are given as a `control` record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`.
```
val stat : unit -> stat
```
Return the current values of the memory management counters in a `stat` record that represent the program's total memory stats. This function causes a full major collection.
```
val quick_stat : unit -> stat
```
Same as `stat` except that `live_words`, `live_blocks`, `free_words`, `free_blocks`, `largest_free`, and `fragments` are set to 0. Due to per-domain buffers it may only represent the state of the program's total memory usage since the last minor collection. This function is much faster than `stat` because it does not need to trigger a full major collection.
```
val counters : unit -> float * float * float
```
Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`.
```
val minor_words : unit -> float
```
Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code.
In native code this function does not allocate.
* **Since** 4.04
```
val get : unit -> control
```
Return the current values of the GC parameters in a `control` record.
* **Alert unsynchronized\_access.** GC parameters are a mutable global state.
```
val set : control -> unit
```
`set r` changes the GC parameters according to the `control` record `r`. The normal usage is: `Gc.set { (Gc.get()) with Gc.verbose = 0x00d }`
* **Alert unsynchronized\_access.** GC parameters are a mutable global state.
```
val minor : unit -> unit
```
Trigger a minor collection.
```
val major_slice : int -> int
```
`major_slice n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n` = 0, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0).
```
val major : unit -> unit
```
Do a minor collection and finish the current major collection cycle.
```
val full_major : unit -> unit
```
Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks.
```
val compact : unit -> unit
```
Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation.
```
val print_stat : out_channel -> unit
```
Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument.
```
val allocated_bytes : unit -> float
```
Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines.
```
val get_minor_free : unit -> int
```
Return the current size of the free space inside the minor heap of this domain.
* **Since** 4.03.0
```
val finalise : ('a -> unit) -> 'a -> unit
```
`finalise f v` registers `f` as a finalisation function for `v`. `v` must be heap-allocated. `f` will be called with `v` as argument at some point between the first time `v` becomes unreachable (including through weak pointers) and the time `v` is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before `v` becomes unreachable).
The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments.
In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads.
Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected:
* `let v = ... in Gc.finalise (fun _ -> ...v...) v`
Instead you should make sure that `v` is not in the closure of the finalisation function by writing:
* `let f = fun x -> ... let v = ... in Gc.finalise f v`
The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of f, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called.
`finalise` will raise `Invalid\_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid\_argument` for them. Values of type `'a Lazy.t` (for any `'a`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid\_argument`, but you should still avoid calling `finalise` on lazy values.
The results of calling [`String.make`](string#VALmake), [`Bytes.make`](bytes#VALmake), [`Bytes.create`](bytes#VALcreate), [`Array.make`](array#VALmake), and [`ref`](stdlib#VALref) are guaranteed to be heap-allocated and non-constant except when the length argument is `0`.
```
val finalise_last : (unit -> unit) -> 'a -> unit
```
same as [`Gc.finalise`](gc#VALfinalise) except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to [`Gc.finalise`](gc#VALfinalise) the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with [`Gc.finalise`](gc#VALfinalise) are always called before the finalisation functions attached with [`Gc.finalise_last`](gc#VALfinalise_last).
* **Since** 4.04
```
val finalise_release : unit -> unit
```
A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return.
```
type alarm
```
An alarm is a piece of data that calls a user function at the end of each major GC cycle. The following functions are provided to create and delete alarms.
```
val create_alarm : (unit -> unit) -> alarm
```
`create_alarm f` will arrange for `f` to be called at the end of each major GC cycle, starting with the current cycle or the next one. A value of type `alarm` is returned that you can use to call `delete_alarm`.
```
val delete_alarm : alarm -> unit
```
`delete_alarm a` will stop the calls to the function associated to `a`. Calling `delete_alarm a` again has no effect.
```
val eventlog_pause : unit -> unit
```
Deprecated. Use Runtime\_events.pause instead.
```
val eventlog_resume : unit -> unit
```
Deprecated. Use Runtime\_events.resume instead.
```
module Memprof: sig .. end
```
`Memprof` is a sampling engine for allocated memory words.
| programming_docs |
ocaml Module Random.State Module Random.State
===================
```
module State: sig .. end
```
```
type t
```
The type of PRNG states.
```
val make : int array -> t
```
Create a new state and initialize it with the given seed.
```
val make_self_init : unit -> t
```
Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in [`Random.self_init`](random#VALself_init).
```
val copy : t -> t
```
Return a copy of the given state.
```
val bits : t -> int
```
```
val int : t -> int -> int
```
```
val full_int : t -> int -> int
```
```
val int32 : t -> Int32.t -> Int32.t
```
```
val nativeint : t -> Nativeint.t -> Nativeint.t
```
```
val int64 : t -> Int64.t -> Int64.t
```
```
val float : t -> float -> float
```
```
val bool : t -> bool
```
```
val bits32 : t -> Int32.t
```
```
val bits64 : t -> Int64.t
```
```
val nativebits : t -> Nativeint.t
```
These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one.
```
val split : t -> t
```
Draw a fresh PRNG state from the given PRNG state. (The given PRNG state is modified.) The new PRNG is statistically independent from the given PRNG. Data can be drawn from both PRNGs, in any order, without risk of correlation. Both PRNGs can be split later, arbitrarily many times.
* **Since** 5.0.0
ocaml Module Char Module Char
===========
```
module Char: sig .. end
```
Character operations.
```
val code : char -> int
```
Return the ASCII code of the argument.
```
val chr : int -> char
```
Return the character with the given ASCII code.
* **Raises** `Invalid_argument` if the argument is outside the range 0--255.
```
val escaped : char -> string
```
Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote.
```
val lowercase_ascii : char -> char
```
Convert the given character to its equivalent lowercase character, using the US-ASCII character set.
* **Since** 4.03.0
```
val uppercase_ascii : char -> char
```
Convert the given character to its equivalent uppercase character, using the US-ASCII character set.
* **Since** 4.03.0
```
type t = char
```
An alias for the type of characters.
```
val compare : t -> t -> int
```
The comparison function for characters, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Char` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val equal : t -> t -> bool
```
The equal function for chars.
* **Since** 4.03.0
ocaml Module Array Module Array
============
```
module Array: sig .. end
```
Array operations.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
```
type 'a t = 'a array
```
An alias for the type of arrays.
```
val length : 'a array -> int
```
Return the length (number of elements) of the given array.
```
val get : 'a array -> int -> 'a
```
`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `(length a - 1)`.
```
val set : 'a array -> int -> 'a -> unit
```
`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`.
* **Raises** `Invalid_argument` if `n` is outside the range 0 to `length a - 1`.
```
val make : int -> 'a -> 'a array
```
`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the value of `x` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.
```
val create_float : int -> float array
```
`create_float n` returns a fresh float array of length `n`, with uninitialized data.
* **Since** 4.03
```
val init : int -> (int -> 'a) -> 'a array
```
`init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`.
* **Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.
```
val make_matrix : int -> int -> 'a -> 'a array array
```
`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`.
* **Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than [`Sys.max_array_length`](sys#VALmax_array_length). If the value of `e` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.
```
val append : 'a array -> 'a array -> 'a array
```
`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`.
* **Raises** `Invalid_argument` if `length v1 + length v2 > Sys.max_array_length`.
```
val concat : 'a array list -> 'a array
```
Same as [`Array.append`](array#VALappend), but concatenates a list of arrays.
```
val sub : 'a array -> int -> int -> 'a array
```
`sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.
```
val copy : 'a array -> 'a array
```
`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`.
```
val fill : 'a array -> int -> int -> 'a -> unit
```
`fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.
```
val blit : 'a array -> int -> 'a array -> int -> int -> unit
```
`blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.
```
val to_list : 'a array -> 'a list
```
`to_list a` returns the list of all the elements of `a`.
```
val of_list : 'a list -> 'a array
```
`of_list l` returns a fresh array containing the elements of `l`.
* **Raises** `Invalid_argument` if the length of `l` is greater than `Sys.max_array_length`.
Iterators
---------
```
val iter : ('a -> unit) -> 'a array -> unit
```
`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`.
```
val iteri : (int -> 'a -> unit) -> 'a array -> unit
```
Same as [`Array.iter`](array#VALiter), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val map : ('a -> 'b) -> 'a array -> 'b array
```
`map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.
```
val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array
```
Same as [`Array.map`](array#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument.
```
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
```
`fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`.
```
val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array
```
`fold_left_map` is a combination of [`Array.fold_left`](array#VALfold_left) and [`Array.map`](array#VALmap) that threads an accumulator through calls to `f`.
* **Since** 4.13.0
```
val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a
```
`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`.
Iterators on two arrays
-----------------------
```
val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit
```
`iter2 f a b` applies function `f` to all the elements of `a` and `b`.
* **Since** 4.03.0 (4.05.0 in ArrayLabels)
* **Raises** `Invalid_argument` if the arrays are not the same size.
```
val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
```
`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.
* **Since** 4.03.0 (4.05.0 in ArrayLabels)
* **Raises** `Invalid_argument` if the arrays are not the same size.
Array scanning
--------------
```
val for_all : ('a -> bool) -> 'a array -> bool
```
`for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.
* **Since** 4.03.0
```
val exists : ('a -> bool) -> 'a array -> bool
```
`exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.
* **Since** 4.03.0
```
val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool
```
Same as [`Array.for_all`](array#VALfor_all), but for a two-argument predicate.
* **Since** 4.11.0
* **Raises** `Invalid_argument` if the two arrays have different lengths.
```
val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool
```
Same as [`Array.exists`](array#VALexists), but for a two-argument predicate.
* **Since** 4.11.0
* **Raises** `Invalid_argument` if the two arrays have different lengths.
```
val mem : 'a -> 'a array -> bool
```
`mem a set` is true if and only if `a` is structurally equal to an element of `l` (i.e. there is an `x` in `l` such that `compare a x = 0`).
* **Since** 4.03.0
```
val memq : 'a -> 'a array -> bool
```
Same as [`Array.mem`](array#VALmem), but uses physical equality instead of structural equality to compare list elements.
* **Since** 4.03.0
```
val find_opt : ('a -> bool) -> 'a array -> 'a option
```
`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`.
* **Since** 4.13.0
```
val find_map : ('a -> 'b option) -> 'a array -> 'b option
```
`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist.
* **Since** 4.13.0
Arrays of pairs
---------------
```
val split : ('a * 'b) array -> 'a array * 'b array
```
`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`.
* **Since** 4.13.0
```
val combine : 'a array -> 'b array -> ('a * 'b) array
```
`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid\_argument` if the two arrays have different lengths.
* **Since** 4.13.0
Sorting
-------
```
val sort : ('a -> 'a -> int) -> 'a array -> unit
```
Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` :
* `cmp x y` > 0 if and only if `cmp y x` < 0
* if `cmp x y` >= 0 and `cmp y z` >= 0 then `cmp x z` >= 0
When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` :
* `cmp a.(i) a.(j)` >= 0 if and only if i >= j
```
val stable_sort : ('a -> 'a -> int) -> 'a array -> unit
```
Same as [`Array.sort`](array#VALsort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`Array.sort`](array#VALsort).
```
val fast_sort : ('a -> 'a -> int) -> 'a array -> unit
```
Same as [`Array.sort`](array#VALsort) or [`Array.stable_sort`](array#VALstable_sort), whichever is faster on typical input.
Arrays and Sequences
--------------------
```
val to_seq : 'a array -> 'a Seq.t
```
Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : 'a array -> (int * 'a) Seq.t
```
Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a array
```
Create an array from the generator
* **Since** 4.07
Arrays and concurrency safety
-----------------------------
Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.
For example, consider the following program:
```
let size = 100_000_000
let a = Array.make size 1
let d1 = Domain.spawn (fun () ->
Array.iteri (fun i x -> a.(i) <- x + 1) a
)
let d2 = Domain.spawn (fun () ->
Array.iteri (fun i x -> a.(i) <- 2 * x + 1) a
)
let () = Domain.join d1; Domain.join d2
```
After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays).
### Float arrays
Float arrays have two supplementary caveats in the presence of data races.
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.
For instance, at the end of
```
let zeros = Array.make size 0.
let max_floats = Array.make size Float.max_float
let res = Array.copy zeros
let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```
the `res` array might contain values that are neither `0.` nor `max_float`.
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
ocaml Module type Weak.S Module type Weak.S
==================
```
module type S = sig .. end
```
The output signature of the functor [`Weak.Make`](weak.make).
```
type data
```
The type of the elements stored in the table.
```
type t
```
The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`output_value`](stdlib#VALoutput_value) or the functions of the [`Marshal`](marshal) module.
```
val create : int -> t
```
`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed.
```
val clear : t -> unit
```
Remove all elements from the table.
```
val merge : t -> data -> data
```
`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`.
```
val add : t -> data -> unit
```
`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`.
```
val remove : t -> data -> unit
```
`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`.
```
val find : t -> data -> data
```
`find t x` returns an instance of `x` found in `t`.
* **Raises** `Not_found` if there is no such element.
```
val find_opt : t -> data -> data option
```
`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element.
* **Since** 4.05
```
val find_all : t -> data -> data list
```
`find_all t x` returns a list of all the instances of `x` found in `t`.
```
val mem : t -> data -> bool
```
`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise.
```
val iter : (data -> unit) -> t -> unit
```
`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself.
```
val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
```
`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself.
```
val count : t -> int
```
Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements.
```
val stats : t -> int * int * int * int * int * int
```
Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length.
| programming_docs |
ocaml Module Effect.Deep Module Effect.Deep
==================
```
module Deep: sig .. end
```
Deep handlers
```
type ('a, 'b) continuation
```
`('a,'b) continuation` is a delimited continuation that expects a `'a` value and returns a `'b` value.
```
val continue : ('a, 'b) continuation -> 'a -> 'b
```
`continue k x` resumes the continuation `k` by passing `x` to `k`.
* **Raises** `Continuation_already_resumed` if the continuation has already been resumed.
```
val discontinue : ('a, 'b) continuation -> exn -> 'b
```
`discontinue k e` resumes the continuation `k` by raising the exception `e` in `k`.
* **Raises** `Continuation_already_resumed` if the continuation has already been resumed.
```
val discontinue_with_backtrace : ('a, 'b) continuation -> exn -> Printexc.raw_backtrace -> 'b
```
`discontinue_with_backtrace k e bt` resumes the continuation `k` by raising the exception `e` in `k` using `bt` as the origin for the exception.
* **Raises** `Continuation_already_resumed` if the continuation has already been resumed.
```
type ('a, 'b) handler = {
```
| | |
| --- | --- |
| | `retc : `'a -> 'b`;` |
| | `exnc : `exn -> 'b`;` |
| | `effc : `'c. 'c [Effect.t](effect#TYPEt) -> (('c, 'b) [continuation](effect.deep#TYPEcontinuation) -> 'b) option`;` |
`}` `('a,'b) handler` is a handler record with three fields -- `retc` is the value handler, `exnc` handles exceptions, and `effc` handles the effects performed by the computation enclosed by the handler.
```
val match_with : ('c -> 'a) -> 'c -> ('a, 'b) handler -> 'b
```
`match_with f v h` runs the computation `f v` in the handler `h`.
```
type 'a effect_handler = {
```
| | |
| --- | --- |
| | `effc : `'b. 'b [Effect.t](effect#TYPEt) -> (('b, 'a) [continuation](effect.deep#TYPEcontinuation) -> 'a) option`;` |
`}` `'a effect_handler` is a deep handler with an identity value handler `fun x -> x` and an exception handler that raises any exception `fun e -> raise e`.
```
val try_with : ('b -> 'a) -> 'b -> 'a effect_handler -> 'a
```
`try_with f v h` runs the computation `f v` under the handler `h`.
```
val get_callstack : ('a, 'b) continuation -> int -> Printexc.raw_backtrace
```
`get_callstack c n` returns a description of the top of the call stack on the continuation `c`, with at most `n` entries.
ocaml Index of modules Index of modules
================
| |
| --- |
| A |
| [Arg](arg) | Parsing of command line arguments. |
| [Array](array) | Array operations. |
| [Array](stdlabels.array) [[StdLabels](stdlabels)] | |
| [Array](float.array) [[Float](float)] | Float arrays with packed representation. |
| [Array0](bigarray.array0) [[Bigarray](bigarray)] | Zero-dimensional arrays. |
| [Array1](bigarray.array1) [[Bigarray](bigarray)] | One-dimensional arrays. |
| [Array2](bigarray.array2) [[Bigarray](bigarray)] | Two-dimensional arrays. |
| [Array3](bigarray.array3) [[Bigarray](bigarray)] | Three-dimensional arrays. |
| [ArrayLabels](arraylabels) | Array operations. |
| [ArrayLabels](float.arraylabels) [[Float](float)] | Float arrays with packed representation (labeled functions). |
| [Atomic](atomic) | Atomic references. |
| B |
| [Bigarray](bigarray) | Large, multi-dimensional, numerical arrays. |
| [Binary](semaphore.binary) [[Semaphore](semaphore)] | |
| [Bool](bool) | Boolean values. |
| [Bucket](ephemeron.kn.bucket) [[Ephemeron.Kn](ephemeron.kn)] | |
| [Bucket](ephemeron.k2.bucket) [[Ephemeron.K2](ephemeron.k2)] | |
| [Bucket](ephemeron.k1.bucket) [[Ephemeron.K1](ephemeron.k1)] | |
| [Buffer](buffer) | Extensible buffers. |
| [Bytes](bytes) | Byte sequence operations. |
| [Bytes](stdlabels.bytes) [[StdLabels](stdlabels)] | |
| [BytesLabels](byteslabels) | Byte sequence operations. |
| C |
| [Callback](callback) | Registering OCaml values with the C runtime. |
| [Callbacks](runtime_events.callbacks) [[Runtime\_events](runtime_events)] | |
| [CamlinternalFormat](camlinternalformat) | |
| [CamlinternalFormatBasics](camlinternalformatbasics) | |
| [CamlinternalLazy](camlinternallazy) | Run-time support for lazy values. |
| [CamlinternalMod](camlinternalmod) | Run-time support for recursive modules. |
| [CamlinternalOO](camlinternaloo) | Run-time support for objects and classes. |
| [Char](char) | Character operations. |
| [Closure](obj.closure) [[Obj](obj)] | |
| [Complex](complex) | Complex numbers. |
| [Condition](condition) | Condition variables. |
| [Counting](semaphore.counting) [[Semaphore](semaphore)] | |
| D |
| [DLS](domain.dls) [[Domain](domain)] | |
| [Deep](effect.deep) [[Effect](effect)] | |
| [Digest](digest) | MD5 message digest. |
| [Domain](domain) | |
| [Dynlink](dynlink) | Dynamic loading of .cmo, .cma and .cmxs files. |
| E |
| [Effect](effect) | |
| [Either](either) | Either type. |
| [Ephemeron](ephemeron) | Ephemerons and weak hash tables. |
| [Ephemeron](obj.ephemeron) [[Obj](obj)] | |
| [Event](event) | First-class synchronous communication. |
| [Extension\_constructor](obj.extension_constructor) [[Obj](obj)] | |
| F |
| [Filename](filename) | Operations on file names. |
| [Float](float) | Floating-point arithmetic. |
| [Format](format) | Pretty-printing. |
| [Format\_tutorial](format_tutorial) | Using the Format module |
| [Fun](fun) | Function manipulation. |
| G |
| [Gc](gc) | Memory management control and statistics; finalised values. |
| [Genarray](bigarray.genarray) [[Bigarray](bigarray)] | |
| H |
| [Hashtbl](hashtbl) | Hash tables and hash functions. |
| [Hashtbl](morelabels.hashtbl) [[MoreLabels](morelabels)] | |
| I |
| [Immediate64](sys.immediate64) [[Sys](sys)] | |
| [In\_channel](in_channel) | Input channels. |
| [Int](int) | Integer values. |
| [Int32](int32) | 32-bit integers. |
| [Int64](int64) | 64-bit integers. |
| K |
| [K1](ephemeron.k1) [[Ephemeron](ephemeron)] | Ephemerons with one key. |
| [K2](ephemeron.k2) [[Ephemeron](ephemeron)] | Ephemerons with two keys. |
| [Kn](ephemeron.kn) [[Ephemeron](ephemeron)] | Ephemerons with arbitrary number of keys of the same type. |
| L |
| [LargeFile](unixlabels.largefile) [[UnixLabels](unixlabels)] | File operations on large files. |
| [LargeFile](unix.largefile) [[Unix](unix)] | File operations on large files. |
| [Lazy](lazy) | Deferred computations. |
| [Lexing](lexing) | The run-time library for lexers generated by `ocamllex`. |
| [List](list) | List operations. |
| [List](stdlabels.list) [[StdLabels](stdlabels)] | |
| [ListLabels](listlabels) | List operations. |
| M |
| [Make](weak.make) [[Weak](weak)] | Functor building an implementation of the weak hash set structure. |
| [Make](sys.immediate64.make) [[Sys.Immediate64](sys.immediate64)] | |
| [Make](set.make) [[Set](set)] | Functor building an implementation of the set structure given a totally ordered type. |
| [Make](morelabels.set.make) [[MoreLabels.Set](morelabels.set)] | Functor building an implementation of the set structure given a totally ordered type. |
| [Make](morelabels.map.make) [[MoreLabels.Map](morelabels.map)] | Functor building an implementation of the map structure given a totally ordered type. |
| [Make](morelabels.hashtbl.make) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Functor building an implementation of the hashtable structure. |
| [Make](map.make) [[Map](map)] | Functor building an implementation of the map structure given a totally ordered type. |
| [Make](hashtbl.make) [[Hashtbl](hashtbl)] | Functor building an implementation of the hashtable structure. |
| [Make](ephemeron.kn.make) [[Ephemeron.Kn](ephemeron.kn)] | Functor building an implementation of a weak hash table |
| [Make](ephemeron.k2.make) [[Ephemeron.K2](ephemeron.k2)] | Functor building an implementation of a weak hash table |
| [Make](ephemeron.k1.make) [[Ephemeron.K1](ephemeron.k1)] | Functor building an implementation of a weak hash table |
| [MakeSeeded](morelabels.hashtbl.makeseeded) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Functor building an implementation of the hashtable structure. |
| [MakeSeeded](hashtbl.makeseeded) [[Hashtbl](hashtbl)] | Functor building an implementation of the hashtable structure. |
| [MakeSeeded](ephemeron.kn.makeseeded) [[Ephemeron.Kn](ephemeron.kn)] | Functor building an implementation of a weak hash table. |
| [MakeSeeded](ephemeron.k2.makeseeded) [[Ephemeron.K2](ephemeron.k2)] | Functor building an implementation of a weak hash table. |
| [MakeSeeded](ephemeron.k1.makeseeded) [[Ephemeron.K1](ephemeron.k1)] | Functor building an implementation of a weak hash table. |
| [Map](map) | Association tables over ordered types. |
| [Map](morelabels.map) [[MoreLabels](morelabels)] | |
| [Marshal](marshal) | Marshaling of data structures. |
| [Memprof](gc.memprof) [[Gc](gc)] | `Memprof` is a sampling engine for allocated memory words. |
| [MoreLabels](morelabels) | Extra labeled libraries. |
| [Mutex](mutex) | Locks for mutual exclusion. |
| N |
| [Nativeint](nativeint) | Processor-native integers. |
| O |
| [Obj](obj) | Operations on internal representations of values. |
| [Ocaml\_operators](ocaml_operators) | Precedence level and associativity of operators |
| [Oo](oo) | Operations on objects |
| [Option](option) | Option values. |
| [Out\_channel](out_channel) | Output channels. |
| P |
| [Parsing](parsing) | The run-time library for parsers generated by `ocamlyacc`. |
| [Printexc](printexc) | Facilities for printing exceptions and inspecting current call stack. |
| [Printf](printf) | Formatted output functions. |
| Q |
| [Queue](queue) | First-in first-out queues. |
| R |
| [Random](random) | Pseudo-random number generators (PRNG). |
| [Result](result) | Result values. |
| [Runtime\_events](runtime_events) | Runtime events - ring buffer-based runtime tracing |
| S |
| [Scanf](scanf) | Formatted input functions. |
| [Scanning](scanf.scanning) [[Scanf](scanf)] | |
| [Semaphore](semaphore) | Semaphores |
| [Seq](seq) | Sequences. |
| [Set](set) | Sets over ordered types. |
| [Set](morelabels.set) [[MoreLabels](morelabels)] | |
| [Shallow](effect.shallow) [[Effect](effect)] | |
| [Slot](printexc.slot) [[Printexc](printexc)] | |
| [Stack](stack) | Last-in first-out stacks. |
| [State](random.state) [[Random](random)] | |
| [StdLabels](stdlabels) | Standard labeled libraries. |
| [Stdlib](stdlib) | The OCaml Standard library. |
| [Str](str) | Regular expressions and high-level string processing |
| [String](string) | Strings. |
| [String](stdlabels.string) [[StdLabels](stdlabels)] | |
| [StringLabels](stringlabels) | Strings. |
| [Sys](sys) | System interface. |
| T |
| [Thread](thread) | Lightweight threads for Posix `1003.1c` and Win32. |
| [Timestamp](runtime_events.timestamp) [[Runtime\_events](runtime_events)] | |
| U |
| [Uchar](uchar) | Unicode characters. |
| [Unit](unit) | Unit values. |
| [Unix](unix) | Interface to the Unix system. |
| [UnixLabels](unixlabels) | Interface to the Unix system. |
| W |
| [Weak](weak) | Arrays of weak pointers and hash sets of weak pointers. |
ocaml Module Semaphore.Counting Module Semaphore.Counting
=========================
```
module Counting: sig .. end
```
```
type t
```
The type of counting semaphores.
```
val make : int -> t
```
`make n` returns a new counting semaphore, with initial value `n`. The initial value `n` must be nonnegative.
* **Raises** `Invalid_argument` if `n < 0`
```
val release : t -> unit
```
`release s` increments the value of semaphore `s`. If other threads are waiting on `s`, one of them is restarted. If the current value of `s` is equal to `max_int`, the value of the semaphore is unchanged and a `Sys\_error` exception is raised to signal overflow.
* **Raises** `Sys_error` if the value of the semaphore would overflow `max_int`
```
val acquire : t -> unit
```
`acquire s` blocks the calling thread until the value of semaphore `s` is not zero, then atomically decrements the value of `s` and returns.
```
val try_acquire : t -> bool
```
`try_acquire s` immediately returns `false` if the value of semaphore `s` is zero. Otherwise, the value of `s` is atomically decremented and `try_acquire s` returns `true`.
```
val get_value : t -> int
```
`get_value s` returns the current value of semaphore `s`. The current value can be modified at any time by concurrent [`Semaphore.Counting.release`](semaphore.counting#VALrelease) and [`Semaphore.Counting.acquire`](semaphore.counting#VALacquire) operations. Hence, the `get_value` operation is racy, and its result should only be used for debugging or informational messages.
ocaml Module Lexing Module Lexing
=============
```
module Lexing: sig .. end
```
The run-time library for lexers generated by `ocamllex`.
Positions
---------
```
type position = {
```
| | |
| --- | --- |
| | `pos\_fname : `string`;` |
| | `pos\_lnum : `int`;` |
| | `pos\_bol : `int`;` |
| | `pos\_cnum : `int`;` |
`}` A value of type `position` describes a point in a source file. `pos_fname` is the file name; `pos_lnum` is the line number; `pos_bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos_cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos_cnum` and `pos_bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide).
See the documentation of type `lexbuf` for information about how the lexing engine will manage positions.
```
val dummy_pos : position
```
A value of type `position`, guaranteed to be different from any valid position.
Lexer buffers
-------------
```
type lexbuf = {
```
| | |
| --- | --- |
| | `refill\_buff : `[lexbuf](lexing#TYPElexbuf) -> unit`;` |
| | `mutable lex\_buffer : `bytes`;` |
| | `mutable lex\_buffer\_len : `int`;` |
| | `mutable lex\_abs\_pos : `int`;` |
| | `mutable lex\_start\_pos : `int`;` |
| | `mutable lex\_curr\_pos : `int`;` |
| | `mutable lex\_last\_pos : `int`;` |
| | `mutable lex\_last\_action : `int`;` |
| | `mutable lex\_eof\_reached : `bool`;` |
| | `mutable lex\_mem : `int array`;` |
| | `mutable lex\_start\_p : `[position](lexing#TYPEposition)`;` |
| | `mutable lex\_curr\_p : `[position](lexing#TYPEposition)`;` |
`}` The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input.
Lexers can optionally maintain the `lex_curr_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_curr_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_curr_p` are not needed.
Position tracking mode works as follows. At each token, the lexing engine will copy `lex_curr_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_curr_p` by updating it with the number of characters read since the start of the `lexbuf`. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line -- see also `new_line`).
```
val from_channel : ?with_positions:bool -> in_channel -> lexbuf
```
Create a lexer buffer on the given input channel. `Lexing.from_channel inchan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position.
```
val from_string : ?with_positions:bool -> string -> lexbuf
```
Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached.
```
val from_function : ?with_positions:bool -> (bytes -> int -> int) -> lexbuf
```
Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input.
```
val set_position : lexbuf -> position -> unit
```
Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos_fname`. See [`Lexing.set_filename`](lexing#VALset_filename) for changing this field.
* **Since** 4.11
```
val set_filename : lexbuf -> string -> unit
```
Set filename in the initial tracked position to `file` in `lexbuf`.
* **Since** 4.11
```
val with_positions : lexbuf -> bool
```
Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`).
When `with_positions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances.
Functions for lexer semantic actions
------------------------------------
The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function.
```
val lexeme : lexbuf -> string
```
`Lexing.lexeme lexbuf` returns the string matched by the regular expression.
```
val lexeme_char : lexbuf -> int -> char
```
`Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string.
```
val lexeme_start : lexbuf -> int
```
`Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0.
```
val lexeme_end : lexbuf -> int
```
`Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0.
```
val lexeme_start_p : lexbuf -> position
```
Like `lexeme_start`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`.
```
val lexeme_end_p : lexbuf -> position
```
Like `lexeme_end`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`.
```
val new_line : lexbuf -> unit
```
Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled.
* **Since** 3.11.0
Miscellaneous functions
-----------------------
```
val flush_input : lexbuf -> unit
```
Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill.
| programming_docs |
ocaml Module Condition Module Condition
================
```
module Condition: sig .. end
```
Condition variables.
Condition variables are useful when several threads wish to access a shared data structure that is protected by a mutex (a mutual exclusion lock).
A condition variable is a *communication channel*. On the receiver side, one or more threads can indicate that they wish to *wait* for a certain property to become true. On the sender side, a thread can *signal* that this property has become true, causing one (or more) waiting threads to be woken up.
For instance, in the implementation of a queue data structure, if a thread that wishes to extract an element finds that the queue is currently empty, then this thread waits for the queue to become nonempty. A thread that inserts an element into the queue signals that the queue has become nonempty. A condition variable is used for this purpose. This communication channel conveys the information that the property "the queue is nonempty" is true, or more accurately, may be true. (We explain below why the receiver of a signal cannot be certain that the property holds.)
To continue the example of the queue, assuming that the queue has a fixed maximum capacity, then a thread that wishes to insert an element may find that the queue is full. Then, this thread must wait for the queue to become not full, and a thread that extracts an element of the queue signals that the queue has become not full. Another condition variable is used for this purpose.
In short, a condition variable `c` is used to convey the information that a certain property *P* about a shared data structure *D*, protected by a mutex `m`, may be true.
Condition variables provide an efficient alternative to busy-waiting. When one wishes to wait for the property *P* to be true, instead of writing a busy-waiting loop:
```
Mutex.lock m;
while not P do
Mutex.unlock m; Mutex.lock m
done;
<update the data structure>;
Mutex.unlock m
```
one uses [`Condition.wait`](condition#VALwait) in the body of the loop, as follows:
```
Mutex.lock m;
while not P do
Condition.wait c m
done;
<update the data structure>;
Mutex.unlock m
```
The busy-waiting loop is inefficient because the waiting thread consumes processing time and creates contention of the mutex `m`. Calling [`Condition.wait`](condition#VALwait) allows the waiting thread to be suspended, so it does not consume any computing resources while waiting.
With a condition variable `c`, exactly one mutex `m` is associated. This association is implicit: the mutex `m` is not explicitly passed as an argument to [`Condition.create`](condition#VALcreate). It is up to the programmer to know, for each condition variable `c`, which is the associated mutex `m`.
With a mutex `m`, several condition variables can be associated. In the example of the bounded queue, one condition variable is used to indicate that the queue is nonempty, and another condition variable is used to indicate that the queue is not full.
With a condition variable `c`, exactly one logical property *P* should be associated. Examples of such properties include "the queue is nonempty" and "the queue is not full". It is up to the programmer to keep track, for each condition variable, of the corresponding property *P*. A signal is sent on the condition variable `c` as an indication that the property *P* is true, or may be true. On the receiving end, however, a thread that is woken up cannot assume that *P* is true; after a call to [`Condition.wait`](condition#VALwait) terminates, one must explicitly test whether *P* is true. There are several reasons why this is so. One reason is that, between the moment when the signal is sent and the moment when a waiting thread receives the signal and is scheduled, the property *P* may be falsified by some other thread that is able to acquire the mutex `m` and alter the data structure *D*. Another reason is that *spurious wakeups* may occur: a waiting thread can be woken up even if no signal was sent.
Here is a complete example, where a mutex protects a sequential unbounded queue, and where a condition variable is used to signal that the queue is nonempty.
```
type 'a safe_queue =
{ queue : 'a Queue.t; mutex : Mutex.t; nonempty : Condition.t }
let create () =
{ queue = Queue.create(); mutex = Mutex.create();
nonempty = Condition.create() }
let add v q =
Mutex.lock q.mutex;
let was_empty = Queue.is_empty q.queue in
Queue.add v q.queue;
if was_empty then Condition.broadcast q.nonempty;
Mutex.unlock q.mutex
let take q =
Mutex.lock q.mutex;
while Queue.is_empty q.queue do Condition.wait q.nonempty q.mutex done;
let v = Queue.take q.queue in (* cannot fail since queue is nonempty *)
Mutex.unlock q.mutex;
v
```
Because the call to [`Condition.broadcast`](condition#VALbroadcast) takes place inside the critical section, the following property holds whenever the mutex is unlocked: *if the queue is nonempty, then no thread is waiting*, or, in other words, *if some thread is waiting, then the queue must be empty*. This is a desirable property: if a thread that attempts to execute a `take` operation could remain suspended even though the queue is nonempty, that would be a problematic situation, known as a *deadlock*.
```
type t
```
The type of condition variables.
```
val create : unit -> t
```
`create()` creates and returns a new condition variable. This condition variable should be associated (in the programmer's mind) with a certain mutex `m` and with a certain property *P* of the data structure that is protected by the mutex `m`.
```
val wait : t -> Mutex.t -> unit
```
The call `wait c m` is permitted only if `m` is the mutex associated with the condition variable `c`, and only if `m` is currently locked. This call atomically unlocks the mutex `m` and suspends the current thread on the condition variable `c`. This thread can later be woken up after the condition variable `c` has been signaled via [`Condition.signal`](condition#VALsignal) or [`Condition.broadcast`](condition#VALbroadcast); however, it can also be woken up for no reason. The mutex `m` is locked again before `wait` returns. One cannot assume that the property *P* associated with the condition variable `c` holds when `wait` returns; one must explicitly test whether *P* holds after calling `wait`.
```
val signal : t -> unit
```
`signal c` wakes up one of the threads waiting on the condition variable `c`, if there is one. If there is none, this call has no effect.
It is recommended to call `signal c` inside a critical section, that is, while the mutex `m` associated with `c` is locked.
```
val broadcast : t -> unit
```
`broadcast c` wakes up all threads waiting on the condition variable `c`. If there are none, this call has no effect.
It is recommended to call `broadcast c` inside a critical section, that is, while the mutex `m` associated with `c` is locked.
ocaml Module Ephemeron Module Ephemeron
================
```
module Ephemeron: sig .. end
```
Ephemerons and weak hash tables.
Ephemerons and weak hash tables are useful when one wants to cache or memorize the computation of a function, as long as the arguments and the function are used, without creating memory leaks by continuously keeping old computation results that are not useful anymore because one argument or the function is freed. An implementation using [`Hashtbl.t`](hashtbl#TYPEt) is not suitable because all associations would keep the arguments and the result in memory.
Ephemerons can also be used for "adding" a field to an arbitrary boxed OCaml value: you can attach some information to a value created by an external library without memory leaks.
Ephemerons hold some keys and one or no data. They are all boxed OCaml values. The keys of an ephemeron have the same behavior as weak pointers according to the garbage collector. In fact OCaml weak pointers are implemented as ephemerons without data.
The keys and data of an ephemeron are said to be full if they point to a value, or empty if the value has never been set, has been unset, or was erased by the GC. In the function that accesses the keys or data these two states are represented by the `option` type.
The data is considered by the garbage collector alive if all the full keys are alive and if the ephemeron is alive. When one of the keys is not considered alive anymore by the GC, the data is emptied from the ephemeron. The data could be alive for another reason and in that case the GC will not free it, but the ephemeron will not hold the data anymore.
The ephemerons complicate the notion of liveness of values, because it is not anymore an equivalence with the reachability from root value by usual pointers (not weak and not ephemerons). With ephemerons the notion of liveness is constructed by the least fixpoint of: A value is alive if:
* it is a root value
* it is reachable from alive value by usual pointers
* it is the data of an alive ephemeron with all its full keys alive
Notes:
* All the types defined in this module cannot be marshaled using [`output_value`](stdlib#VALoutput_value) or the functions of the [`Marshal`](marshal) module.
Ephemerons are defined in a language agnostic way in this paper: B. Hayes, Ephemerons: A New Finalization Mechanism, OOPSLA'97
* **Since** 4.03.0
* **Alert unsynchronized\_access.** Unsynchronized accesses to weak hash tables are a programming error.
**Unsynchronized accesses**
Unsynchronized accesses to a weak hash table may lead to an invalid weak hash table state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
```
module type S = sig .. end
```
The output signature of the functors [`Ephemeron.K1.Make`](ephemeron.k1.make) and [`Ephemeron.K2.Make`](ephemeron.k2.make).
```
module type SeededS = sig .. end
```
The output signature of the functors [`Ephemeron.K1.MakeSeeded`](ephemeron.k1.makeseeded) and [`Ephemeron.K2.MakeSeeded`](ephemeron.k2.makeseeded).
```
module K1: sig .. end
```
Ephemerons with one key.
```
module K2: sig .. end
```
Ephemerons with two keys.
```
module Kn: sig .. end
```
Ephemerons with arbitrary number of keys of the same type.
ocaml Functor MoreLabels.Hashtbl.Make Functor MoreLabels.Hashtbl.Make
===============================
```
module Make: functor (H : HashedType) -> S
with type key = H.t
and type 'a t = 'a Hashtbl.Make(H).t
```
Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[HashedType](morelabels.hashtbl.hashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
* **Since** 4.00.0
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key:key -> data:'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key:key -> data:'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> MoreLabels.Hashtbl.statistics
```
* **Since** 4.00.0
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Module Atomic Module Atomic
=============
```
module Atomic: sig .. end
```
Atomic references.
See 'Memory model: The hard bits' chapter in the manual.
* **Since** 4.12
```
type 'a t
```
An atomic (mutable) reference to a value of type `'a`.
```
val make : 'a -> 'a t
```
Create an atomic reference.
```
val get : 'a t -> 'a
```
Get the current value of the atomic reference.
```
val set : 'a t -> 'a -> unit
```
Set a new value for the atomic reference.
```
val exchange : 'a t -> 'a -> 'a
```
Set a new value for the atomic reference, and return the current value.
```
val compare_and_set : 'a t -> 'a -> 'a -> bool
```
`compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` -- the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise.
```
val fetch_and_add : int t -> int -> int
```
`fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment).
```
val incr : int t -> unit
```
`incr r` atomically increments the value of `r` by `1`.
```
val decr : int t -> unit
```
`decr r` atomically decrements the value of `r` by `1`.
ocaml Functor Hashtbl.Make Functor Hashtbl.Make
====================
```
module Make: functor (H : HashedType) -> S with type key = H.t
```
Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[HashedType](hashtbl.hashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
* **Since** 4.00.0
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : (key -> 'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
* **Since** 4.00.0
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Module Bigarray.Array0 Module Bigarray.Array0
======================
```
module Array0: sig .. end
```
Zero-dimensional arrays. The `Array0` structure provides operations similar to those of [`Bigarray.Genarray`](bigarray.genarray), but specialized to the case of zero-dimensional arrays that only contain a single scalar value. Statically knowing the number of dimensions of the array allows faster operations, and more precise static type-checking.
* **Since** 4.05.0
```
type ('a, 'b, 'c) t
```
The type of zero-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`.
```
val create : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> ('a, 'b, 'c) t
```
`Array0.create kind layout` returns a new Bigarray of zero dimension. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
```
val init : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> 'a -> ('a, 'b, 'c) t
```
`Array0.init kind layout v` behaves like `Array0.create kind layout` except that the element is additionally initialized to the value `v`.
* **Since** 4.12.0
```
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```
Return the kind of the given Bigarray.
```
val layout : ('a, 'b, 'c) t -> 'c Bigarray.layout
```
Return the layout of the given Bigarray.
```
val change_layout : ('a, 'b, 'c) t -> 'd Bigarray.layout -> ('a, 'b, 'd) t
```
`Array0.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a`. No copying of elements is involved: the new array and the original array share the same storage space.
* **Since** 4.06.0
```
val size_in_bytes : ('a, 'b, 'c) t -> int
```
`size_in_bytes a` is `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes).
```
val get : ('a, 'b, 'c) t -> 'a
```
`Array0.get a` returns the only element in `a`.
```
val set : ('a, 'b, 'c) t -> 'a -> unit
```
`Array0.set a x v` stores the value `v` in `a`.
```
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```
Copy the first Bigarray to the second Bigarray. See [`Bigarray.Genarray.blit`](bigarray.genarray#VALblit) for more details.
```
val fill : ('a, 'b, 'c) t -> 'a -> unit
```
Fill the given Bigarray with the given value. See [`Bigarray.Genarray.fill`](bigarray.genarray#VALfill) for more details.
```
val of_value : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> 'a -> ('a, 'b, 'c) t
```
Build a zero-dimensional Bigarray initialized from the given value.
ocaml Module Printexc.Slot Module Printexc.Slot
====================
```
module Slot: sig .. end
```
* **Since** 4.02.0
```
type t = Printexc.backtrace_slot
```
```
val is_raise : t -> bool
```
`is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call.
* **Since** 4.02
```
val is_inline : t -> bool
```
`is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context.
* **Since** 4.04.0
```
val location : t -> Printexc.location option
```
`location slot` returns the location information of the slot, if available, and `None` otherwise.
Some possible reasons for failing to return a location are as follow:
* the slot corresponds to a compiler-inserted raise
* the slot corresponds to a part of the program that has not been compiled with debug information (`-g`)
* **Since** 4.02
```
val name : t -> string option
```
`name slot` returns the name of the function or definition enclosing the location referred to by the slot.
`name slot` returns None if the name is unavailable, which may happen for the same reasons as `location` returning None.
* **Since** 4.11
```
val format : int -> t -> string option
```
`format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`-th element of the backtrace: the `0`-th element is pretty-printed differently than the others.
Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`.
* **Since** 4.02
| programming_docs |
ocaml Module Marshal Module Marshal
==============
```
module Marshal: sig .. end
```
Marshaling of data structures.
This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml.
Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the `Marshal.from_*` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax:
* `(Marshal.from_channel chan : type)`. Anything can happen at run-time if the object in the file does not belong to the given type.
Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the unmarshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as Printexc.to\_string, will still work as expected.
The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with `Marshal.to_channel` and `Marshal.from_channel` must be opened in binary mode, using e.g. `open_out_bin` or `open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows.
```
type extern_flags =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `No\_sharing` | `(*` | Don't preserve sharing | `*)` |
| `|` | `Closures` | `(*` | Send function closures | `*)` |
| `|` | `Compat\_32` | `(*` | Ensure 32-bit compatibility | `*)` |
The flags to the `Marshal.to_*` functions below.
```
val to_channel : out_channel -> 'a -> extern_flags list -> unit
```
`Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms.
If `flags` does not contain `Marshal.No\_sharing`, circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to `Marshal.to_channel` is neither detected nor preserved, though. If `flags` contains `Marshal.No\_sharing`, sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles.
If `flags` does not contain `Marshal.Closures`, marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains `Marshal.Closures`, functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.)
The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one.
If `flags` contains `Marshal.Compat\_32`, marshaling fails when it encounters an integer value outside the range `[-2{^30}, 2{^30}-1]` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain `Marshal.Compat\_32`, integer values outside the range `[-2{^30}, 2{^30}-1]` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The `Mashal.Compat\_32` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform.
* **Raises** `Failure` if `chan` is not in binary mode.
```
val to_bytes : 'a -> extern_flags list -> bytes
```
`Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for [`Marshal.to_channel`](marshal#VALto_channel).
* **Since** 4.02.0
```
val to_string : 'a -> extern_flags list -> string
```
Same as `to_bytes` but return the result as a string instead of a byte sequence.
```
val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int
```
`Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised.
```
val from_channel : in_channel -> 'a
```
`Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value.
* **Raises**
+ `End_of_file` if `chan` is already at the end of the file.
+ `Failure` if the end of the file is reached during unmarshalling itself or if `chan` is not in binary mode.
```
val from_bytes : bytes -> int -> 'a
```
`Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](marshal#VALfrom_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. The byte sequence is not mutated.
* **Since** 4.02.0
```
val from_string : string -> int -> 'a
```
Same as `from_bytes` but take a string as argument instead of a byte sequence.
```
val header_size : int
```
The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. [`Marshal.header_size`](marshal#VALheader_size) is the size, in bytes, of the header. [`Marshal.data_size`](marshal#VALdata_size)`buff ofs` is the size, in bytes, of the data part, assuming a valid header is stored in `buff` starting at position `ofs`. Finally, [`Marshal.total_size`](marshal#VALtotal_size) `buff ofs` is the total size, in bytes, of the marshaled value. Both [`Marshal.data_size`](marshal#VALdata_size) and [`Marshal.total_size`](marshal#VALtotal_size) raise `Failure` if `buff`, `ofs` does not contain a valid header.
To read the byte representation of a marshaled value into a byte sequence, the program needs to read first [`Marshal.header_size`](marshal#VALheader_size) bytes into the sequence, then determine the length of the remainder of the representation using [`Marshal.data_size`](marshal#VALdata_size), make sure the sequence is large enough to hold the remaining data, then read it, and finally call [`Marshal.from_bytes`](marshal#VALfrom_bytes) to unmarshal the value.
```
val data_size : bytes -> int -> int
```
See [`Marshal.header_size`](marshal#VALheader_size).
```
val total_size : bytes -> int -> int
```
See [`Marshal.header_size`](marshal#VALheader_size).
ocaml Module MoreLabels.Hashtbl Module MoreLabels.Hashtbl
=========================
```
module Hashtbl: sig .. end
```
Hash tables and hash functions.
Hash tables are hashed association tables, with in-place modification.
**Unsynchronized accesses**
Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
Generic interface
-----------------
```
type ('a, 'b) t = ('a, 'b) Hashtbl.t
```
The type of hash tables from type `'a` to type `'b`.
```
val create : ?random:bool -> int -> ('a, 'b) t
```
`Hashtbl.create n` creates a new, empty hash table, with initial size `n`. For best results, `n` should be on the order of the expected number of elements that will be in the table. The table grows as needed, so `n` is just an initial guess.
The optional `~random` parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of `Hashtbl.create` or deterministic over all executions.
A hash table that is created with `~random` set to `false` uses a fixed hash function ([`MoreLabels.Hashtbl.hash`](morelabels.hashtbl#VALhash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.
A hash table that is created with `~random` set to `true` uses the seeded hash function [`MoreLabels.Hashtbl.seeded_hash`](morelabels.hashtbl#VALseeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`MoreLabels.Hashtbl.fold`](morelabels.hashtbl#VALfold) or [`MoreLabels.Hashtbl.iter`](morelabels.hashtbl#VALiter) is no longer deterministic: elements are enumerated in different orders at different runs of the program.
If no `~random` parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling [`MoreLabels.Hashtbl.randomize`](morelabels.hashtbl#VALrandomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable.
* **Before 4.00.0** the `~random` parameter was not present and all hash tables were created in non-randomized mode.
```
val clear : ('a, 'b) t -> unit
```
Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size.
```
val reset : ('a, 'b) t -> unit
```
Empty a hash table and shrink the size of the bucket table to its initial size.
* **Since** 4.00.0
```
val copy : ('a, 'b) t -> ('a, 'b) t
```
Return a copy of the given hashtable.
```
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
```
`Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`MoreLabels.Hashtbl.remove`](morelabels.hashtbl#VALremove)`tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.)
```
val find : ('a, 'b) t -> 'a -> 'b
```
`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not\_found` if no such binding exists.
```
val find_opt : ('a, 'b) t -> 'a -> 'b option
```
`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists.
* **Since** 4.05
```
val find_all : ('a, 'b) t -> 'a -> 'b list
```
`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.
```
val mem : ('a, 'b) t -> 'a -> bool
```
`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`.
```
val remove : ('a, 'b) t -> 'a -> unit
```
`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`.
```
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
```
`Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`MoreLabels.Hashtbl.remove`](morelabels.hashtbl#VALremove)`tbl key` followed by [`MoreLabels.Hashtbl.add`](morelabels.hashtbl#VALadd)`tbl key data`.
```
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
```
`Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`.
The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by `f` during the iteration.
```
val filter_map_inplace : f:(key:'a -> data:'b -> 'b option) -> ('a, 'b) t -> unit
```
`Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`.
Other comments for [`MoreLabels.Hashtbl.iter`](morelabels.hashtbl#VALiter) apply as well.
* **Since** 4.03.0
```
val fold : f:(key:'a -> data:'b -> 'c -> 'c) -> ('a, 'b) t -> init:'c -> 'c
```
`Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`.
The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.
The behavior is not specified if the hash table is modified by `f` during the iteration.
```
val length : ('a, 'b) t -> int
```
`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument.
```
val randomize : unit -> unit
```
After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`MoreLabels.Hashtbl.create`](morelabels.hashtbl#VALcreate) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable.
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`MoreLabels.Hashtbl.create`](morelabels.hashtbl#VALcreate) call `Hashtbl.randomize()` at initialization time before any domains are created.
Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`MoreLabels.Hashtbl.create`](morelabels.hashtbl#VALcreate). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`.
* **Since** 4.00.0
```
val is_randomized : unit -> bool
```
Return `true` if the tables are currently created in randomized mode by default, `false` otherwise.
* **Since** 4.03.0
```
val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t
```
Return a copy of the given hashtable. Unlike [`MoreLabels.Hashtbl.copy`](morelabels.hashtbl#VALcopy), [`MoreLabels.Hashtbl.rebuild`](morelabels.hashtbl#VALrebuild)`h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`MoreLabels.Hashtbl.create`](morelabels.hashtbl#VALcreate) for more information.
[`MoreLabels.Hashtbl.rebuild`](morelabels.hashtbl#VALrebuild) can safely be used to import a hash table built by an old version of the [`MoreLabels.Hashtbl`](morelabels.hashtbl) module, then marshaled to persistent storage. After unmarshaling, apply [`MoreLabels.Hashtbl.rebuild`](morelabels.hashtbl#VALrebuild) to produce a hash table for the current version of the [`MoreLabels.Hashtbl`](morelabels.hashtbl) module.
* **Since** 4.12.0
```
type statistics = Hashtbl.statistics = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `num\_bindings : `int`;` | `(*` | Number of bindings present in the table. Same value as returned by [`MoreLabels.Hashtbl.length`](morelabels.hashtbl#VALlength). | `*)` |
| | `num\_buckets : `int`;` | `(*` | Number of buckets in the table. | `*)` |
| | `max\_bucket\_length : `int`;` | `(*` | Maximal number of bindings per bucket. | `*)` |
| | `bucket\_histogram : `int array`;` | `(*` | Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. | `*)` |
`}` * **Since** 4.00.0
```
val stats : ('a, 'b) t -> statistics
```
`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size.
* **Since** 4.00.0
Hash tables and Sequences
-------------------------
```
val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t
```
Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.
The behavior is not specified if the hash table is modified during the iteration.
* **Since** 4.07
```
val to_seq_keys : ('a, 'b) t -> 'a Seq.t
```
Same as `Seq.map fst (to_seq m)`
* **Since** 4.07
```
val to_seq_values : ('a, 'b) t -> 'b Seq.t
```
Same as `Seq.map snd (to_seq m)`
* **Since** 4.07
```
val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
```
Add the given bindings to the table, using [`MoreLabels.Hashtbl.add`](morelabels.hashtbl#VALadd)
* **Since** 4.07
```
val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
```
Add the given bindings to the table, using [`MoreLabels.Hashtbl.replace`](morelabels.hashtbl#VALreplace)
* **Since** 4.07
```
val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t
```
Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`MoreLabels.Hashtbl.replace_seq`](morelabels.hashtbl#VALreplace_seq), which means that if two pairs have the same key, only the latest one will appear in the table.
* **Since** 4.07
Functorial interface
--------------------
The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.
For instance, one might want to specialize a table for integer keys:
```
module IntHash =
struct
type t = int
let equal i j = i=j
let hash i = i land max_int
end
module IntHashtbl = Hashtbl.Make(IntHash)
let h = IntHashtbl.create 17 in
IntHashtbl.add h 12 "hello"
```
This creates a new module `IntHashtbl`, with a new type `'a
IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`.
Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`.
```
module type HashedType = sig .. end
```
The input signature of the functor [`MoreLabels.Hashtbl.Make`](morelabels.hashtbl.make).
```
module type S = sig .. end
```
The output signature of the functor [`MoreLabels.Hashtbl.Make`](morelabels.hashtbl.make).
```
module Make: functor (H : HashedType) -> S
with type key = H.t
and type 'a t = 'a Hashtbl.Make(H).t
```
Functor building an implementation of the hashtable structure.
```
module type SeededHashedType = sig .. end
```
The input signature of the functor [`MoreLabels.Hashtbl.MakeSeeded`](morelabels.hashtbl.makeseeded).
```
module type SeededS = sig .. end
```
The output signature of the functor [`MoreLabels.Hashtbl.MakeSeeded`](morelabels.hashtbl.makeseeded).
```
module MakeSeeded: functor (H : SeededHashedType) -> SeededS
with type key = H.t
and type 'a t = 'a Hashtbl.MakeSeeded(H).t
```
Functor building an implementation of the hashtable structure.
The polymorphic hash functions
------------------------------
```
val hash : 'a -> int
```
`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures.
```
val seeded_hash : int -> 'a -> int
```
A variant of [`MoreLabels.Hashtbl.hash`](morelabels.hashtbl#VALhash) that is further parameterized by an integer seed.
* **Since** 4.00.0
```
val hash_param : int -> int -> 'a -> int
```
`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`MoreLabels.Hashtbl.hash`](morelabels.hashtbl#VALhash) and [`MoreLabels.Hashtbl.seeded_hash`](morelabels.hashtbl#VALseeded_hash) take `meaningful = 10` and `total = 100`.
```
val seeded_hash_param : int -> int -> int -> 'a -> int
```
A variant of [`MoreLabels.Hashtbl.hash_param`](morelabels.hashtbl#VALhash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`.
* **Since** 4.00.0
| programming_docs |
ocaml Index of values Index of values
===============
| |
| --- |
| |
| [( \* )](stdlib#VAL(%20*%20)) [[Stdlib](stdlib)] | Integer multiplication. |
| [( \*\* )](stdlib#VAL(%20**%20)) [[Stdlib](stdlib)] | Exponentiation. |
| [( \*. )](stdlib#VAL(%20*.%20)) [[Stdlib](stdlib)] | Floating-point multiplication. |
| [(!)](stdlib#VAL(!)) [[Stdlib](stdlib)] | `!r` returns the current contents of reference `r`. |
| [(!=)](stdlib#VAL(!=)) [[Stdlib](stdlib)] | Negation of [`(==)`](stdlib#VAL(==)). |
| [(&&)](bool#VAL(&&)) [[Bool](bool)] | `e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. |
| [(&&)](stdlib#VAL(&&)) [[Stdlib](stdlib)] | The boolean 'and'. |
| [(+)](stdlib#VAL(+)) [[Stdlib](stdlib)] | Integer addition. |
| [(+.)](stdlib#VAL(+.)) [[Stdlib](stdlib)] | Floating-point addition. |
| [(-)](stdlib#VAL(-)) [[Stdlib](stdlib)] | Integer subtraction. |
| [(-.)](stdlib#VAL(-.)) [[Stdlib](stdlib)] | Floating-point subtraction. |
| [(/)](stdlib#VAL(/)) [[Stdlib](stdlib)] | Integer division. |
| [(/.)](stdlib#VAL(/.)) [[Stdlib](stdlib)] | Floating-point division. |
| [(:=)](stdlib#VAL(:=)) [[Stdlib](stdlib)] | `r := a` stores the value of `a` in reference `r`. |
| [(<)](#) [[Stdlib](stdlib)] | See [`(>=)`](#). |
| [(<=)](#) [[Stdlib](stdlib)] | See [`(>=)`](#). |
| [(<>)](#) [[Stdlib](stdlib)] | Negation of [`(=)`](stdlib#VAL(=)). |
| [(=)](stdlib#VAL(=)) [[Stdlib](stdlib)] | `e1 = e2` tests for structural equality of `e1` and `e2`. |
| [(==)](stdlib#VAL(==)) [[Stdlib](stdlib)] | `e1 == e2` tests for physical equality of `e1` and `e2`. |
| [(>)](#) [[Stdlib](stdlib)] | See [`(>=)`](#). |
| [(>=)](#) [[Stdlib](stdlib)] | Structural ordering functions. |
| [(@)](stdlib#VAL(@)) [[Stdlib](stdlib)] | List concatenation. |
| [(@@)](stdlib#VAL(@@)) [[Stdlib](stdlib)] | Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. |
| [(^)](#) [[Stdlib](stdlib)] | String concatenation. |
| [(^^)](#) [[Stdlib](stdlib)] | `f1 ^^ f2` catenates format strings `f1` and `f2`. |
| [(asr)](stdlib#VAL(asr)) [[Stdlib](stdlib)] | `n asr m` shifts `n` to the right by `m` bits. |
| [(land)](stdlib#VAL(land)) [[Stdlib](stdlib)] | Bitwise logical and. |
| [(lor)](stdlib#VAL(lor)) [[Stdlib](stdlib)] | Bitwise logical or. |
| [(lsl)](stdlib#VAL(lsl)) [[Stdlib](stdlib)] | `n lsl m` shifts `n` to the left by `m` bits. |
| [(lsr)](stdlib#VAL(lsr)) [[Stdlib](stdlib)] | `n lsr m` shifts `n` to the right by `m` bits. |
| [(lxor)](stdlib#VAL(lxor)) [[Stdlib](stdlib)] | Bitwise logical exclusive or. |
| [(mod)](stdlib#VAL(mod)) [[Stdlib](stdlib)] | Integer remainder. |
| [(|>)](#) [[Stdlib](stdlib)] | Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. |
| [(||)](#) [[Bool](bool)] | `e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. |
| [(||)](#) [[Stdlib](stdlib)] | The boolean 'or'. |
| [(~+)](stdlib#VAL(~+)) [[Stdlib](stdlib)] | Unary addition. |
| [(~+.)](stdlib#VAL(~+.)) [[Stdlib](stdlib)] | Unary addition. |
| [(~-)](stdlib#VAL(~-)) [[Stdlib](stdlib)] | Unary negation. |
| [(~-.)](stdlib#VAL(~-.)) [[Stdlib](stdlib)] | Unary negation. |
| [\_\_FILE\_\_](stdlib#VAL__FILE__) [[Stdlib](stdlib)] | `__FILE__` returns the name of the file currently being parsed by the compiler. |
| [\_\_FUNCTION\_\_](stdlib#VAL__FUNCTION__) [[Stdlib](stdlib)] | `__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes. |
| [\_\_LINE\_OF\_\_](stdlib#VAL__LINE_OF__) [[Stdlib](stdlib)] | `__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler. |
| [\_\_LINE\_\_](stdlib#VAL__LINE__) [[Stdlib](stdlib)] | `__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler. |
| [\_\_LOC\_OF\_\_](stdlib#VAL__LOC_OF__) [[Stdlib](stdlib)] | `__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". |
| [\_\_LOC\_\_](stdlib#VAL__LOC__) [[Stdlib](stdlib)] | `__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". |
| [\_\_MODULE\_\_](stdlib#VAL__MODULE__) [[Stdlib](stdlib)] | `__MODULE__` returns the module name of the file being parsed by the compiler. |
| [\_\_POS\_OF\_\_](stdlib#VAL__POS_OF__) [[Stdlib](stdlib)] | `__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. |
| [\_\_POS\_\_](stdlib#VAL__POS__) [[Stdlib](stdlib)] | `__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. |
| [\_exit](unixlabels#VAL_exit) [[UnixLabels](unixlabels)] | Terminate the calling process immediately, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. |
| [\_exit](unix#VAL_exit) [[Unix](unix)] | Terminate the calling process immediately, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. |
| A |
| [abs](nativeint#VALabs) [[Nativeint](nativeint)] | `abs x` is the absolute value of `x`. |
| [abs](int64#VALabs) [[Int64](int64)] | `abs x` is the absolute value of `x`. |
| [abs](int32#VALabs) [[Int32](int32)] | `abs x` is the absolute value of `x`. |
| [abs](int#VALabs) [[Int](int)] | `abs x` is the absolute value of `x`. |
| [abs](float#VALabs) [[Float](float)] | `abs f` returns the absolute value of `f`. |
| [abs](stdlib#VALabs) [[Stdlib](stdlib)] | `abs x` is the absolute value of `x`. |
| [abs\_float](stdlib#VALabs_float) [[Stdlib](stdlib)] | `abs_float f` returns the absolute value of `f`. |
| [abstract\_tag](obj#VALabstract_tag) [[Obj](obj)] | |
| [accept](unixlabels#VALaccept) [[UnixLabels](unixlabels)] | Accept connections on the given socket. |
| [accept](unix#VALaccept) [[Unix](unix)] | Accept connections on the given socket. |
| [access](unixlabels#VALaccess) [[UnixLabels](unixlabels)] | Check that the process has the given permissions over the named file. |
| [access](unix#VALaccess) [[Unix](unix)] | Check that the process has the given permissions over the named file. |
| [acos](float#VALacos) [[Float](float)] | Arc cosine. |
| [acos](stdlib#VALacos) [[Stdlib](stdlib)] | Arc cosine. |
| [acosh](float#VALacosh) [[Float](float)] | Hyperbolic arc cosine. |
| [acosh](stdlib#VALacosh) [[Stdlib](stdlib)] | Hyperbolic arc cosine. |
| [acquire](semaphore.binary#VALacquire) [[Semaphore.Binary](semaphore.binary)] | `acquire s` blocks the calling thread until the semaphore `s` has value 1 (is available), then atomically sets it to 0 and returns. |
| [acquire](semaphore.counting#VALacquire) [[Semaphore.Counting](semaphore.counting)] | `acquire s` blocks the calling thread until the value of semaphore `s` is not zero, then atomically decrements the value of `s` and returns. |
| [adapt\_filename](dynlink#VALadapt_filename) [[Dynlink](dynlink)] | In bytecode, the identity function. |
| [add](weak.s#VALadd) [[Weak.S](weak.s)] | `add t x` adds `x` to `t`. |
| [add](set.s#VALadd) [[Set.S](set.s)] | `add x s` returns a set containing all elements of `s`, plus `x`. |
| [add](queue#VALadd) [[Queue](queue)] | `add x q` adds the element `x` at the end of the queue `q`. |
| [add](nativeint#VALadd) [[Nativeint](nativeint)] | Addition. |
| [add](morelabels.set.s#VALadd) [[MoreLabels.Set.S](morelabels.set.s)] | `add x s` returns a set containing all elements of `s`, plus `x`. |
| [add](morelabels.map.s#VALadd) [[MoreLabels.Map.S](morelabels.map.s)] | `add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. |
| [add](morelabels.hashtbl.seededs#VALadd) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [add](morelabels.hashtbl.s#VALadd) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [add](morelabels.hashtbl#VALadd) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. |
| [add](map.s#VALadd) [[Map.S](map.s)] | `add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. |
| [add](int64#VALadd) [[Int64](int64)] | Addition. |
| [add](int32#VALadd) [[Int32](int32)] | Addition. |
| [add](int#VALadd) [[Int](int)] | `add x y` is the addition `x + y`. |
| [add](hashtbl.seededs#VALadd) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [add](hashtbl.s#VALadd) [[Hashtbl.S](hashtbl.s)] | |
| [add](hashtbl#VALadd) [[Hashtbl](hashtbl)] | `Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. |
| [add](float#VALadd) [[Float](float)] | Floating-point addition. |
| [add](ephemeron.kn.bucket#VALadd) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | Add an ephemeron to the bucket. |
| [add](ephemeron.k2.bucket#VALadd) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | Add an ephemeron to the bucket. |
| [add](ephemeron.k1.bucket#VALadd) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | Add an ephemeron to the bucket. |
| [add](ephemeron.seededs#VALadd) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [add](ephemeron.s#VALadd) [[Ephemeron.S](ephemeron.s)] | |
| [add](complex#VALadd) [[Complex](complex)] | Addition |
| [add\_buffer](buffer#VALadd_buffer) [[Buffer](buffer)] | `add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. |
| [add\_bytes](buffer#VALadd_bytes) [[Buffer](buffer)] | `add_bytes b s` appends the byte sequence `s` at the end of buffer `b`. |
| [add\_channel](buffer#VALadd_channel) [[Buffer](buffer)] | `add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`. |
| [add\_char](buffer#VALadd_char) [[Buffer](buffer)] | `add_char b c` appends the character `c` at the end of buffer `b`. |
| [add\_in\_char\_set](camlinternalformat#VALadd_in_char_set) [[CamlinternalFormat](camlinternalformat)] | |
| [add\_initializer](camlinternaloo#VALadd_initializer) [[CamlinternalOO](camlinternaloo)] | |
| [add\_int16\_be](buffer#VALadd_int16_be) [[Buffer](buffer)] | `add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`. |
| [add\_int16\_le](buffer#VALadd_int16_le) [[Buffer](buffer)] | `add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`. |
| [add\_int16\_ne](buffer#VALadd_int16_ne) [[Buffer](buffer)] | `add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`. |
| [add\_int32\_be](buffer#VALadd_int32_be) [[Buffer](buffer)] | `add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`. |
| [add\_int32\_le](buffer#VALadd_int32_le) [[Buffer](buffer)] | `add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`. |
| [add\_int32\_ne](buffer#VALadd_int32_ne) [[Buffer](buffer)] | `add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`. |
| [add\_int64\_be](buffer#VALadd_int64_be) [[Buffer](buffer)] | `add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`. |
| [add\_int64\_le](buffer#VALadd_int64_le) [[Buffer](buffer)] | `add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`. |
| [add\_int64\_ne](buffer#VALadd_int64_ne) [[Buffer](buffer)] | `add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`. |
| [add\_int8](buffer#VALadd_int8) [[Buffer](buffer)] | `add_int8 b i` appends a binary signed 8-bit integer `i` to `b`. |
| [add\_offset](obj#VALadd_offset) [[Obj](obj)] | |
| [add\_seq](stack#VALadd_seq) [[Stack](stack)] | Add the elements from the sequence on the top of the stack. |
| [add\_seq](set.s#VALadd_seq) [[Set.S](set.s)] | Add the given elements to the set, in order. |
| [add\_seq](queue#VALadd_seq) [[Queue](queue)] | Add the elements from a sequence to the end of the queue. |
| [add\_seq](morelabels.set.s#VALadd_seq) [[MoreLabels.Set.S](morelabels.set.s)] | Add the given elements to the set, in order. |
| [add\_seq](morelabels.map.s#VALadd_seq) [[MoreLabels.Map.S](morelabels.map.s)] | Add the given bindings to the map, in order. |
| [add\_seq](morelabels.hashtbl.seededs#VALadd_seq) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [add\_seq](morelabels.hashtbl.s#VALadd_seq) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [add\_seq](morelabels.hashtbl#VALadd_seq) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Add the given bindings to the table, using [`MoreLabels.Hashtbl.add`](morelabels.hashtbl#VALadd) |
| [add\_seq](map.s#VALadd_seq) [[Map.S](map.s)] | Add the given bindings to the map, in order. |
| [add\_seq](hashtbl.seededs#VALadd_seq) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [add\_seq](hashtbl.s#VALadd_seq) [[Hashtbl.S](hashtbl.s)] | |
| [add\_seq](hashtbl#VALadd_seq) [[Hashtbl](hashtbl)] | Add the given bindings to the table, using [`Hashtbl.add`](hashtbl#VALadd) |
| [add\_seq](ephemeron.seededs#VALadd_seq) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [add\_seq](ephemeron.s#VALadd_seq) [[Ephemeron.S](ephemeron.s)] | |
| [add\_seq](buffer#VALadd_seq) [[Buffer](buffer)] | Add chars to the buffer |
| [add\_string](buffer#VALadd_string) [[Buffer](buffer)] | `add_string b s` appends the string `s` at the end of buffer `b`. |
| [add\_subbytes](buffer#VALadd_subbytes) [[Buffer](buffer)] | `add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`. |
| [add\_substitute](buffer#VALadd_substitute) [[Buffer](buffer)] | `add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. |
| [add\_substring](buffer#VALadd_substring) [[Buffer](buffer)] | `add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`. |
| [add\_symbolic\_output\_item](format#VALadd_symbolic_output_item) [[Format](format)] | `add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`. |
| [add\_uint16\_be](buffer#VALadd_uint16_be) [[Buffer](buffer)] | `add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`. |
| [add\_uint16\_le](buffer#VALadd_uint16_le) [[Buffer](buffer)] | `add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`. |
| [add\_uint16\_ne](buffer#VALadd_uint16_ne) [[Buffer](buffer)] | `add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`. |
| [add\_uint8](buffer#VALadd_uint8) [[Buffer](buffer)] | `add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`. |
| [add\_utf\_16be\_uchar](buffer#VALadd_utf_16be_uchar) [[Buffer](buffer)] | `add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. |
| [add\_utf\_16le\_uchar](buffer#VALadd_utf_16le_uchar) [[Buffer](buffer)] | `add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. |
| [add\_utf\_8\_uchar](buffer#VALadd_utf_8_uchar) [[Buffer](buffer)] | `add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`. |
| [alarm](unixlabels#VALalarm) [[UnixLabels](unixlabels)] | Schedule a `SIGALRM` signal after the given number of seconds. |
| [alarm](unix#VALalarm) [[Unix](unix)] | Schedule a `SIGALRM` signal after the given number of seconds. |
| [align](arg#VALalign) [[Arg](arg)] | Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. |
| [all\_units](dynlink#VALall_units) [[Dynlink](dynlink)] | Return the list of compilation units that form the main program together with those that have been dynamically loaded via `loadfile` (and not via `loadfile_private`). |
| [allocated\_bytes](gc#VALallocated_bytes) [[Gc](gc)] | Return the number of bytes allocated by this domain and potentially a previous domain. |
| [allow\_only](dynlink#VALallow_only) [[Dynlink](dynlink)] | `allow_only units` sets the list of allowed units to be the intersection of the existing allowed units and the given list of units. |
| [allow\_unsafe\_modules](dynlink#VALallow_unsafe_modules) [[Dynlink](dynlink)] | Govern whether unsafe object files are allowed to be dynamically linked. |
| [always](event#VALalways) [[Event](event)] | `always v` returns an event that is always ready for synchronization. |
| [append](seq#VALappend) [[Seq](seq)] | `append xs ys` is the concatenation of the sequences `xs` and `ys`. |
| [append](listlabels#VALappend) [[ListLabels](listlabels)] | Concatenate two lists. |
| [append](list#VALappend) [[List](list)] | Concatenate two lists. |
| [append](float.arraylabels#VALappend) [[Float.ArrayLabels](float.arraylabels)] | `append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. |
| [append](float.array#VALappend) [[Float.Array](float.array)] | `append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. |
| [append](arraylabels#VALappend) [[ArrayLabels](arraylabels)] | `append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. |
| [append](array#VALappend) [[Array](array)] | `append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. |
| [arg](complex#VALarg) [[Complex](complex)] | Argument. |
| [argv](sys#VALargv) [[Sys](sys)] | The command line arguments given to the process. |
| [array0\_of\_genarray](bigarray#VALarray0_of_genarray) [[Bigarray](bigarray)] | Return the zero-dimensional Bigarray corresponding to the given generic Bigarray. |
| [array1\_of\_genarray](bigarray#VALarray1_of_genarray) [[Bigarray](bigarray)] | Return the one-dimensional Bigarray corresponding to the given generic Bigarray. |
| [array2\_of\_genarray](bigarray#VALarray2_of_genarray) [[Bigarray](bigarray)] | Return the two-dimensional Bigarray corresponding to the given generic Bigarray. |
| [array3\_of\_genarray](bigarray#VALarray3_of_genarray) [[Bigarray](bigarray)] | Return the three-dimensional Bigarray corresponding to the given generic Bigarray. |
| [asin](float#VALasin) [[Float](float)] | Arc sine. |
| [asin](stdlib#VALasin) [[Stdlib](stdlib)] | Arc sine. |
| [asinh](float#VALasinh) [[Float](float)] | Hyperbolic arc sine. |
| [asinh](stdlib#VALasinh) [[Stdlib](stdlib)] | Hyperbolic arc sine. |
| [asprintf](format#VALasprintf) [[Format](format)] | Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. |
| [assoc](listlabels#VALassoc) [[ListLabels](listlabels)] | `assoc a l` returns the value associated with key `a` in the list of pairs `l`. |
| [assoc](list#VALassoc) [[List](list)] | `assoc a l` returns the value associated with key `a` in the list of pairs `l`. |
| [assoc\_opt](listlabels#VALassoc_opt) [[ListLabels](listlabels)] | `assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. |
| [assoc\_opt](list#VALassoc_opt) [[List](list)] | `assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. |
| [assq](listlabels#VALassq) [[ListLabels](listlabels)] | Same as [`ListLabels.assoc`](listlabels#VALassoc), but uses physical equality instead of structural equality to compare keys. |
| [assq](list#VALassq) [[List](list)] | Same as [`List.assoc`](list#VALassoc), but uses physical equality instead of structural equality to compare keys. |
| [assq\_opt](listlabels#VALassq_opt) [[ListLabels](listlabels)] | Same as [`ListLabels.assoc_opt`](listlabels#VALassoc_opt), but uses physical equality instead of structural equality to compare keys. |
| [assq\_opt](list#VALassq_opt) [[List](list)] | Same as [`List.assoc_opt`](list#VALassoc_opt), but uses physical equality instead of structural equality to compare keys. |
| [at\_exit](domain#VALat_exit) [[Domain](domain)] | `at_exit f` registers `f` to be called when the current domain exits. |
| [at\_exit](stdlib#VALat_exit) [[Stdlib](stdlib)] | Register the given function to be called at program termination time. |
| [atan](float#VALatan) [[Float](float)] | Arc tangent. |
| [atan](stdlib#VALatan) [[Stdlib](stdlib)] | Arc tangent. |
| [atan2](float#VALatan2) [[Float](float)] | `atan2 y x` returns the arc tangent of `y /. x`. |
| [atan2](stdlib#VALatan2) [[Stdlib](stdlib)] | `atan2 y x` returns the arc tangent of `y /. x`. |
| [atanh](float#VALatanh) [[Float](float)] | Hyperbolic arc tangent. |
| [atanh](stdlib#VALatanh) [[Stdlib](stdlib)] | Hyperbolic arc tangent. |
| B |
| [backend\_type](sys#VALbackend_type) [[Sys](sys)] | Backend type currently executing the OCaml program. |
| [backtrace\_slots](printexc#VALbacktrace_slots) [[Printexc](printexc)] | Returns the slots of a raw backtrace, or `None` if none of them contain useful information. |
| [backtrace\_slots\_of\_raw\_entry](printexc#VALbacktrace_slots_of_raw_entry) [[Printexc](printexc)] | Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information. |
| [backtrace\_status](printexc#VALbacktrace_status) [[Printexc](printexc)] | `Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not. |
| [basename](filename#VALbasename) [[Filename](filename)] | Split a file name into directory name / base file name. |
| [before\_first\_spawn](domain#VALbefore_first_spawn) [[Domain](domain)] | `before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. |
| [beginning\_of\_input](scanf.scanning#VALbeginning_of_input) [[Scanf.Scanning](scanf.scanning)] | `Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel. |
| [big\_endian](sys#VALbig_endian) [[Sys](sys)] | Whether the machine currently executing the Caml program is big-endian. |
| [bind](unixlabels#VALbind) [[UnixLabels](unixlabels)] | Bind a socket to an address. |
| [bind](unix#VALbind) [[Unix](unix)] | Bind a socket to an address. |
| [bind](result#VALbind) [[Result](result)] | `bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`. |
| [bind](option#VALbind) [[Option](option)] | `bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`. |
| [bindings](morelabels.map.s#VALbindings) [[MoreLabels.Map.S](morelabels.map.s)] | Return the list of all bindings of the given map. |
| [bindings](map.s#VALbindings) [[Map.S](map.s)] | Return the list of all bindings of the given map. |
| [bits](random.state#VALbits) [[Random.State](random.state)] | |
| [bits](random#VALbits) [[Random](random)] | Return 30 random bits in a nonnegative integer. |
| [bits32](random.state#VALbits32) [[Random.State](random.state)] | |
| [bits32](random#VALbits32) [[Random](random)] | `Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](int32#VALmin_int) and [`Int32.max_int`](int32#VALmax_int). |
| [bits64](random.state#VALbits64) [[Random.State](random.state)] | |
| [bits64](random#VALbits64) [[Random](random)] | `Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](int64#VALmin_int) and [`Int64.max_int`](int64#VALmax_int). |
| [bits\_of\_float](int64#VALbits_of_float) [[Int64](int64)] | Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. |
| [bits\_of\_float](int32#VALbits_of_float) [[Int32](int32)] | Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. |
| [blit](weak#VALblit) [[Weak](weak)] | `Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). |
| [blit](string#VALblit) [[String](string)] | `blit src src_pos dst dst_pos len` copies `len` bytes from the string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at character number `dst_pos`. |
| [blit](stringlabels#VALblit) [[StringLabels](stringlabels)] | `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from the string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at character number `dst_pos`. |
| [blit](float.arraylabels#VALblit) [[Float.ArrayLabels](float.arraylabels)] | `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. |
| [blit](float.array#VALblit) [[Float.Array](float.array)] | `blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. |
| [blit](byteslabels#VALblit) [[BytesLabels](byteslabels)] | `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from sequence `src`, starting at index `src_pos`, to sequence `dst`, starting at index `dst_pos`. |
| [blit](bytes#VALblit) [[Bytes](bytes)] | `blit src src_pos dst dst_pos len` copies `len` bytes from sequence `src`, starting at index `src_pos`, to sequence `dst`, starting at index `dst_pos`. |
| [blit](buffer#VALblit) [[Buffer](buffer)] | `Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`. |
| [blit](bigarray.array3#VALblit) [[Bigarray.Array3](bigarray.array3)] | Copy the first Bigarray to the second Bigarray. |
| [blit](bigarray.array2#VALblit) [[Bigarray.Array2](bigarray.array2)] | Copy the first Bigarray to the second Bigarray. |
| [blit](bigarray.array1#VALblit) [[Bigarray.Array1](bigarray.array1)] | Copy the first Bigarray to the second Bigarray. |
| [blit](bigarray.array0#VALblit) [[Bigarray.Array0](bigarray.array0)] | Copy the first Bigarray to the second Bigarray. |
| [blit](bigarray.genarray#VALblit) [[Bigarray.Genarray](bigarray.genarray)] | Copy all elements of a Bigarray in another Bigarray. |
| [blit](arraylabels#VALblit) [[ArrayLabels](arraylabels)] | `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. |
| [blit](array#VALblit) [[Array](array)] | `blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. |
| [blit\_data](obj.ephemeron#VALblit_data) [[Obj.Ephemeron](obj.ephemeron)] | |
| [blit\_key](obj.ephemeron#VALblit_key) [[Obj.Ephemeron](obj.ephemeron)] | |
| [blit\_string](byteslabels#VALblit_string) [[BytesLabels](byteslabels)] | `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. |
| [blit\_string](bytes#VALblit_string) [[Bytes](bytes)] | `blit src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. |
| [bom](uchar#VALbom) [[Uchar](uchar)] | `bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character. |
| [bool](random.state#VALbool) [[Random.State](random.state)] | |
| [bool](random#VALbool) [[Random](random)] | `Random.bool ()` returns `true` or `false` with probability 0.5 each. |
| [bool\_of\_string](stdlib#VALbool_of_string) [[Stdlib](stdlib)] | Same as [`bool_of_string_opt`](stdlib#VALbool_of_string_opt), but raise `Invalid\_argument "bool\_of\_string"` instead of returning `None`. |
| [bool\_of\_string\_opt](stdlib#VALbool_of_string_opt) [[Stdlib](stdlib)] | Convert the given string to a boolean. |
| [bounded\_full\_split](str#VALbounded_full_split) [[Str](str)] | Same as [`Str.bounded_split_delim`](str#VALbounded_split_delim), but returns the delimiters as well as the substrings contained between delimiters. |
| [bounded\_split](str#VALbounded_split) [[Str](str)] | Same as [`Str.split`](str#VALsplit), but splits into at most `n` substrings, where `n` is the extra integer parameter. |
| [bounded\_split\_delim](str#VALbounded_split_delim) [[Str](str)] | Same as [`Str.bounded_split`](str#VALbounded_split), but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. |
| [bprintf](printf#VALbprintf) [[Printf](printf)] | Same as [`Printf.fprintf`](printf#VALfprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](buffer)). |
| [broadcast](condition#VALbroadcast) [[Condition](condition)] | `broadcast c` wakes up all threads waiting on the condition variable `c`. |
| [bscanf](scanf#VALbscanf) [[Scanf](scanf)] | |
| [bscanf\_format](scanf#VALbscanf_format) [[Scanf](scanf)] | `bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value. |
| [bscanf\_opt](scanf#VALbscanf_opt) [[Scanf](scanf)] | Same as [`Scanf.bscanf`](scanf#VALbscanf), but returns `None` in case of scanning failure. |
| [bufput\_acc](camlinternalformat#VALbufput_acc) [[CamlinternalFormat](camlinternalformat)] | |
| [bytes](digest#VALbytes) [[Digest](digest)] | Return the digest of the given byte sequence. |
| C |
| [c\_layout](bigarray#VALc_layout) [[Bigarray](bigarray)] | |
| [capitalize\_ascii](string#VALcapitalize_ascii) [[String](string)] | `capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. |
| [capitalize\_ascii](stringlabels#VALcapitalize_ascii) [[StringLabels](stringlabels)] | `capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. |
| [capitalize\_ascii](byteslabels#VALcapitalize_ascii) [[BytesLabels](byteslabels)] | Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. |
| [capitalize\_ascii](bytes#VALcapitalize_ascii) [[Bytes](bytes)] | Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. |
| [cardinal](set.s#VALcardinal) [[Set.S](set.s)] | Return the number of elements of a set. |
| [cardinal](morelabels.set.s#VALcardinal) [[MoreLabels.Set.S](morelabels.set.s)] | Return the number of elements of a set. |
| [cardinal](morelabels.map.s#VALcardinal) [[MoreLabels.Map.S](morelabels.map.s)] | Return the number of bindings of a map. |
| [cardinal](map.s#VALcardinal) [[Map.S](map.s)] | Return the number of bindings of a map. |
| [cat](string#VALcat) [[String](string)] | `cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). |
| [cat](stringlabels#VALcat) [[StringLabels](stringlabels)] | `cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). |
| [cat](byteslabels#VALcat) [[BytesLabels](byteslabels)] | `cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. |
| [cat](bytes#VALcat) [[Bytes](bytes)] | `cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. |
| [catch](printexc#VALcatch) [[Printexc](printexc)] | `Printexc.catch fn x` is similar to [`Printexc.print`](printexc#VALprint), but aborts the program with exit code 2 after printing the uncaught exception.
|
| [catch\_break](sys#VALcatch_break) [[Sys](sys)] | `catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. |
| [cbrt](float#VALcbrt) [[Float](float)] | Cube root. |
| [ceil](float#VALceil) [[Float](float)] | Round above to an integer value. |
| [ceil](stdlib#VALceil) [[Stdlib](stdlib)] | Round above to an integer value. |
| [change\_layout](bigarray.array3#VALchange_layout) [[Bigarray.Array3](bigarray.array3)] | `Array3.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). |
| [change\_layout](bigarray.array2#VALchange_layout) [[Bigarray.Array2](bigarray.array2)] | `Array2.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). |
| [change\_layout](bigarray.array1#VALchange_layout) [[Bigarray.Array1](bigarray.array1)] | `Array1.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimension as `a`). |
| [change\_layout](bigarray.array0#VALchange_layout) [[Bigarray.Array0](bigarray.array0)] | `Array0.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a`. |
| [change\_layout](bigarray.genarray#VALchange_layout) [[Bigarray.Genarray](bigarray.genarray)] | `Genarray.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). |
| [channel](digest#VALchannel) [[Digest](digest)] | If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End\_of\_file` if end-of-file is reached before `len` characters are read. |
| [char](bigarray#VALchar) [[Bigarray](bigarray)] | As shown by the types of the values above, Bigarrays of kind `float32_elt` and `float64_elt` are accessed using the OCaml type `float`. |
| [char\_of\_iconv](camlinternalformat#VALchar_of_iconv) [[CamlinternalFormat](camlinternalformat)] | |
| [char\_of\_int](stdlib#VALchar_of_int) [[Stdlib](stdlib)] | Return the character with the given ASCII code. |
| [chdir](unixlabels#VALchdir) [[UnixLabels](unixlabels)] | Change the process working directory. |
| [chdir](unix#VALchdir) [[Unix](unix)] | Change the process working directory. |
| [chdir](sys#VALchdir) [[Sys](sys)] | Change the current working directory of the process. |
| [check](weak#VALcheck) [[Weak](weak)] | `Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. |
| [check\_data](obj.ephemeron#VALcheck_data) [[Obj.Ephemeron](obj.ephemeron)] | |
| [check\_geometry](format#VALcheck_geometry) [[Format](format)] | Check if the formatter geometry is valid: `1 < max_indent < margin` |
| [check\_key](obj.ephemeron#VALcheck_key) [[Obj.Ephemeron](obj.ephemeron)] | |
| [check\_suffix](filename#VALcheck_suffix) [[Filename](filename)] | `check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`. |
| [chmod](unixlabels#VALchmod) [[UnixLabels](unixlabels)] | Change the permissions of the named file. |
| [chmod](unix#VALchmod) [[Unix](unix)] | Change the permissions of the named file. |
| [choose](event#VALchoose) [[Event](event)] | `choose evl` returns the event that is the alternative of all the events in the list `evl`. |
| [choose](set.s#VALchoose) [[Set.S](set.s)] | Return one element of the given set, or raise `Not\_found` if the set is empty. |
| [choose](morelabels.set.s#VALchoose) [[MoreLabels.Set.S](morelabels.set.s)] | Return one element of the given set, or raise `Not\_found` if the set is empty. |
| [choose](morelabels.map.s#VALchoose) [[MoreLabels.Map.S](morelabels.map.s)] | Return one binding of the given map, or raise `Not\_found` if the map is empty. |
| [choose](map.s#VALchoose) [[Map.S](map.s)] | Return one binding of the given map, or raise `Not\_found` if the map is empty. |
| [choose\_opt](set.s#VALchoose_opt) [[Set.S](set.s)] | Return one element of the given set, or `None` if the set is empty. |
| [choose\_opt](morelabels.set.s#VALchoose_opt) [[MoreLabels.Set.S](morelabels.set.s)] | Return one element of the given set, or `None` if the set is empty. |
| [choose\_opt](morelabels.map.s#VALchoose_opt) [[MoreLabels.Map.S](morelabels.map.s)] | Return one binding of the given map, or `None` if the map is empty. |
| [choose\_opt](map.s#VALchoose_opt) [[Map.S](map.s)] | Return one binding of the given map, or `None` if the map is empty. |
| [chop\_extension](filename#VALchop_extension) [[Filename](filename)] | Same as [`Filename.remove_extension`](filename#VALremove_extension), but raise `Invalid\_argument` if the given name has an empty extension. |
| [chop\_suffix](filename#VALchop_suffix) [[Filename](filename)] | `chop_suffix name suff` removes the suffix `suff` from the filename `name`. |
| [chop\_suffix\_opt](filename#VALchop_suffix_opt) [[Filename](filename)] | `chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix. |
| [chown](unixlabels#VALchown) [[UnixLabels](unixlabels)] | Change the owner uid and owner gid of the named file. |
| [chown](unix#VALchown) [[Unix](unix)] | Change the owner uid and owner gid of the named file. |
| [chr](char#VALchr) [[Char](char)] | Return the character with the given ASCII code. |
| [chroot](unixlabels#VALchroot) [[UnixLabels](unixlabels)] | Change the process root directory. |
| [chroot](unix#VALchroot) [[Unix](unix)] | Change the process root directory. |
| [classify\_float](float#VALclassify_float) [[Float](float)] | Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. |
| [classify\_float](stdlib#VALclassify_float) [[Stdlib](stdlib)] | Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. |
| [clean](ephemeron.seededs#VALclean) [[Ephemeron.SeededS](ephemeron.seededs)] | remove all dead bindings. |
| [clean](ephemeron.s#VALclean) [[Ephemeron.S](ephemeron.s)] | remove all dead bindings. |
| [clear](weak.s#VALclear) [[Weak.S](weak.s)] | Remove all elements from the table. |
| [clear](stack#VALclear) [[Stack](stack)] | Discard all elements from a stack. |
| [clear](queue#VALclear) [[Queue](queue)] | Discard all elements from a queue. |
| [clear](morelabels.hashtbl.seededs#VALclear) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [clear](morelabels.hashtbl.s#VALclear) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [clear](morelabels.hashtbl#VALclear) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Empty a hash table. |
| [clear](hashtbl.seededs#VALclear) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [clear](hashtbl.s#VALclear) [[Hashtbl.S](hashtbl.s)] | |
| [clear](hashtbl#VALclear) [[Hashtbl](hashtbl)] | Empty a hash table. |
| [clear](ephemeron.kn.bucket#VALclear) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | Remove all ephemerons from the bucket. |
| [clear](ephemeron.k2.bucket#VALclear) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | Remove all ephemerons from the bucket. |
| [clear](ephemeron.k1.bucket#VALclear) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | Remove all ephemerons from the bucket. |
| [clear](ephemeron.seededs#VALclear) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [clear](ephemeron.s#VALclear) [[Ephemeron.S](ephemeron.s)] | |
| [clear](buffer#VALclear) [[Buffer](buffer)] | Empty the buffer. |
| [clear\_close\_on\_exec](unixlabels#VALclear_close_on_exec) [[UnixLabels](unixlabels)] | Clear the ``close-on-exec'' flag on the given descriptor. |
| [clear\_close\_on\_exec](unix#VALclear_close_on_exec) [[Unix](unix)] | Clear the ``close-on-exec'' flag on the given descriptor. |
| [clear\_nonblock](unixlabels#VALclear_nonblock) [[UnixLabels](unixlabels)] | Clear the ``non-blocking'' flag on the given descriptor. |
| [clear\_nonblock](unix#VALclear_nonblock) [[Unix](unix)] | Clear the ``non-blocking'' flag on the given descriptor. |
| [clear\_parser](parsing#VALclear_parser) [[Parsing](parsing)] | Empty the parser stack. |
| [clear\_symbolic\_output\_buffer](format#VALclear_symbolic_output_buffer) [[Format](format)] | `clear_symbolic_output_buffer sob` resets buffer `sob`. |
| [close](unixlabels#VALclose) [[UnixLabels](unixlabels)] | Close a file descriptor. |
| [close](unix#VALclose) [[Unix](unix)] | Close a file descriptor. |
| [close](out_channel#VALclose) [[Out\_channel](out_channel)] | Close the given channel, flushing all buffered write operations. |
| [close](in_channel#VALclose) [[In\_channel](in_channel)] | Close the given channel. |
| [close\_box](format#VALclose_box) [[Format](format)] | Closes the most recently open pretty-printing box. |
| [close\_in](scanf.scanning#VALclose_in) [[Scanf.Scanning](scanf.scanning)] | Closes the [`in_channel`](stdlib#TYPEin_channel) associated with the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel. |
| [close\_in](stdlib#VALclose_in) [[Stdlib](stdlib)] | Close the given channel. |
| [close\_in\_noerr](stdlib#VALclose_in_noerr) [[Stdlib](stdlib)] | Same as `close_in`, but ignore all errors. |
| [close\_noerr](out_channel#VALclose_noerr) [[Out\_channel](out_channel)] | Same as [`Out\_channel.close`](out_channel#VALclose), but ignore all errors. |
| [close\_noerr](in_channel#VALclose_noerr) [[In\_channel](in_channel)] | Same as [`In\_channel.close`](in_channel#VALclose), but ignore all errors. |
| [close\_out](stdlib#VALclose_out) [[Stdlib](stdlib)] | Close the given channel, flushing all buffered write operations. |
| [close\_out\_noerr](stdlib#VALclose_out_noerr) [[Stdlib](stdlib)] | Same as `close_out`, but ignore all errors. |
| [close\_process](unixlabels#VALclose_process) [[UnixLabels](unixlabels)] | Close channels opened by [`UnixLabels.open_process`](unixlabels#VALopen_process), wait for the associated command to terminate, and return its termination status. |
| [close\_process](unix#VALclose_process) [[Unix](unix)] | Close channels opened by [`Unix.open_process`](unix#VALopen_process), wait for the associated command to terminate, and return its termination status. |
| [close\_process\_full](unixlabels#VALclose_process_full) [[UnixLabels](unixlabels)] | Close channels opened by [`UnixLabels.open_process_full`](unixlabels#VALopen_process_full), wait for the associated command to terminate, and return its termination status. |
| [close\_process\_full](unix#VALclose_process_full) [[Unix](unix)] | Close channels opened by [`Unix.open_process_full`](unix#VALopen_process_full), wait for the associated command to terminate, and return its termination status. |
| [close\_process\_in](unixlabels#VALclose_process_in) [[UnixLabels](unixlabels)] | Close channels opened by [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in), wait for the associated command to terminate, and return its termination status. |
| [close\_process\_in](unix#VALclose_process_in) [[Unix](unix)] | Close channels opened by [`Unix.open_process_in`](unix#VALopen_process_in), wait for the associated command to terminate, and return its termination status. |
| [close\_process\_out](unixlabels#VALclose_process_out) [[UnixLabels](unixlabels)] | Close channels opened by [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out), wait for the associated command to terminate, and return its termination status. |
| [close\_process\_out](unix#VALclose_process_out) [[Unix](unix)] | Close channels opened by [`Unix.open_process_out`](unix#VALopen_process_out), wait for the associated command to terminate, and return its termination status. |
| [close\_stag](format#VALclose_stag) [[Format](format)] | `pp_close_stag ppf ()` closes the most recently opened semantic tag `t`. |
| [close\_tbox](format#VALclose_tbox) [[Format](format)] | Closes the most recently opened tabulation box. |
| [closedir](unixlabels#VALclosedir) [[UnixLabels](unixlabels)] | Close a directory descriptor. |
| [closedir](unix#VALclosedir) [[Unix](unix)] | Close a directory descriptor. |
| [closure\_tag](obj#VALclosure_tag) [[Obj](obj)] | |
| [code](char#VALcode) [[Char](char)] | Return the ASCII code of the argument. |
| [combine](listlabels#VALcombine) [[ListLabels](listlabels)] | Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. |
| [combine](list#VALcombine) [[List](list)] | Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. |
| [combine](arraylabels#VALcombine) [[ArrayLabels](arraylabels)] | `combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. |
| [combine](array#VALcombine) [[Array](array)] | `combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. |
| [command](sys#VALcommand) [[Sys](sys)] | Execute the given shell command and return its exit code. |
| [compact](gc#VALcompact) [[Gc](gc)] | Perform a full major collection and compact the heap. |
| [compare](unit#VALcompare) [[Unit](unit)] | `compare u1 u2` is `0`. |
| [compare](uchar#VALcompare) [[Uchar](uchar)] | `compare u u'` is `Stdlib.compare u u'`. |
| [compare](string#VALcompare) [[String](string)] | `compare s0 s1` sorts `s0` and `s1` in lexicographical order. |
| [compare](stringlabels#VALcompare) [[StringLabels](stringlabels)] | `compare s0 s1` sorts `s0` and `s1` in lexicographical order. |
| [compare](set.orderedtype#VALcompare) [[Set.OrderedType](set.orderedtype)] | A total ordering function over the set elements. |
| [compare](set.s#VALcompare) [[Set.S](set.s)] | Total ordering between sets. |
| [compare](seq#VALcompare) [[Seq](seq)] | Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder. |
| [compare](result#VALcompare) [[Result](result)] | `compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. |
| [compare](option#VALcompare) [[Option](option)] | `compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. |
| [compare](nativeint#VALcompare) [[Nativeint](nativeint)] | The comparison function for native integers, with the same specification as [`compare`](stdlib#VALcompare). |
| [compare](morelabels.set.orderedtype#VALcompare) [[MoreLabels.Set.OrderedType](morelabels.set.orderedtype)] | A total ordering function over the set elements. |
| [compare](morelabels.set.s#VALcompare) [[MoreLabels.Set.S](morelabels.set.s)] | Total ordering between sets. |
| [compare](morelabels.map.orderedtype#VALcompare) [[MoreLabels.Map.OrderedType](morelabels.map.orderedtype)] | A total ordering function over the keys. |
| [compare](morelabels.map.s#VALcompare) [[MoreLabels.Map.S](morelabels.map.s)] | Total ordering between maps. |
| [compare](map.orderedtype#VALcompare) [[Map.OrderedType](map.orderedtype)] | A total ordering function over the keys. |
| [compare](map.s#VALcompare) [[Map.S](map.s)] | Total ordering between maps. |
| [compare](listlabels#VALcompare) [[ListLabels](listlabels)] | `compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`compare`](stdlib#VALcompare): |
| [compare](list#VALcompare) [[List](list)] | `compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`compare`](stdlib#VALcompare): |
| [compare](int64#VALcompare) [[Int64](int64)] | The comparison function for 64-bit integers, with the same specification as [`compare`](stdlib#VALcompare). |
| [compare](int32#VALcompare) [[Int32](int32)] | The comparison function for 32-bit integers, with the same specification as [`compare`](stdlib#VALcompare). |
| [compare](int#VALcompare) [[Int](int)] | `compare x y` is [`compare`](stdlib#VALcompare)`x y` but more efficient. |
| [compare](float#VALcompare) [[Float](float)] | `compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. |
| [compare](either#VALcompare) [[Either](either)] | `compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. |
| [compare](digest#VALcompare) [[Digest](digest)] | The comparison function for 16-character digest, with the same specification as [`compare`](stdlib#VALcompare) and the implementation shared with [`String.compare`](string#VALcompare). |
| [compare](char#VALcompare) [[Char](char)] | The comparison function for characters, with the same specification as [`compare`](stdlib#VALcompare). |
| [compare](byteslabels#VALcompare) [[BytesLabels](byteslabels)] | The comparison function for byte sequences, with the same specification as [`compare`](stdlib#VALcompare). |
| [compare](bytes#VALcompare) [[Bytes](bytes)] | The comparison function for byte sequences, with the same specification as [`compare`](stdlib#VALcompare). |
| [compare](bool#VALcompare) [[Bool](bool)] | `compare b0 b1` is a total order on boolean values. |
| [compare](stdlib#VALcompare) [[Stdlib](stdlib)] | `compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. |
| [compare\_and\_set](atomic#VALcompare_and_set) [[Atomic](atomic)] | `compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` -- the comparison and the set occur atomically. |
| [compare\_and\_swap\_field](obj#VALcompare_and_swap_field) [[Obj](obj)] | |
| [compare\_length\_with](listlabels#VALcompare_length_with) [[ListLabels](listlabels)] | Compare the length of a list to an integer. |
| [compare\_length\_with](list#VALcompare_length_with) [[List](list)] | Compare the length of a list to an integer. |
| [compare\_lengths](listlabels#VALcompare_lengths) [[ListLabels](listlabels)] | Compare the lengths of two lists. |
| [compare\_lengths](list#VALcompare_lengths) [[List](list)] | Compare the lengths of two lists. |
| [complex32](bigarray#VALcomplex32) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [complex64](bigarray#VALcomplex64) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [concat](string#VALconcat) [[String](string)] | `concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. |
| [concat](stringlabels#VALconcat) [[StringLabels](stringlabels)] | `concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. |
| [concat](seq#VALconcat) [[Seq](seq)] | If `xss` is a sequence of sequences, then `concat xss` is its concatenation. |
| [concat](listlabels#VALconcat) [[ListLabels](listlabels)] | Concatenate a list of lists. |
| [concat](list#VALconcat) [[List](list)] | Concatenate a list of lists. |
| [concat](float.arraylabels#VALconcat) [[Float.ArrayLabels](float.arraylabels)] | Same as [`Float.ArrayLabels.append`](float.arraylabels#VALappend), but concatenates a list of floatarrays. |
| [concat](float.array#VALconcat) [[Float.Array](float.array)] | Same as [`Float.Array.append`](float.array#VALappend), but concatenates a list of floatarrays. |
| [concat](filename#VALconcat) [[Filename](filename)] | `concat dir file` returns a file name that designates file `file` in directory `dir`. |
| [concat](byteslabels#VALconcat) [[BytesLabels](byteslabels)] | `concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. |
| [concat](bytes#VALconcat) [[Bytes](bytes)] | `concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. |
| [concat](arraylabels#VALconcat) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.append`](arraylabels#VALappend), but concatenates a list of arrays. |
| [concat](array#VALconcat) [[Array](array)] | Same as [`Array.append`](array#VALappend), but concatenates a list of arrays. |
| [concat\_fmt](camlinternalformatbasics#VALconcat_fmt) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [concat\_fmtty](camlinternalformatbasics#VALconcat_fmtty) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [concat\_map](seq#VALconcat_map) [[Seq](seq)] | `concat_map f xs` is equivalent to `concat (map f xs)`. |
| [concat\_map](listlabels#VALconcat_map) [[ListLabels](listlabels)] | `concat_map ~f l` gives the same result as [`ListLabels.concat`](listlabels#VALconcat)`(`[`ListLabels.map`](listlabels#VALmap)`f l)`. |
| [concat\_map](list#VALconcat_map) [[List](list)] | `concat_map f l` gives the same result as [`List.concat`](list#VALconcat)`(`[`List.map`](list#VALmap)`f l)`. |
| [conj](complex#VALconj) [[Complex](complex)] | Conjugate: given the complex `x + i.y`, returns `x - i.y`. |
| [connect](unixlabels#VALconnect) [[UnixLabels](unixlabels)] | Connect a socket to an address. |
| [connect](unix#VALconnect) [[Unix](unix)] | Connect a socket to an address. |
| [cons](seq#VALcons) [[Seq](seq)] | `cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`. |
| [cons](listlabels#VALcons) [[ListLabels](listlabels)] | `cons x xs` is `x :: xs` |
| [cons](list#VALcons) [[List](list)] | `cons x xs` is `x :: xs` |
| [const](fun#VALconst) [[Fun](fun)] | `const c` is a function that always returns the value `c`. |
| [cont\_tag](obj#VALcont_tag) [[Obj](obj)] | |
| [contains](string#VALcontains) [[String](string)] | `contains s c` is [`String.contains_from`](string#VALcontains_from)`s 0 c`. |
| [contains](stringlabels#VALcontains) [[StringLabels](stringlabels)] | `contains s c` is [`String.contains_from`](string#VALcontains_from)`s 0 c`. |
| [contains](byteslabels#VALcontains) [[BytesLabels](byteslabels)] | `contains s c` tests if byte `c` appears in `s`. |
| [contains](bytes#VALcontains) [[Bytes](bytes)] | `contains s c` tests if byte `c` appears in `s`. |
| [contains\_from](string#VALcontains_from) [[String](string)] | `contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. |
| [contains\_from](stringlabels#VALcontains_from) [[StringLabels](stringlabels)] | `contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. |
| [contains\_from](byteslabels#VALcontains_from) [[BytesLabels](byteslabels)] | `contains_from s start c` tests if byte `c` appears in `s` after position `start`. |
| [contains\_from](bytes#VALcontains_from) [[Bytes](bytes)] | `contains_from s start c` tests if byte `c` appears in `s` after position `start`. |
| [contents](buffer#VALcontents) [[Buffer](buffer)] | Return a copy of the current contents of the buffer. |
| [continue](effect.deep#VALcontinue) [[Effect.Deep](effect.deep)] | `continue k x` resumes the continuation `k` by passing `x` to `k`. |
| [continue\_with](effect.shallow#VALcontinue_with) [[Effect.Shallow](effect.shallow)] | `continue_with k v h` resumes the continuation `k` with value `v` with the handler `h`. |
| [convert\_raw\_backtrace\_slot](printexc#VALconvert_raw_backtrace_slot) [[Printexc](printexc)] | Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`. |
| [copy](camlinternaloo#VALcopy) [[CamlinternalOO](camlinternaloo)] | |
| [copy](stack#VALcopy) [[Stack](stack)] | Return a copy of the given stack. |
| [copy](random.state#VALcopy) [[Random.State](random.state)] | Return a copy of the given state. |
| [copy](queue#VALcopy) [[Queue](queue)] | Return a copy of the given queue. |
| [copy](oo#VALcopy) [[Oo](oo)] | `Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`. |
| [copy](morelabels.hashtbl.seededs#VALcopy) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [copy](morelabels.hashtbl.s#VALcopy) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [copy](morelabels.hashtbl#VALcopy) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Return a copy of the given hashtable. |
| [copy](hashtbl.seededs#VALcopy) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [copy](hashtbl.s#VALcopy) [[Hashtbl.S](hashtbl.s)] | |
| [copy](hashtbl#VALcopy) [[Hashtbl](hashtbl)] | Return a copy of the given hashtable. |
| [copy](float.arraylabels#VALcopy) [[Float.ArrayLabels](float.arraylabels)] | `copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. |
| [copy](float.array#VALcopy) [[Float.Array](float.array)] | `copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. |
| [copy](ephemeron.seededs#VALcopy) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [copy](ephemeron.s#VALcopy) [[Ephemeron.S](ephemeron.s)] | |
| [copy](byteslabels#VALcopy) [[BytesLabels](byteslabels)] | Return a new byte sequence that contains the same bytes as the argument. |
| [copy](bytes#VALcopy) [[Bytes](bytes)] | Return a new byte sequence that contains the same bytes as the argument. |
| [copy](arraylabels#VALcopy) [[ArrayLabels](arraylabels)] | `copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. |
| [copy](array#VALcopy) [[Array](array)] | `copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. |
| [copy\_sign](float#VALcopy_sign) [[Float](float)] | `copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. |
| [copysign](stdlib#VALcopysign) [[Stdlib](stdlib)] | `copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. |
| [cos](float#VALcos) [[Float](float)] | Cosine. |
| [cos](stdlib#VALcos) [[Stdlib](stdlib)] | Cosine. |
| [cosh](float#VALcosh) [[Float](float)] | Hyperbolic cosine. |
| [cosh](stdlib#VALcosh) [[Stdlib](stdlib)] | Hyperbolic cosine. |
| [count](weak.s#VALcount) [[Weak.S](weak.s)] | Count the number of elements in the table. |
| [counters](gc#VALcounters) [[Gc](gc)] | Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. |
| [cpu\_relax](domain#VALcpu_relax) [[Domain](domain)] | If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures |
| [create](runtime_events.callbacks#VALcreate) [[Runtime\_events.Callbacks](runtime_events.callbacks)] | Create a `Callback` that optionally subscribes to one or more runtime events. |
| [create](thread#VALcreate) [[Thread](thread)] | `Thread.create funct arg` creates a new thread of control, in which the function application `funct arg` is executed concurrently with the other threads of the domain. |
| [create](weak.s#VALcreate) [[Weak.S](weak.s)] | `create n` creates a new empty weak hash set, of initial size `n`. |
| [create](weak#VALcreate) [[Weak](weak)] | `Weak.create n` returns a new weak array of length `n`. |
| [create](stack#VALcreate) [[Stack](stack)] | Return a new stack, initially empty. |
| [create](queue#VALcreate) [[Queue](queue)] | Return a new queue, initially empty. |
| [create](obj.ephemeron#VALcreate) [[Obj.Ephemeron](obj.ephemeron)] | `create n` returns an ephemeron with `n` keys. |
| [create](mutex#VALcreate) [[Mutex](mutex)] | Return a new mutex. |
| [create](morelabels.hashtbl.seededs#VALcreate) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [create](morelabels.hashtbl.s#VALcreate) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [create](morelabels.hashtbl#VALcreate) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.create n` creates a new, empty hash table, with initial size `n`. |
| [create](hashtbl.seededs#VALcreate) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [create](hashtbl.s#VALcreate) [[Hashtbl.S](hashtbl.s)] | |
| [create](hashtbl#VALcreate) [[Hashtbl](hashtbl)] | `Hashtbl.create n` creates a new, empty hash table, with initial size `n`. |
| [create](float.arraylabels#VALcreate) [[Float.ArrayLabels](float.arraylabels)] | `create n` returns a fresh floatarray of length `n`, with uninitialized data. |
| [create](float.array#VALcreate) [[Float.Array](float.array)] | `create n` returns a fresh floatarray of length `n`, with uninitialized data. |
| [create](ephemeron.seededs#VALcreate) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [create](ephemeron.s#VALcreate) [[Ephemeron.S](ephemeron.s)] | |
| [create](condition#VALcreate) [[Condition](condition)] | `create()` creates and returns a new condition variable. |
| [create](byteslabels#VALcreate) [[BytesLabels](byteslabels)] | `create n` returns a new byte sequence of length `n`. |
| [create](bytes#VALcreate) [[Bytes](bytes)] | `create n` returns a new byte sequence of length `n`. |
| [create](buffer#VALcreate) [[Buffer](buffer)] | `create n` returns a fresh buffer, initially empty. |
| [create](bigarray.array3#VALcreate) [[Bigarray.Array3](bigarray.array3)] | `Array3.create kind layout dim1 dim2 dim3` returns a new Bigarray of three dimensions, whose size is `dim1` in the first dimension, `dim2` in the second dimension, and `dim3` in the third. |
| [create](bigarray.array2#VALcreate) [[Bigarray.Array2](bigarray.array2)] | `Array2.create kind layout dim1 dim2` returns a new Bigarray of two dimensions, whose size is `dim1` in the first dimension and `dim2` in the second dimension. |
| [create](bigarray.array1#VALcreate) [[Bigarray.Array1](bigarray.array1)] | `Array1.create kind layout dim` returns a new Bigarray of one dimension, whose size is `dim`. |
| [create](bigarray.array0#VALcreate) [[Bigarray.Array0](bigarray.array0)] | `Array0.create kind layout` returns a new Bigarray of zero dimension. |
| [create](bigarray.genarray#VALcreate) [[Bigarray.Genarray](bigarray.genarray)] | `Genarray.create kind layout dimensions` returns a new Bigarray whose element kind is determined by the parameter `kind` (one of `float32`, `float64`, `int8_signed`, etc) and whose layout is determined by the parameter `layout` (one of `c_layout` or `fortran_layout`). |
| [create\_alarm](gc#VALcreate_alarm) [[Gc](gc)] | `create_alarm f` will arrange for `f` to be called at the end of each major GC cycle, starting with the current cycle or the next one. |
| [create\_char\_set](camlinternalformat#VALcreate_char_set) [[CamlinternalFormat](camlinternalformat)] | |
| [create\_cursor](runtime_events#VALcreate_cursor) [[Runtime\_events](runtime_events)] | `create_cursor path_pid` creates a cursor to read from an runtime\_events. |
| [create\_float](arraylabels#VALcreate_float) [[ArrayLabels](arraylabels)] | `create_float n` returns a fresh float array of length `n`, with uninitialized data. |
| [create\_float](array#VALcreate_float) [[Array](array)] | `create_float n` returns a fresh float array of length `n`, with uninitialized data. |
| [create\_object](camlinternaloo#VALcreate_object) [[CamlinternalOO](camlinternaloo)] | |
| [create\_object\_and\_run\_initializers](camlinternaloo#VALcreate_object_and_run_initializers) [[CamlinternalOO](camlinternaloo)] | |
| [create\_object\_opt](camlinternaloo#VALcreate_object_opt) [[CamlinternalOO](camlinternaloo)] | |
| [create\_process](unixlabels#VALcreate_process) [[UnixLabels](unixlabels)] | `create_process ~prog ~args ~stdin ~stdout ~stderr` forks a new process that executes the program in file `prog`, with arguments `args`. |
| [create\_process](unix#VALcreate_process) [[Unix](unix)] | `create_process prog args stdin stdout stderr` forks a new process that executes the program in file `prog`, with arguments `args`. |
| [create\_process\_env](unixlabels#VALcreate_process_env) [[UnixLabels](unixlabels)] | `create_process_env ~prog ~args ~env ~stdin ~stdout ~stderr` works as [`UnixLabels.create_process`](unixlabels#VALcreate_process), except that the extra argument `env` specifies the environment passed to the program. |
| [create\_process\_env](unix#VALcreate_process_env) [[Unix](unix)] | `create_process_env prog args env stdin stdout stderr` works as [`Unix.create_process`](unix#VALcreate_process), except that the extra argument `env` specifies the environment passed to the program. |
| [create\_table](camlinternaloo#VALcreate_table) [[CamlinternalOO](camlinternaloo)] | |
| [current](arg#VALcurrent) [[Arg](arg)] | Position (in [`Sys.argv`](sys#VALargv)) of the argument being processed. |
| [current\_dir\_name](filename#VALcurrent_dir_name) [[Filename](filename)] | The conventional name for the current directory (e.g. |
| [custom\_tag](obj#VALcustom_tag) [[Obj](obj)] | |
| [cycle](seq#VALcycle) [[Seq](seq)] | `cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`. |
| [cygwin](sys#VALcygwin) [[Sys](sys)] | True if `Sys.os_type = "Cygwin"`. |
| D |
| [data\_size](marshal#VALdata_size) [[Marshal](marshal)] | See [`Marshal.header_size`](marshal#VALheader_size). |
| [decr](atomic#VALdecr) [[Atomic](atomic)] | `decr r` atomically decrements the value of `r` by `1`. |
| [decr](stdlib#VALdecr) [[Stdlib](stdlib)] | Decrement the integer contained in the given reference. |
| [default\_uncaught\_exception\_handler](thread#VALdefault_uncaught_exception_handler) [[Thread](thread)] | `Thread.default_uncaught_exception_handler` will print the thread's id, exception and backtrace (if available). |
| [default\_uncaught\_exception\_handler](printexc#VALdefault_uncaught_exception_handler) [[Printexc](printexc)] | `Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output. |
| [delay](thread#VALdelay) [[Thread](thread)] | `delay d` suspends the execution of the calling thread for `d` seconds. |
| [delete\_alarm](gc#VALdelete_alarm) [[Gc](gc)] | `delete_alarm a` will stop the calls to the function associated to `a`. |
| [descr\_of\_in\_channel](unixlabels#VALdescr_of_in_channel) [[UnixLabels](unixlabels)] | Return the descriptor corresponding to an input channel. |
| [descr\_of\_in\_channel](unix#VALdescr_of_in_channel) [[Unix](unix)] | Return the descriptor corresponding to an input channel. |
| [descr\_of\_out\_channel](unixlabels#VALdescr_of_out_channel) [[UnixLabels](unixlabels)] | Return the descriptor corresponding to an output channel. |
| [descr\_of\_out\_channel](unix#VALdescr_of_out_channel) [[Unix](unix)] | Return the descriptor corresponding to an output channel. |
| [development\_version](sys#VALdevelopment_version) [[Sys](sys)] | `true` if this is a development version, `false` otherwise. |
| [diff](set.s#VALdiff) [[Set.S](set.s)] | Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. |
| [diff](morelabels.set.s#VALdiff) [[MoreLabels.Set.S](morelabels.set.s)] | Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. |
| [dim](bigarray.array1#VALdim) [[Bigarray.Array1](bigarray.array1)] | Return the size (dimension) of the given one-dimensional Bigarray. |
| [dim1](bigarray.array3#VALdim1) [[Bigarray.Array3](bigarray.array3)] | Return the first dimension of the given three-dimensional Bigarray. |
| [dim1](bigarray.array2#VALdim1) [[Bigarray.Array2](bigarray.array2)] | Return the first dimension of the given two-dimensional Bigarray. |
| [dim2](bigarray.array3#VALdim2) [[Bigarray.Array3](bigarray.array3)] | Return the second dimension of the given three-dimensional Bigarray. |
| [dim2](bigarray.array2#VALdim2) [[Bigarray.Array2](bigarray.array2)] | Return the second dimension of the given two-dimensional Bigarray. |
| [dim3](bigarray.array3#VALdim3) [[Bigarray.Array3](bigarray.array3)] | Return the third dimension of the given three-dimensional Bigarray. |
| [dims](bigarray.genarray#VALdims) [[Bigarray.Genarray](bigarray.genarray)] | `Genarray.dims a` returns all dimensions of the Bigarray `a`, as an array of integers of length `Genarray.num_dims a`. |
| [dir\_sep](filename#VALdir_sep) [[Filename](filename)] | The directory separator (e.g. |
| [dirname](filename#VALdirname) [[Filename](filename)] | See [`Filename.basename`](filename#VALbasename). |
| [discontinue](effect.deep#VALdiscontinue) [[Effect.Deep](effect.deep)] | `discontinue k e` resumes the continuation `k` by raising the exception `e` in `k`. |
| [discontinue\_with](effect.shallow#VALdiscontinue_with) [[Effect.Shallow](effect.shallow)] | `discontinue_with k e h` resumes the continuation `k` by raising the exception `e` with the handler `h`. |
| [discontinue\_with\_backtrace](effect.shallow#VALdiscontinue_with_backtrace) [[Effect.Shallow](effect.shallow)] | `discontinue_with k e bt h` resumes the continuation `k` by raising the exception `e` with the handler `h` using the raw backtrace `bt` as the origin of the exception. |
| [discontinue\_with\_backtrace](effect.deep#VALdiscontinue_with_backtrace) [[Effect.Deep](effect.deep)] | `discontinue_with_backtrace k e bt` resumes the continuation `k` by raising the exception `e` in `k` using `bt` as the origin for the exception. |
| [disjoint](set.s#VALdisjoint) [[Set.S](set.s)] | Test if two sets are disjoint. |
| [disjoint](morelabels.set.s#VALdisjoint) [[MoreLabels.Set.S](morelabels.set.s)] | Test if two sets are disjoint. |
| [div](nativeint#VALdiv) [[Nativeint](nativeint)] | Integer division. |
| [div](int64#VALdiv) [[Int64](int64)] | Integer division. |
| [div](int32#VALdiv) [[Int32](int32)] | Integer division. |
| [div](int#VALdiv) [[Int](int)] | `div x y` is the division `x / y`. |
| [div](float#VALdiv) [[Float](float)] | Floating-point division. |
| [div](complex#VALdiv) [[Complex](complex)] | Division |
| [domain\_of\_sockaddr](unixlabels#VALdomain_of_sockaddr) [[UnixLabels](unixlabels)] | Return the socket domain adequate for the given socket address. |
| [domain\_of\_sockaddr](unix#VALdomain_of_sockaddr) [[Unix](unix)] | Return the socket domain adequate for the given socket address. |
| [double\_array\_tag](obj#VALdouble_array_tag) [[Obj](obj)] | |
| [double\_field](obj#VALdouble_field) [[Obj](obj)] | |
| [double\_tag](obj#VALdouble_tag) [[Obj](obj)] | |
| [dprintf](format#VALdprintf) [[Format](format)] | Same as [`Format.fprintf`](format#VALfprintf), except the formatter is the last argument. |
| [drop](seq#VALdrop) [[Seq](seq)] | `drop n xs` is the sequence `xs`, deprived of its first `n` elements. |
| [drop\_while](seq#VALdrop_while) [[Seq](seq)] | `drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`. |
| [dummy\_class](camlinternaloo#VALdummy_class) [[CamlinternalOO](camlinternaloo)] | |
| [dummy\_pos](lexing#VALdummy_pos) [[Lexing](lexing)] | A value of type `position`, guaranteed to be different from any valid position. |
| [dummy\_table](camlinternaloo#VALdummy_table) [[CamlinternalOO](camlinternaloo)] | |
| [dup](unixlabels#VALdup) [[UnixLabels](unixlabels)] | Return a new file descriptor referencing the same file as the given descriptor. |
| [dup](unix#VALdup) [[Unix](unix)] | Return a new file descriptor referencing the same file as the given descriptor. |
| [dup](obj#VALdup) [[Obj](obj)] | |
| [dup2](unixlabels#VALdup2) [[UnixLabels](unixlabels)] | `dup2 ~src ~dst` duplicates `src` to `dst`, closing `dst` if already opened. |
| [dup2](unix#VALdup2) [[Unix](unix)] | `dup2 src dst` duplicates `src` to `dst`, closing `dst` if already opened. |
| E |
| [elements](set.s#VALelements) [[Set.S](set.s)] | Return the list of all elements of the given set. |
| [elements](morelabels.set.s#VALelements) [[MoreLabels.Set.S](morelabels.set.s)] | Return the list of all elements of the given set. |
| [empty](string#VALempty) [[String](string)] | The empty string. |
| [empty](stringlabels#VALempty) [[StringLabels](stringlabels)] | The empty string. |
| [empty](set.s#VALempty) [[Set.S](set.s)] | The empty set. |
| [empty](seq#VALempty) [[Seq](seq)] | `empty` is the empty sequence. |
| [empty](morelabels.set.s#VALempty) [[MoreLabels.Set.S](morelabels.set.s)] | The empty set. |
| [empty](morelabels.map.s#VALempty) [[MoreLabels.Map.S](morelabels.map.s)] | The empty map. |
| [empty](map.s#VALempty) [[Map.S](map.s)] | The empty map. |
| [empty](byteslabels#VALempty) [[BytesLabels](byteslabels)] | A byte sequence of size 0. |
| [empty](bytes#VALempty) [[Bytes](bytes)] | A byte sequence of size 0. |
| [enable\_runtime\_warnings](sys#VALenable_runtime_warnings) [[Sys](sys)] | Control whether the OCaml runtime system can emit warnings on stderr. |
| [end\_of\_input](scanf.scanning#VALend_of_input) [[Scanf.Scanning](scanf.scanning)] | `Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel. |
| [ends\_with](string#VALends_with) [[String](string)] | `ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`. |
| [ends\_with](stringlabels#VALends_with) [[StringLabels](stringlabels)] | `ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`. |
| [ends\_with](byteslabels#VALends_with) [[BytesLabels](byteslabels)] | `ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`. |
| [ends\_with](bytes#VALends_with) [[Bytes](bytes)] | `ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`. |
| [environment](unixlabels#VALenvironment) [[UnixLabels](unixlabels)] | Return the process environment, as an array of strings with the format ``variable=value''. |
| [environment](unix#VALenvironment) [[Unix](unix)] | Return the process environment, as an array of strings with the format ``variable=value''. |
| [eprintf](printf#VALeprintf) [[Printf](printf)] | Same as [`Printf.fprintf`](printf#VALfprintf), but output on `stderr`. |
| [eprintf](format#VALeprintf) [[Format](format)] | Same as `fprintf` above, but output on `get_err_formatter ()`. |
| [epsilon](float#VALepsilon) [[Float](float)] | The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. |
| [epsilon\_float](stdlib#VALepsilon_float) [[Stdlib](stdlib)] | The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. |
| [equal](unit#VALequal) [[Unit](unit)] | `equal u1 u2` is `true`. |
| [equal](uchar#VALequal) [[Uchar](uchar)] | `equal u u'` is `u = u'`. |
| [equal](string#VALequal) [[String](string)] | `equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. |
| [equal](stringlabels#VALequal) [[StringLabels](stringlabels)] | `equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. |
| [equal](set.s#VALequal) [[Set.S](set.s)] | `equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. |
| [equal](seq#VALequal) [[Seq](seq)] | Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal. |
| [equal](result#VALequal) [[Result](result)] | `equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. |
| [equal](option#VALequal) [[Option](option)] | `equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`. |
| [equal](nativeint#VALequal) [[Nativeint](nativeint)] | The equal function for native ints. |
| [equal](morelabels.set.s#VALequal) [[MoreLabels.Set.S](morelabels.set.s)] | `equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. |
| [equal](morelabels.map.s#VALequal) [[MoreLabels.Map.S](morelabels.map.s)] | `equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. |
| [equal](morelabels.hashtbl.seededhashedtype#VALequal) [[MoreLabels.Hashtbl.SeededHashedType](morelabels.hashtbl.seededhashedtype)] | The equality predicate used to compare keys. |
| [equal](morelabels.hashtbl.hashedtype#VALequal) [[MoreLabels.Hashtbl.HashedType](morelabels.hashtbl.hashedtype)] | The equality predicate used to compare keys. |
| [equal](map.s#VALequal) [[Map.S](map.s)] | `equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. |
| [equal](listlabels#VALequal) [[ListLabels](listlabels)] | `equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. |
| [equal](list#VALequal) [[List](list)] | `equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. |
| [equal](int64#VALequal) [[Int64](int64)] | The equal function for int64s. |
| [equal](int32#VALequal) [[Int32](int32)] | The equal function for int32s. |
| [equal](int#VALequal) [[Int](int)] | `equal x y` is `true` if and only if `x = y`. |
| [equal](hashtbl.seededhashedtype#VALequal) [[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)] | The equality predicate used to compare keys. |
| [equal](hashtbl.hashedtype#VALequal) [[Hashtbl.HashedType](hashtbl.hashedtype)] | The equality predicate used to compare keys. |
| [equal](float#VALequal) [[Float](float)] | The equal function for floating-point numbers, compared using [`Float.compare`](float#VALcompare). |
| [equal](either#VALequal) [[Either](either)] | `equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. |
| [equal](digest#VALequal) [[Digest](digest)] | The equal function for 16-character digest. |
| [equal](char#VALequal) [[Char](char)] | The equal function for chars. |
| [equal](byteslabels#VALequal) [[BytesLabels](byteslabels)] | The equality function for byte sequences. |
| [equal](bytes#VALequal) [[Bytes](bytes)] | The equality function for byte sequences. |
| [equal](bool#VALequal) [[Bool](bool)] | `equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`. |
| [erase\_rel](camlinternalformatbasics#VALerase_rel) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [erf](float#VALerf) [[Float](float)] | Error function. |
| [erfc](float#VALerfc) [[Float](float)] | Complementary error function (`erfc x = 1 - erf x`). |
| [err\_formatter](format#VALerr_formatter) [[Format](format)] | The initial domain's formatter to write to standard error. |
| [error](result#VALerror) [[Result](result)] | `error e` is `Error e`. |
| [error\_message](unixlabels#VALerror_message) [[UnixLabels](unixlabels)] | Return a string describing the given error code. |
| [error\_message](unix#VALerror_message) [[Unix](unix)] | Return a string describing the given error code. |
| [error\_message](dynlink#VALerror_message) [[Dynlink](dynlink)] | Convert an error description to a printable message. |
| [escaped](string#VALescaped) [[String](string)] | `escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. |
| [escaped](stringlabels#VALescaped) [[StringLabels](stringlabels)] | `escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. |
| [escaped](char#VALescaped) [[Char](char)] | Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. |
| [escaped](byteslabels#VALescaped) [[BytesLabels](byteslabels)] | Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. |
| [escaped](bytes#VALescaped) [[Bytes](bytes)] | Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. |
| [establish\_server](unixlabels#VALestablish_server) [[UnixLabels](unixlabels)] | Establish a server on the given address. |
| [establish\_server](unix#VALestablish_server) [[Unix](unix)] | Establish a server on the given address. |
| [eventlog\_pause](gc#VALeventlog_pause) [[Gc](gc)] | |
| [eventlog\_resume](gc#VALeventlog_resume) [[Gc](gc)] | |
| [exchange](atomic#VALexchange) [[Atomic](atomic)] | Set a new value for the atomic reference, and return the current value. |
| [executable\_name](sys#VALexecutable_name) [[Sys](sys)] | The name of the file containing the executable currently running. |
| [execv](unixlabels#VALexecv) [[UnixLabels](unixlabels)] | `execv ~prog ~args` execute the program in file `prog`, with the arguments `args`, and the current process environment. |
| [execv](unix#VALexecv) [[Unix](unix)] | `execv prog args` execute the program in file `prog`, with the arguments `args`, and the current process environment. |
| [execve](unixlabels#VALexecve) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.execv`](unixlabels#VALexecv), except that the third argument provides the environment to the program executed. |
| [execve](unix#VALexecve) [[Unix](unix)] | Same as [`Unix.execv`](unix#VALexecv), except that the third argument provides the environment to the program executed. |
| [execvp](unixlabels#VALexecvp) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.execv`](unixlabels#VALexecv), except that the program is searched in the path. |
| [execvp](unix#VALexecvp) [[Unix](unix)] | Same as [`Unix.execv`](unix#VALexecv), except that the program is searched in the path. |
| [execvpe](unixlabels#VALexecvpe) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.execve`](unixlabels#VALexecve), except that the program is searched in the path. |
| [execvpe](unix#VALexecvpe) [[Unix](unix)] | Same as [`Unix.execve`](unix#VALexecve), except that the program is searched in the path. |
| [exists](string#VALexists) [[String](string)] | `exists p s` checks if at least one character of `s` satisfies the predicate `p`. |
| [exists](stringlabels#VALexists) [[StringLabels](stringlabels)] | `exists p s` checks if at least one character of `s` satisfies the predicate `p`. |
| [exists](set.s#VALexists) [[Set.S](set.s)] | `exists f s` checks if at least one element of the set satisfies the predicate `f`. |
| [exists](seq#VALexists) [[Seq](seq)] | `exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`. |
| [exists](morelabels.set.s#VALexists) [[MoreLabels.Set.S](morelabels.set.s)] | `exists ~f s` checks if at least one element of the set satisfies the predicate `f`. |
| [exists](morelabels.map.s#VALexists) [[MoreLabels.Map.S](morelabels.map.s)] | `exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. |
| [exists](map.s#VALexists) [[Map.S](map.s)] | `exists f m` checks if at least one binding of the map satisfies the predicate `f`. |
| [exists](listlabels#VALexists) [[ListLabels](listlabels)] | `exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. |
| [exists](list#VALexists) [[List](list)] | `exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. |
| [exists](float.arraylabels#VALexists) [[Float.ArrayLabels](float.arraylabels)] | `exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. |
| [exists](float.array#VALexists) [[Float.Array](float.array)] | `exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. |
| [exists](byteslabels#VALexists) [[BytesLabels](byteslabels)] | `exists p s` checks if at least one character of `s` satisfies the predicate `p`. |
| [exists](bytes#VALexists) [[Bytes](bytes)] | `exists p s` checks if at least one character of `s` satisfies the predicate `p`. |
| [exists](arraylabels#VALexists) [[ArrayLabels](arraylabels)] | `exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. |
| [exists](array#VALexists) [[Array](array)] | `exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. |
| [exists2](seq#VALexists2) [[Seq](seq)] | `exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`. |
| [exists2](listlabels#VALexists2) [[ListLabels](listlabels)] | Same as [`ListLabels.exists`](listlabels#VALexists), but for a two-argument predicate. |
| [exists2](list#VALexists2) [[List](list)] | Same as [`List.exists`](list#VALexists), but for a two-argument predicate. |
| [exists2](arraylabels#VALexists2) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.exists`](arraylabels#VALexists), but for a two-argument predicate. |
| [exists2](array#VALexists2) [[Array](array)] | Same as [`Array.exists`](array#VALexists), but for a two-argument predicate. |
| [exit](thread#VALexit) [[Thread](thread)] | Raise the [`Thread.Exit`](thread#EXCEPTIONExit) exception.
|
| [exit](stdlib#VALexit) [[Stdlib](stdlib)] | Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. |
| [exn\_slot\_id](printexc#VALexn_slot_id) [[Printexc](printexc)] | `Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime). |
| [exn\_slot\_name](printexc#VALexn_slot_name) [[Printexc](printexc)] | `Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`. |
| [exp](float#VALexp) [[Float](float)] | Exponential. |
| [exp](complex#VALexp) [[Complex](complex)] | Exponentiation. |
| [exp](stdlib#VALexp) [[Stdlib](stdlib)] | Exponential. |
| [exp2](float#VALexp2) [[Float](float)] | Base 2 exponential function. |
| [expm1](float#VALexpm1) [[Float](float)] | `expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. |
| [expm1](stdlib#VALexpm1) [[Stdlib](stdlib)] | `expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. |
| [extend](byteslabels#VALextend) [[BytesLabels](byteslabels)] | `extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. |
| [extend](bytes#VALextend) [[Bytes](bytes)] | `extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. |
| [extension](filename#VALextension) [[Filename](filename)] | `extension name` is the shortest suffix `ext` of `name0` where: |
| F |
| [failwith](stdlib#VALfailwith) [[Stdlib](stdlib)] | Raise exception `Failure` with the given string. |
| [fast\_sort](listlabels#VALfast_sort) [[ListLabels](listlabels)] | Same as [`ListLabels.sort`](listlabels#VALsort) or [`ListLabels.stable_sort`](listlabels#VALstable_sort), whichever is faster on typical input. |
| [fast\_sort](list#VALfast_sort) [[List](list)] | Same as [`List.sort`](list#VALsort) or [`List.stable_sort`](list#VALstable_sort), whichever is faster on typical input. |
| [fast\_sort](float.arraylabels#VALfast_sort) [[Float.ArrayLabels](float.arraylabels)] | Same as [`Float.ArrayLabels.sort`](float.arraylabels#VALsort) or [`Float.ArrayLabels.stable_sort`](float.arraylabels#VALstable_sort), whichever is faster on typical input. |
| [fast\_sort](float.array#VALfast_sort) [[Float.Array](float.array)] | Same as [`Float.Array.sort`](float.array#VALsort) or [`Float.Array.stable_sort`](float.array#VALstable_sort), whichever is faster on typical input. |
| [fast\_sort](arraylabels#VALfast_sort) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.sort`](arraylabels#VALsort) or [`ArrayLabels.stable_sort`](arraylabels#VALstable_sort), whichever is faster on typical input. |
| [fast\_sort](array#VALfast_sort) [[Array](array)] | Same as [`Array.sort`](array#VALsort) or [`Array.stable_sort`](array#VALstable_sort), whichever is faster on typical input. |
| [fchmod](unixlabels#VALfchmod) [[UnixLabels](unixlabels)] | Change the permissions of an opened file. |
| [fchmod](unix#VALfchmod) [[Unix](unix)] | Change the permissions of an opened file. |
| [fchown](unixlabels#VALfchown) [[UnixLabels](unixlabels)] | Change the owner uid and owner gid of an opened file. |
| [fchown](unix#VALfchown) [[Unix](unix)] | Change the owner uid and owner gid of an opened file. |
| [fetch\_and\_add](atomic#VALfetch_and_add) [[Atomic](atomic)] | `fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment). |
| [fiber](effect.shallow#VALfiber) [[Effect.Shallow](effect.shallow)] | `fiber f` constructs a continuation that runs the computation `f`. |
| [field](obj#VALfield) [[Obj](obj)] | |
| [file](digest#VALfile) [[Digest](digest)] | Return the digest of the file whose name is given. |
| [file\_exists](sys#VALfile_exists) [[Sys](sys)] | Test if a file with the given name exists. |
| [fill](weak#VALfill) [[Weak](weak)] | `Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`. |
| [fill](float.arraylabels#VALfill) [[Float.ArrayLabels](float.arraylabels)] | `fill a ~pos ~len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. |
| [fill](float.array#VALfill) [[Float.Array](float.array)] | `fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. |
| [fill](byteslabels#VALfill) [[BytesLabels](byteslabels)] | `fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. |
| [fill](bytes#VALfill) [[Bytes](bytes)] | `fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. |
| [fill](bigarray.array3#VALfill) [[Bigarray.Array3](bigarray.array3)] | Fill the given Bigarray with the given value. |
| [fill](bigarray.array2#VALfill) [[Bigarray.Array2](bigarray.array2)] | Fill the given Bigarray with the given value. |
| [fill](bigarray.array1#VALfill) [[Bigarray.Array1](bigarray.array1)] | Fill the given Bigarray with the given value. |
| [fill](bigarray.array0#VALfill) [[Bigarray.Array0](bigarray.array0)] | Fill the given Bigarray with the given value. |
| [fill](bigarray.genarray#VALfill) [[Bigarray.Genarray](bigarray.genarray)] | Set all elements of a Bigarray to a given value. |
| [fill](arraylabels#VALfill) [[ArrayLabels](arraylabels)] | `fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. |
| [fill](array#VALfill) [[Array](array)] | `fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. |
| [filter](set.s#VALfilter) [[Set.S](set.s)] | `filter f s` returns the set of all elements in `s` that satisfy predicate `f`. |
| [filter](seq#VALfilter) [[Seq](seq)] | `filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`. |
| [filter](morelabels.set.s#VALfilter) [[MoreLabels.Set.S](morelabels.set.s)] | `filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. |
| [filter](morelabels.map.s#VALfilter) [[MoreLabels.Map.S](morelabels.map.s)] | `filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. |
| [filter](map.s#VALfilter) [[Map.S](map.s)] | `filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. |
| [filter](listlabels#VALfilter) [[ListLabels](listlabels)] | `filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. |
| [filter](list#VALfilter) [[List](list)] | `filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. |
| [filter\_map](set.s#VALfilter_map) [[Set.S](set.s)] | `filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. |
| [filter\_map](seq#VALfilter_map) [[Seq](seq)] | `filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`. |
| [filter\_map](morelabels.set.s#VALfilter_map) [[MoreLabels.Set.S](morelabels.set.s)] | `filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. |
| [filter\_map](morelabels.map.s#VALfilter_map) [[MoreLabels.Map.S](morelabels.map.s)] | `filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. |
| [filter\_map](map.s#VALfilter_map) [[Map.S](map.s)] | `filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. |
| [filter\_map](listlabels#VALfilter_map) [[ListLabels](listlabels)] | `filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. |
| [filter\_map](list#VALfilter_map) [[List](list)] | `filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. |
| [filter\_map\_inplace](morelabels.hashtbl.seededs#VALfilter_map_inplace) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [filter\_map\_inplace](morelabels.hashtbl.s#VALfilter_map_inplace) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [filter\_map\_inplace](morelabels.hashtbl#VALfilter_map_inplace) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. |
| [filter\_map\_inplace](hashtbl.seededs#VALfilter_map_inplace) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [filter\_map\_inplace](hashtbl.s#VALfilter_map_inplace) [[Hashtbl.S](hashtbl.s)] | |
| [filter\_map\_inplace](hashtbl#VALfilter_map_inplace) [[Hashtbl](hashtbl)] | `Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. |
| [filteri](listlabels#VALfilteri) [[ListLabels](listlabels)] | Same as [`ListLabels.filter`](listlabels#VALfilter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. |
| [filteri](list#VALfilteri) [[List](list)] | Same as [`List.filter`](list#VALfilter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. |
| [finalise](gc#VALfinalise) [[Gc](gc)] | `finalise f v` registers `f` as a finalisation function for `v`. |
| [finalise\_last](gc#VALfinalise_last) [[Gc](gc)] | same as [`Gc.finalise`](gc#VALfinalise) except the value is not given as argument. |
| [finalise\_release](gc#VALfinalise_release) [[Gc](gc)] | A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return. |
| [find](weak.s#VALfind) [[Weak.S](weak.s)] | `find t x` returns an instance of `x` found in `t`. |
| [find](set.s#VALfind) [[Set.S](set.s)] | `find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not\_found` if no such element exists. |
| [find](seq#VALfind) [[Seq](seq)] | `find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element. |
| [find](morelabels.set.s#VALfind) [[MoreLabels.Set.S](morelabels.set.s)] | `find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not\_found` if no such element exists. |
| [find](morelabels.map.s#VALfind) [[MoreLabels.Map.S](morelabels.map.s)] | `find x m` returns the current value of `x` in `m`, or raises `Not\_found` if no binding for `x` exists. |
| [find](morelabels.hashtbl.seededs#VALfind) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [find](morelabels.hashtbl.s#VALfind) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [find](morelabels.hashtbl#VALfind) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not\_found` if no such binding exists. |
| [find](map.s#VALfind) [[Map.S](map.s)] | `find x m` returns the current value of `x` in `m`, or raises `Not\_found` if no binding for `x` exists. |
| [find](listlabels#VALfind) [[ListLabels](listlabels)] | `find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. |
| [find](list#VALfind) [[List](list)] | `find f l` returns the first element of the list `l` that satisfies the predicate `f`. |
| [find](hashtbl.seededs#VALfind) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [find](hashtbl.s#VALfind) [[Hashtbl.S](hashtbl.s)] | |
| [find](hashtbl#VALfind) [[Hashtbl](hashtbl)] | `Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not\_found` if no such binding exists. |
| [find](ephemeron.kn.bucket#VALfind) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | Returns the data of the most-recently added ephemeron with the given keys, or `None` if there is no such ephemeron. |
| [find](ephemeron.k2.bucket#VALfind) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | Returns the data of the most-recently added ephemeron with the given keys, or `None` if there is no such ephemeron. |
| [find](ephemeron.k1.bucket#VALfind) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | Returns the data of the most-recently added ephemeron with the given key, or `None` if there is no such ephemeron. |
| [find](ephemeron.seededs#VALfind) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [find](ephemeron.s#VALfind) [[Ephemeron.S](ephemeron.s)] | |
| [find\_all](weak.s#VALfind_all) [[Weak.S](weak.s)] | `find_all t x` returns a list of all the instances of `x` found in `t`. |
| [find\_all](morelabels.hashtbl.seededs#VALfind_all) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [find\_all](morelabels.hashtbl.s#VALfind_all) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [find\_all](morelabels.hashtbl#VALfind_all) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. |
| [find\_all](listlabels#VALfind_all) [[ListLabels](listlabels)] | `find_all` is another name for [`ListLabels.filter`](listlabels#VALfilter). |
| [find\_all](list#VALfind_all) [[List](list)] | `find_all` is another name for [`List.filter`](list#VALfilter). |
| [find\_all](hashtbl.seededs#VALfind_all) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [find\_all](hashtbl.s#VALfind_all) [[Hashtbl.S](hashtbl.s)] | |
| [find\_all](hashtbl#VALfind_all) [[Hashtbl](hashtbl)] | `Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. |
| [find\_all](ephemeron.seededs#VALfind_all) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [find\_all](ephemeron.s#VALfind_all) [[Ephemeron.S](ephemeron.s)] | |
| [find\_first](set.s#VALfind_first) [[Set.S](set.s)] | `find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists. |
| [find\_first](morelabels.set.s#VALfind_first) [[MoreLabels.Set.S](morelabels.set.s)] | `find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists. |
| [find\_first](morelabels.map.s#VALfind_first) [[MoreLabels.Map.S](morelabels.map.s)] | `find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not\_found` if no such key exists. |
| [find\_first](map.s#VALfind_first) [[Map.S](map.s)] | `find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not\_found` if no such key exists. |
| [find\_first\_opt](set.s#VALfind_first_opt) [[Set.S](set.s)] | `find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. |
| [find\_first\_opt](morelabels.set.s#VALfind_first_opt) [[MoreLabels.Set.S](morelabels.set.s)] | `find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. |
| [find\_first\_opt](morelabels.map.s#VALfind_first_opt) [[MoreLabels.Map.S](morelabels.map.s)] | `find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. |
| [find\_first\_opt](map.s#VALfind_first_opt) [[Map.S](map.s)] | `find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. |
| [find\_last](set.s#VALfind_last) [[Set.S](set.s)] | `find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists. |
| [find\_last](morelabels.set.s#VALfind_last) [[MoreLabels.Set.S](morelabels.set.s)] | `find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not\_found` if no such element exists. |
| [find\_last](morelabels.map.s#VALfind_last) [[MoreLabels.Map.S](morelabels.map.s)] | `find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not\_found` if no such key exists. |
| [find\_last](map.s#VALfind_last) [[Map.S](map.s)] | `find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not\_found` if no such key exists. |
| [find\_last\_opt](set.s#VALfind_last_opt) [[Set.S](set.s)] | `find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. |
| [find\_last\_opt](morelabels.set.s#VALfind_last_opt) [[MoreLabels.Set.S](morelabels.set.s)] | `find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. |
| [find\_last\_opt](morelabels.map.s#VALfind_last_opt) [[MoreLabels.Map.S](morelabels.map.s)] | `find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. |
| [find\_last\_opt](map.s#VALfind_last_opt) [[Map.S](map.s)] | `find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. |
| [find\_left](either#VALfind_left) [[Either](either)] | `find_left (Left v)` is `Some v`, `find_left (Right _)` is `None` |
| [find\_map](seq#VALfind_map) [[Seq](seq)] | `find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`. |
| [find\_map](listlabels#VALfind_map) [[ListLabels](listlabels)] | `find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. |
| [find\_map](list#VALfind_map) [[List](list)] | `find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. |
| [find\_map](arraylabels#VALfind_map) [[ArrayLabels](arraylabels)] | `find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. |
| [find\_map](array#VALfind_map) [[Array](array)] | `find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. |
| [find\_opt](weak.s#VALfind_opt) [[Weak.S](weak.s)] | `find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. |
| [find\_opt](set.s#VALfind_opt) [[Set.S](set.s)] | `find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. |
| [find\_opt](morelabels.set.s#VALfind_opt) [[MoreLabels.Set.S](morelabels.set.s)] | `find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. |
| [find\_opt](morelabels.map.s#VALfind_opt) [[MoreLabels.Map.S](morelabels.map.s)] | `find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. |
| [find\_opt](morelabels.hashtbl.seededs#VALfind_opt) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [find\_opt](morelabels.hashtbl.s#VALfind_opt) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [find\_opt](morelabels.hashtbl#VALfind_opt) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. |
| [find\_opt](map.s#VALfind_opt) [[Map.S](map.s)] | `find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. |
| [find\_opt](listlabels#VALfind_opt) [[ListLabels](listlabels)] | `find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. |
| [find\_opt](list#VALfind_opt) [[List](list)] | `find f l` returns the first element of the list `l` that satisfies the predicate `f`. |
| [find\_opt](hashtbl.seededs#VALfind_opt) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [find\_opt](hashtbl.s#VALfind_opt) [[Hashtbl.S](hashtbl.s)] | |
| [find\_opt](hashtbl#VALfind_opt) [[Hashtbl](hashtbl)] | `Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. |
| [find\_opt](ephemeron.seededs#VALfind_opt) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [find\_opt](ephemeron.s#VALfind_opt) [[Ephemeron.S](ephemeron.s)] | |
| [find\_opt](arraylabels#VALfind_opt) [[ArrayLabels](arraylabels)] | `find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. |
| [find\_opt](array#VALfind_opt) [[Array](array)] | `find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. |
| [find\_right](either#VALfind_right) [[Either](either)] | `find_right (Right v)` is `Some v`, `find_right (Left _)` is `None` |
| [first\_chars](str#VALfirst_chars) [[Str](str)] | `first_chars s n` returns the first `n` characters of `s`. |
| [first\_non\_constant\_constructor\_tag](obj#VALfirst_non_constant_constructor_tag) [[Obj](obj)] | |
| [flat\_map](seq#VALflat_map) [[Seq](seq)] | `flat_map f xs` is equivalent to `concat (map f xs)`. |
| [flatten](listlabels#VALflatten) [[ListLabels](listlabels)] | Same as [`ListLabels.concat`](listlabels#VALconcat). |
| [flatten](list#VALflatten) [[List](list)] | Same as [`List.concat`](list#VALconcat). |
| [flip](fun#VALflip) [[Fun](fun)] | `flip f` reverses the argument order of the binary function `f`. |
| [float](random.state#VALfloat) [[Random.State](random.state)] | |
| [float](random#VALfloat) [[Random](random)] | `Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). |
| [float](stdlib#VALfloat) [[Stdlib](stdlib)] | Same as [`float_of_int`](stdlib#VALfloat_of_int). |
| [float32](bigarray#VALfloat32) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [float64](bigarray#VALfloat64) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [float\_of\_bits](int64#VALfloat_of_bits) [[Int64](int64)] | Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`. |
| [float\_of\_bits](int32#VALfloat_of_bits) [[Int32](int32)] | Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`. |
| [float\_of\_int](stdlib#VALfloat_of_int) [[Stdlib](stdlib)] | Convert an integer to floating-point. |
| [float\_of\_string](stdlib#VALfloat_of_string) [[Stdlib](stdlib)] | Same as [`float_of_string_opt`](stdlib#VALfloat_of_string_opt), but raise `Failure "float\_of\_string"` instead of returning `None`. |
| [float\_of\_string\_opt](stdlib#VALfloat_of_string_opt) [[Stdlib](stdlib)] | Convert the given string to a float. |
| [floor](float#VALfloor) [[Float](float)] | Round below to an integer value. |
| [floor](stdlib#VALfloor) [[Stdlib](stdlib)] | Round below to an integer value. |
| [flush](out_channel#VALflush) [[Out\_channel](out_channel)] | Flush the buffer associated with the given output channel, performing all pending writes on that channel. |
| [flush](stdlib#VALflush) [[Stdlib](stdlib)] | Flush the buffer associated with the given output channel, performing all pending writes on that channel. |
| [flush\_all](out_channel#VALflush_all) [[Out\_channel](out_channel)] | Flush all open output channels; ignore errors. |
| [flush\_all](stdlib#VALflush_all) [[Stdlib](stdlib)] | Flush all open output channels; ignore errors. |
| [flush\_input](lexing#VALflush_input) [[Lexing](lexing)] | Discard the contents of the buffer and reset the current position to 0. |
| [flush\_str\_formatter](format#VALflush_str_formatter) [[Format](format)] | Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer. |
| [flush\_symbolic\_output\_buffer](format#VALflush_symbolic_output_buffer) [[Format](format)] | `flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. |
| [fma](float#VALfma) [[Float](float)] | `fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation. |
| [fmt\_ebb\_of\_string](camlinternalformat#VALfmt_ebb_of_string) [[CamlinternalFormat](camlinternalformat)] | |
| [fold](weak.s#VALfold) [[Weak.S](weak.s)] | `fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. |
| [fold](stack#VALfold) [[Stack](stack)] | `fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. |
| [fold](set.s#VALfold) [[Set.S](set.s)] | `fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. |
| [fold](result#VALfold) [[Result](result)] | `fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`. |
| [fold](queue#VALfold) [[Queue](queue)] | `fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. |
| [fold](option#VALfold) [[Option](option)] | `fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`. |
| [fold](morelabels.set.s#VALfold) [[MoreLabels.Set.S](morelabels.set.s)] | `fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. |
| [fold](morelabels.map.s#VALfold) [[MoreLabels.Map.S](morelabels.map.s)] | `fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. |
| [fold](morelabels.hashtbl.seededs#VALfold) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [fold](morelabels.hashtbl.s#VALfold) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [fold](morelabels.hashtbl#VALfold) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. |
| [fold](map.s#VALfold) [[Map.S](map.s)] | `fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. |
| [fold](hashtbl.seededs#VALfold) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [fold](hashtbl.s#VALfold) [[Hashtbl.S](hashtbl.s)] | |
| [fold](hashtbl#VALfold) [[Hashtbl](hashtbl)] | `Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. |
| [fold](either#VALfold) [[Either](either)] | `fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`. |
| [fold\_left](string#VALfold_left) [[String](string)] | `fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. |
| [fold\_left](stringlabels#VALfold_left) [[StringLabels](stringlabels)] | `fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. |
| [fold\_left](seq#VALfold_left) [[Seq](seq)] | `fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right. |
| [fold\_left](listlabels#VALfold_left) [[ListLabels](listlabels)] | `fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. |
| [fold\_left](list#VALfold_left) [[List](list)] | `fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. |
| [fold\_left](float.arraylabels#VALfold_left) [[Float.ArrayLabels](float.arraylabels)] | `fold_left ~f x ~init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. |
| [fold\_left](float.array#VALfold_left) [[Float.Array](float.array)] | `fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. |
| [fold\_left](byteslabels#VALfold_left) [[BytesLabels](byteslabels)] | `fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. |
| [fold\_left](bytes#VALfold_left) [[Bytes](bytes)] | `fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. |
| [fold\_left](arraylabels#VALfold_left) [[ArrayLabels](arraylabels)] | `fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. |
| [fold\_left](array#VALfold_left) [[Array](array)] | `fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. |
| [fold\_left2](seq#VALfold_left2) [[Seq](seq)] | `fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. |
| [fold\_left2](listlabels#VALfold_left2) [[ListLabels](listlabels)] | `fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. |
| [fold\_left2](list#VALfold_left2) [[List](list)] | `fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. |
| [fold\_left\_map](listlabels#VALfold_left_map) [[ListLabels](listlabels)] | `fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. |
| [fold\_left\_map](list#VALfold_left_map) [[List](list)] | `fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. |
| [fold\_left\_map](arraylabels#VALfold_left_map) [[ArrayLabels](arraylabels)] | `fold_left_map` is a combination of [`ArrayLabels.fold_left`](arraylabels#VALfold_left) and [`ArrayLabels.map`](arraylabels#VALmap) that threads an accumulator through calls to `f`. |
| [fold\_left\_map](array#VALfold_left_map) [[Array](array)] | `fold_left_map` is a combination of [`Array.fold_left`](array#VALfold_left) and [`Array.map`](array#VALmap) that threads an accumulator through calls to `f`. |
| [fold\_lefti](seq#VALfold_lefti) [[Seq](seq)] | `fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`. |
| [fold\_right](string#VALfold_right) [[String](string)] | `fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. |
| [fold\_right](stringlabels#VALfold_right) [[StringLabels](stringlabels)] | `fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. |
| [fold\_right](listlabels#VALfold_right) [[ListLabels](listlabels)] | `fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. |
| [fold\_right](list#VALfold_right) [[List](list)] | `fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. |
| [fold\_right](float.arraylabels#VALfold_right) [[Float.ArrayLabels](float.arraylabels)] | `fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. |
| [fold\_right](float.array#VALfold_right) [[Float.Array](float.array)] | `fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. |
| [fold\_right](byteslabels#VALfold_right) [[BytesLabels](byteslabels)] | `fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. |
| [fold\_right](bytes#VALfold_right) [[Bytes](bytes)] | `fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. |
| [fold\_right](arraylabels#VALfold_right) [[ArrayLabels](arraylabels)] | `fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. |
| [fold\_right](array#VALfold_right) [[Array](array)] | `fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. |
| [fold\_right2](listlabels#VALfold_right2) [[ListLabels](listlabels)] | `fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. |
| [fold\_right2](list#VALfold_right2) [[List](list)] | `fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. |
| [for\_all](string#VALfor_all) [[String](string)] | `for_all p s` checks if all characters in `s` satisfy the predicate `p`. |
| [for\_all](stringlabels#VALfor_all) [[StringLabels](stringlabels)] | `for_all p s` checks if all characters in `s` satisfy the predicate `p`. |
| [for\_all](set.s#VALfor_all) [[Set.S](set.s)] | `for_all f s` checks if all elements of the set satisfy the predicate `f`. |
| [for\_all](seq#VALfor_all) [[Seq](seq)] | `for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`. |
| [for\_all](morelabels.set.s#VALfor_all) [[MoreLabels.Set.S](morelabels.set.s)] | `for_all ~f s` checks if all elements of the set satisfy the predicate `f`. |
| [for\_all](morelabels.map.s#VALfor_all) [[MoreLabels.Map.S](morelabels.map.s)] | `for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. |
| [for\_all](map.s#VALfor_all) [[Map.S](map.s)] | `for_all f m` checks if all the bindings of the map satisfy the predicate `f`. |
| [for\_all](listlabels#VALfor_all) [[ListLabels](listlabels)] | `for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. |
| [for\_all](list#VALfor_all) [[List](list)] | `for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. |
| [for\_all](float.arraylabels#VALfor_all) [[Float.ArrayLabels](float.arraylabels)] | `for_all ~f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. |
| [for\_all](float.array#VALfor_all) [[Float.Array](float.array)] | `for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. |
| [for\_all](either#VALfor_all) [[Either](either)] | `for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`. |
| [for\_all](byteslabels#VALfor_all) [[BytesLabels](byteslabels)] | `for_all p s` checks if all characters in `s` satisfy the predicate `p`. |
| [for\_all](bytes#VALfor_all) [[Bytes](bytes)] | `for_all p s` checks if all characters in `s` satisfy the predicate `p`. |
| [for\_all](arraylabels#VALfor_all) [[ArrayLabels](arraylabels)] | `for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. |
| [for\_all](array#VALfor_all) [[Array](array)] | `for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. |
| [for\_all2](seq#VALfor_all2) [[Seq](seq)] | `for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`. |
| [for\_all2](listlabels#VALfor_all2) [[ListLabels](listlabels)] | Same as [`ListLabels.for_all`](listlabels#VALfor_all), but for a two-argument predicate. |
| [for\_all2](list#VALfor_all2) [[List](list)] | Same as [`List.for_all`](list#VALfor_all), but for a two-argument predicate. |
| [for\_all2](arraylabels#VALfor_all2) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.for_all`](arraylabels#VALfor_all), but for a two-argument predicate. |
| [for\_all2](array#VALfor_all2) [[Array](array)] | Same as [`Array.for_all`](array#VALfor_all), but for a two-argument predicate. |
| [force](lazy#VALforce) [[Lazy](lazy)] | `force x` forces the suspension `x` and returns its result. |
| [force\_gen](camlinternallazy#VALforce_gen) [[CamlinternalLazy](camlinternallazy)] | |
| [force\_lazy\_block](camlinternallazy#VALforce_lazy_block) [[CamlinternalLazy](camlinternallazy)] | |
| [force\_newline](format#VALforce_newline) [[Format](format)] | Force a new line in the current pretty-printing box. |
| [force\_val](lazy#VALforce_val) [[Lazy](lazy)] | `force_val x` forces the suspension `x` and returns its result. |
| [forcing\_tag](obj#VALforcing_tag) [[Obj](obj)] | |
| [forever](seq#VALforever) [[Seq](seq)] | `forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`. |
| [fork](unixlabels#VALfork) [[UnixLabels](unixlabels)] | Fork a new process. |
| [fork](unix#VALfork) [[Unix](unix)] | Fork a new process. |
| [format](printexc.slot#VALformat) [[Printexc.Slot](printexc.slot)] | `format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`-th element of the backtrace: the `0`-th element is pretty-printed differently than the others. |
| [format\_from\_string](scanf#VALformat_from_string) [[Scanf](scanf)] | `format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`. |
| [format\_of\_string](stdlib#VALformat_of_string) [[Stdlib](stdlib)] | `format_of_string s` returns a format string read from the string literal `s`. |
| [format\_of\_string\_fmtty](camlinternalformat#VALformat_of_string_fmtty) [[CamlinternalFormat](camlinternalformat)] | |
| [format\_of\_string\_format](camlinternalformat#VALformat_of_string_format) [[CamlinternalFormat](camlinternalformat)] | |
| [formatter\_of\_buffer](format#VALformatter_of_buffer) [[Format](format)] | `formatter_of_buffer b` returns a new formatter writing to buffer `b`. |
| [formatter\_of\_out\_channel](format#VALformatter_of_out_channel) [[Format](format)] | `formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`. |
| [formatter\_of\_out\_functions](format#VALformatter_of_out_functions) [[Format](format)] | `formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`. |
| [formatter\_of\_symbolic\_output\_buffer](format#VALformatter_of_symbolic_output_buffer) [[Format](format)] | `formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`. |
| [fortran\_layout](bigarray#VALfortran_layout) [[Bigarray](bigarray)] | |
| [forward\_tag](obj#VALforward_tag) [[Obj](obj)] | |
| [fprintf](printf#VALfprintf) [[Printf](printf)] | `fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`. |
| [fprintf](format#VALfprintf) [[Format](format)] | |
| [free\_cursor](runtime_events#VALfree_cursor) [[Runtime\_events](runtime_events)] | Free a previously created runtime\_events cursor |
| [freeze\_char\_set](camlinternalformat#VALfreeze_char_set) [[CamlinternalFormat](camlinternalformat)] | |
| [frexp](float#VALfrexp) [[Float](float)] | `frexp f` returns the pair of the significant and the exponent of `f`. |
| [frexp](stdlib#VALfrexp) [[Stdlib](stdlib)] | `frexp f` returns the pair of the significant and the exponent of `f`. |
| [from\_bytes](marshal#VALfrom_bytes) [[Marshal](marshal)] | `Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](marshal#VALfrom_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. |
| [from\_channel](scanf.scanning#VALfrom_channel) [[Scanf.Scanning](scanf.scanning)] | `Scanning.from_channel ic` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel which reads from the regular [`in_channel`](stdlib#TYPEin_channel) input channel `ic` argument. |
| [from\_channel](marshal#VALfrom_channel) [[Marshal](marshal)] | `Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value. |
| [from\_channel](lexing#VALfrom_channel) [[Lexing](lexing)] | Create a lexer buffer on the given input channel. |
| [from\_file](scanf.scanning#VALfrom_file) [[Scanf.Scanning](scanf.scanning)] | An alias for [`Scanf.Scanning.open_in`](scanf.scanning#VALopen_in) above. |
| [from\_file\_bin](scanf.scanning#VALfrom_file_bin) [[Scanf.Scanning](scanf.scanning)] | An alias for [`Scanf.Scanning.open_in_bin`](scanf.scanning#VALopen_in_bin) above. |
| [from\_fun](lazy#VALfrom_fun) [[Lazy](lazy)] | `from_fun f` is the same as `lazy (f ())` but slightly more efficient. |
| [from\_function](scanf.scanning#VALfrom_function) [[Scanf.Scanning](scanf.scanning)] | `Scanning.from_function f` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel with the given function as its reading method. |
| [from\_function](lexing#VALfrom_function) [[Lexing](lexing)] | Create a lexer buffer with the given function as its reading method. |
| [from\_hex](digest#VALfrom_hex) [[Digest](digest)] | Convert a hexadecimal representation back into the corresponding digest. |
| [from\_string](scanf.scanning#VALfrom_string) [[Scanf.Scanning](scanf.scanning)] | `Scanning.from_string s` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel which reads from the given string. |
| [from\_string](marshal#VALfrom_string) [[Marshal](marshal)] | Same as `from_bytes` but take a string as argument instead of a byte sequence. |
| [from\_string](lexing#VALfrom_string) [[Lexing](lexing)] | Create a lexer buffer which reads from the given string. |
| [from\_val](lazy#VALfrom_val) [[Lazy](lazy)] | `from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. |
| [fst](stdlib#VALfst) [[Stdlib](stdlib)] | Return the first component of a pair. |
| [fstat](unixlabels.largefile#VALfstat) [[UnixLabels.LargeFile](unixlabels.largefile)] | |
| [fstat](unixlabels#VALfstat) [[UnixLabels](unixlabels)] | Return the information for the file associated with the given descriptor. |
| [fstat](unix.largefile#VALfstat) [[Unix.LargeFile](unix.largefile)] | |
| [fstat](unix#VALfstat) [[Unix](unix)] | Return the information for the file associated with the given descriptor. |
| [fsync](unixlabels#VALfsync) [[UnixLabels](unixlabels)] | Flush file buffers to disk. |
| [fsync](unix#VALfsync) [[Unix](unix)] | Flush file buffers to disk. |
| [ftruncate](unixlabels.largefile#VALftruncate) [[UnixLabels.LargeFile](unixlabels.largefile)] | See `ftruncate`. |
| [ftruncate](unixlabels#VALftruncate) [[UnixLabels](unixlabels)] | Truncates the file corresponding to the given descriptor to the given size. |
| [ftruncate](unix.largefile#VALftruncate) [[Unix.LargeFile](unix.largefile)] | See `ftruncate`. |
| [ftruncate](unix#VALftruncate) [[Unix](unix)] | Truncates the file corresponding to the given descriptor to the given size. |
| [full\_init](random#VALfull_init) [[Random](random)] | Same as [`Random.init`](random#VALinit) but takes more data as seed. |
| [full\_int](random.state#VALfull_int) [[Random.State](random.state)] | |
| [full\_int](random#VALfull_int) [[Random](random)] | `Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). |
| [full\_major](gc#VALfull_major) [[Gc](gc)] | Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. |
| [full\_split](str#VALfull_split) [[Str](str)] | Same as [`Str.split_delim`](str#VALsplit_delim), but returns the delimiters as well as the substrings contained between delimiters. |
| G |
| [genarray\_of\_array0](bigarray#VALgenarray_of_array0) [[Bigarray](bigarray)] | Return the generic Bigarray corresponding to the given zero-dimensional Bigarray. |
| [genarray\_of\_array1](bigarray#VALgenarray_of_array1) [[Bigarray](bigarray)] | Return the generic Bigarray corresponding to the given one-dimensional Bigarray. |
| [genarray\_of\_array2](bigarray#VALgenarray_of_array2) [[Bigarray](bigarray)] | Return the generic Bigarray corresponding to the given two-dimensional Bigarray. |
| [genarray\_of\_array3](bigarray#VALgenarray_of_array3) [[Bigarray](bigarray)] | Return the generic Bigarray corresponding to the given three-dimensional Bigarray. |
| [get](weak#VALget) [[Weak](weak)] | `Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full. |
| [get](string#VALget) [[String](string)] | `get s i` is the character at index `i` in `s`. |
| [get](stringlabels#VALget) [[StringLabels](stringlabels)] | `get s i` is the character at index `i` in `s`. |
| [get](option#VALget) [[Option](option)] | `get o` is `v` if `o` is `Some v` and raise otherwise. |
| [get](gc#VALget) [[Gc](gc)] | Return the current values of the GC parameters in a `control` record. |
| [get](float.arraylabels#VALget) [[Float.ArrayLabels](float.arraylabels)] | `get a n` returns the element number `n` of floatarray `a`. |
| [get](float.array#VALget) [[Float.Array](float.array)] | `get a n` returns the element number `n` of floatarray `a`. |
| [get](domain.dls#VALget) [[Domain.DLS](domain.dls)] | `get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. |
| [get](byteslabels#VALget) [[BytesLabels](byteslabels)] | `get s n` returns the byte at index `n` in argument `s`. |
| [get](bytes#VALget) [[Bytes](bytes)] | `get s n` returns the byte at index `n` in argument `s`. |
| [get](bigarray.array3#VALget) [[Bigarray.Array3](bigarray.array3)] | `Array3.get a x y z`, also written `a.{x,y,z}`, returns the element of `a` at coordinates (`x`, `y`, `z`). |
| [get](bigarray.array2#VALget) [[Bigarray.Array2](bigarray.array2)] | `Array2.get a x y`, also written `a.{x,y}`, returns the element of `a` at coordinates (`x`, `y`). |
| [get](bigarray.array1#VALget) [[Bigarray.Array1](bigarray.array1)] | `Array1.get a x`, or alternatively `a.{x}`, returns the element of `a` at index `x`. |
| [get](bigarray.array0#VALget) [[Bigarray.Array0](bigarray.array0)] | `Array0.get a` returns the only element in `a`. |
| [get](bigarray.genarray#VALget) [[Bigarray.Genarray](bigarray.genarray)] | Read an element of a generic Bigarray. |
| [get](atomic#VALget) [[Atomic](atomic)] | Get the current value of the atomic reference. |
| [get](arraylabels#VALget) [[ArrayLabels](arraylabels)] | `get a n` returns the element number `n` of array `a`. |
| [get](array#VALget) [[Array](array)] | `get a n` returns the element number `n` of array `a`. |
| [get\_backtrace](printexc#VALget_backtrace) [[Printexc](printexc)] | `Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. |
| [get\_callstack](printexc#VALget_callstack) [[Printexc](printexc)] | `Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. |
| [get\_callstack](effect.shallow#VALget_callstack) [[Effect.Shallow](effect.shallow)] | `get_callstack c n` returns a description of the top of the call stack on the continuation `c`, with at most `n` entries. |
| [get\_callstack](effect.deep#VALget_callstack) [[Effect.Deep](effect.deep)] | `get_callstack c n` returns a description of the top of the call stack on the continuation `c`, with at most `n` entries. |
| [get\_copy](weak#VALget_copy) [[Weak](weak)] | `Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. |
| [get\_data](obj.ephemeron#VALget_data) [[Obj.Ephemeron](obj.ephemeron)] | |
| [get\_data\_copy](obj.ephemeron#VALget_data_copy) [[Obj.Ephemeron](obj.ephemeron)] | |
| [get\_ellipsis\_text](format#VALget_ellipsis_text) [[Format](format)] | Return the text of the ellipsis. |
| [get\_err\_formatter](format#VALget_err_formatter) [[Format](format)] | `get_err_formatter ()` returns the current domain's formatter used to write to standard error. |
| [get\_error](result#VALget_error) [[Result](result)] | `get_error r` is `e` if `r` is `Error e` and raise otherwise. |
| [get\_formatter\_out\_functions](format#VALget_formatter_out_functions) [[Format](format)] | Return the current output functions of the pretty-printer, including line splitting and indentation functions. |
| [get\_formatter\_output\_functions](format#VALget_formatter_output_functions) [[Format](format)] | Return the current output functions of the standard pretty-printer. |
| [get\_formatter\_stag\_functions](format#VALget_formatter_stag_functions) [[Format](format)] | Return the current semantic tag operation functions of the standard pretty-printer. |
| [get\_geometry](format#VALget_geometry) [[Format](format)] | Return the current geometry of the formatter |
| [get\_id](domain#VALget_id) [[Domain](domain)] | `get_id d` returns the identifier of the domain `d` |
| [get\_int16\_be](string#VALget_int16_be) [[String](string)] | `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. |
| [get\_int16\_be](stringlabels#VALget_int16_be) [[StringLabels](stringlabels)] | `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. |
| [get\_int16\_be](byteslabels#VALget_int16_be) [[BytesLabels](byteslabels)] | `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. |
| [get\_int16\_be](bytes#VALget_int16_be) [[Bytes](bytes)] | `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. |
| [get\_int16\_le](string#VALget_int16_le) [[String](string)] | `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. |
| [get\_int16\_le](stringlabels#VALget_int16_le) [[StringLabels](stringlabels)] | `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. |
| [get\_int16\_le](byteslabels#VALget_int16_le) [[BytesLabels](byteslabels)] | `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. |
| [get\_int16\_le](bytes#VALget_int16_le) [[Bytes](bytes)] | `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. |
| [get\_int16\_ne](string#VALget_int16_ne) [[String](string)] | `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. |
| [get\_int16\_ne](stringlabels#VALget_int16_ne) [[StringLabels](stringlabels)] | `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. |
| [get\_int16\_ne](byteslabels#VALget_int16_ne) [[BytesLabels](byteslabels)] | `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. |
| [get\_int16\_ne](bytes#VALget_int16_ne) [[Bytes](bytes)] | `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. |
| [get\_int32\_be](string#VALget_int32_be) [[String](string)] | `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. |
| [get\_int32\_be](stringlabels#VALget_int32_be) [[StringLabels](stringlabels)] | `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. |
| [get\_int32\_be](byteslabels#VALget_int32_be) [[BytesLabels](byteslabels)] | `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. |
| [get\_int32\_be](bytes#VALget_int32_be) [[Bytes](bytes)] | `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. |
| [get\_int32\_le](string#VALget_int32_le) [[String](string)] | `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. |
| [get\_int32\_le](stringlabels#VALget_int32_le) [[StringLabels](stringlabels)] | `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. |
| [get\_int32\_le](byteslabels#VALget_int32_le) [[BytesLabels](byteslabels)] | `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. |
| [get\_int32\_le](bytes#VALget_int32_le) [[Bytes](bytes)] | `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. |
| [get\_int32\_ne](string#VALget_int32_ne) [[String](string)] | `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. |
| [get\_int32\_ne](stringlabels#VALget_int32_ne) [[StringLabels](stringlabels)] | `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. |
| [get\_int32\_ne](byteslabels#VALget_int32_ne) [[BytesLabels](byteslabels)] | `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. |
| [get\_int32\_ne](bytes#VALget_int32_ne) [[Bytes](bytes)] | `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. |
| [get\_int64\_be](string#VALget_int64_be) [[String](string)] | `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. |
| [get\_int64\_be](stringlabels#VALget_int64_be) [[StringLabels](stringlabels)] | `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. |
| [get\_int64\_be](byteslabels#VALget_int64_be) [[BytesLabels](byteslabels)] | `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. |
| [get\_int64\_be](bytes#VALget_int64_be) [[Bytes](bytes)] | `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. |
| [get\_int64\_le](string#VALget_int64_le) [[String](string)] | `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. |
| [get\_int64\_le](stringlabels#VALget_int64_le) [[StringLabels](stringlabels)] | `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. |
| [get\_int64\_le](byteslabels#VALget_int64_le) [[BytesLabels](byteslabels)] | `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. |
| [get\_int64\_le](bytes#VALget_int64_le) [[Bytes](bytes)] | `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. |
| [get\_int64\_ne](string#VALget_int64_ne) [[String](string)] | `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. |
| [get\_int64\_ne](stringlabels#VALget_int64_ne) [[StringLabels](stringlabels)] | `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. |
| [get\_int64\_ne](byteslabels#VALget_int64_ne) [[BytesLabels](byteslabels)] | `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. |
| [get\_int64\_ne](bytes#VALget_int64_ne) [[Bytes](bytes)] | `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. |
| [get\_int8](string#VALget_int8) [[String](string)] | `get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. |
| [get\_int8](stringlabels#VALget_int8) [[StringLabels](stringlabels)] | `get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. |
| [get\_int8](byteslabels#VALget_int8) [[BytesLabels](byteslabels)] | `get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. |
| [get\_int8](bytes#VALget_int8) [[Bytes](bytes)] | `get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. |
| [get\_key](obj.ephemeron#VALget_key) [[Obj.Ephemeron](obj.ephemeron)] | |
| [get\_key\_copy](obj.ephemeron#VALget_key_copy) [[Obj.Ephemeron](obj.ephemeron)] | |
| [get\_margin](format#VALget_margin) [[Format](format)] | Returns the position of the right margin. |
| [get\_mark\_tags](format#VALget_mark_tags) [[Format](format)] | Return the current status of tag-marking operations. |
| [get\_max\_boxes](format#VALget_max_boxes) [[Format](format)] | Returns the maximum number of pretty-printing boxes allowed before ellipsis. |
| [get\_max\_indent](format#VALget_max_indent) [[Format](format)] | Return the maximum indentation limit (in characters). |
| [get\_method](camlinternaloo#VALget_method) [[CamlinternalOO](camlinternaloo)] | |
| [get\_method\_label](camlinternaloo#VALget_method_label) [[CamlinternalOO](camlinternaloo)] | |
| [get\_method\_labels](camlinternaloo#VALget_method_labels) [[CamlinternalOO](camlinternaloo)] | |
| [get\_minor\_free](gc#VALget_minor_free) [[Gc](gc)] | Return the current size of the free space inside the minor heap of this domain. |
| [get\_ok](result#VALget_ok) [[Result](result)] | `get_ok r` is `v` if `r` is `Ok v` and raise otherwise. |
| [get\_print\_tags](format#VALget_print_tags) [[Format](format)] | Return the current status of tag-printing operations. |
| [get\_public\_method](camlinternaloo#VALget_public_method) [[CamlinternalOO](camlinternaloo)] | |
| [get\_raw\_backtrace](printexc#VALget_raw_backtrace) [[Printexc](printexc)] | `Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. |
| [get\_raw\_backtrace\_next\_slot](printexc#VALget_raw_backtrace_next_slot) [[Printexc](printexc)] | `get_raw_backtrace_next_slot slot` returns the next slot inlined, if any. |
| [get\_raw\_backtrace\_slot](printexc#VALget_raw_backtrace_slot) [[Printexc](printexc)] | `get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`. |
| [get\_state](random#VALget_state) [[Random](random)] | `get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). |
| [get\_std\_formatter](format#VALget_std_formatter) [[Format](format)] | `get_std_formatter ()` returns the current domain's standard formatter used to write to standard output. |
| [get\_stdbuf](format#VALget_stdbuf) [[Format](format)] | `get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes. |
| [get\_str\_formatter](format#VALget_str_formatter) [[Format](format)] | The current domain's formatter to output to the current domains string buffer. |
| [get\_symbolic\_output\_buffer](format#VALget_symbolic_output_buffer) [[Format](format)] | `get_symbolic_output_buffer sob` returns the contents of buffer `sob`. |
| [get\_temp\_dir\_name](filename#VALget_temp_dir_name) [[Filename](filename)] | The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. |
| [get\_uint16\_be](string#VALget_uint16_be) [[String](string)] | `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. |
| [get\_uint16\_be](stringlabels#VALget_uint16_be) [[StringLabels](stringlabels)] | `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. |
| [get\_uint16\_be](byteslabels#VALget_uint16_be) [[BytesLabels](byteslabels)] | `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. |
| [get\_uint16\_be](bytes#VALget_uint16_be) [[Bytes](bytes)] | `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. |
| [get\_uint16\_le](string#VALget_uint16_le) [[String](string)] | `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. |
| [get\_uint16\_le](stringlabels#VALget_uint16_le) [[StringLabels](stringlabels)] | `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. |
| [get\_uint16\_le](byteslabels#VALget_uint16_le) [[BytesLabels](byteslabels)] | `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. |
| [get\_uint16\_le](bytes#VALget_uint16_le) [[Bytes](bytes)] | `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. |
| [get\_uint16\_ne](string#VALget_uint16_ne) [[String](string)] | `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. |
| [get\_uint16\_ne](stringlabels#VALget_uint16_ne) [[StringLabels](stringlabels)] | `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. |
| [get\_uint16\_ne](byteslabels#VALget_uint16_ne) [[BytesLabels](byteslabels)] | `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. |
| [get\_uint16\_ne](bytes#VALget_uint16_ne) [[Bytes](bytes)] | `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. |
| [get\_uint8](string#VALget_uint8) [[String](string)] | `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. |
| [get\_uint8](stringlabels#VALget_uint8) [[StringLabels](stringlabels)] | `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. |
| [get\_uint8](byteslabels#VALget_uint8) [[BytesLabels](byteslabels)] | `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. |
| [get\_uint8](bytes#VALget_uint8) [[Bytes](bytes)] | `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. |
| [get\_utf\_16be\_uchar](string#VALget_utf_16be_uchar) [[String](string)] | `get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`. |
| [get\_utf\_16be\_uchar](stringlabels#VALget_utf_16be_uchar) [[StringLabels](stringlabels)] | `get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`. |
| [get\_utf\_16be\_uchar](byteslabels#VALget_utf_16be_uchar) [[BytesLabels](byteslabels)] | `get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`. |
| [get\_utf\_16be\_uchar](bytes#VALget_utf_16be_uchar) [[Bytes](bytes)] | `get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`. |
| [get\_utf\_16le\_uchar](string#VALget_utf_16le_uchar) [[String](string)] | `get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`. |
| [get\_utf\_16le\_uchar](stringlabels#VALget_utf_16le_uchar) [[StringLabels](stringlabels)] | `get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`. |
| [get\_utf\_16le\_uchar](byteslabels#VALget_utf_16le_uchar) [[BytesLabels](byteslabels)] | `get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`. |
| [get\_utf\_16le\_uchar](bytes#VALget_utf_16le_uchar) [[Bytes](bytes)] | `get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`. |
| [get\_utf\_8\_uchar](string#VALget_utf_8_uchar) [[String](string)] | `get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`. |
| [get\_utf\_8\_uchar](stringlabels#VALget_utf_8_uchar) [[StringLabels](stringlabels)] | `get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`. |
| [get\_utf\_8\_uchar](byteslabels#VALget_utf_8_uchar) [[BytesLabels](byteslabels)] | `get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`. |
| [get\_utf\_8\_uchar](bytes#VALget_utf_8_uchar) [[Bytes](bytes)] | `get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`. |
| [get\_value](semaphore.counting#VALget_value) [[Semaphore.Counting](semaphore.counting)] | `get_value s` returns the current value of semaphore `s`. |
| [get\_variable](camlinternaloo#VALget_variable) [[CamlinternalOO](camlinternaloo)] | |
| [get\_variables](camlinternaloo#VALget_variables) [[CamlinternalOO](camlinternaloo)] | |
| [getaddrinfo](unixlabels#VALgetaddrinfo) [[UnixLabels](unixlabels)] | `getaddrinfo host service opts` returns a list of [`UnixLabels.addr_info`](unixlabels#TYPEaddr_info) records describing socket parameters and addresses suitable for communicating with the given host and service. |
| [getaddrinfo](unix#VALgetaddrinfo) [[Unix](unix)] | `getaddrinfo host service opts` returns a list of [`Unix.addr_info`](unix#TYPEaddr_info) records describing socket parameters and addresses suitable for communicating with the given host and service. |
| [getcwd](unixlabels#VALgetcwd) [[UnixLabels](unixlabels)] | Return the name of the current working directory. |
| [getcwd](unix#VALgetcwd) [[Unix](unix)] | Return the name of the current working directory. |
| [getcwd](sys#VALgetcwd) [[Sys](sys)] | Return the current working directory of the process. |
| [getegid](unixlabels#VALgetegid) [[UnixLabels](unixlabels)] | Return the effective group id under which the process runs. |
| [getegid](unix#VALgetegid) [[Unix](unix)] | Return the effective group id under which the process runs. |
| [getenv](unixlabels#VALgetenv) [[UnixLabels](unixlabels)] | Return the value associated to a variable in the process environment, unless the process has special privileges. |
| [getenv](unix#VALgetenv) [[Unix](unix)] | Return the value associated to a variable in the process environment, unless the process has special privileges. |
| [getenv](sys#VALgetenv) [[Sys](sys)] | Return the value associated to a variable in the process environment. |
| [getenv\_opt](sys#VALgetenv_opt) [[Sys](sys)] | Return the value associated to a variable in the process environment or `None` if the variable is unbound. |
| [geteuid](unixlabels#VALgeteuid) [[UnixLabels](unixlabels)] | Return the effective user id under which the process runs. |
| [geteuid](unix#VALgeteuid) [[Unix](unix)] | Return the effective user id under which the process runs. |
| [getgid](unixlabels#VALgetgid) [[UnixLabels](unixlabels)] | Return the group id of the user executing the process. |
| [getgid](unix#VALgetgid) [[Unix](unix)] | Return the group id of the user executing the process. |
| [getgrgid](unixlabels#VALgetgrgid) [[UnixLabels](unixlabels)] | Find an entry in `group` with the given group id. |
| [getgrgid](unix#VALgetgrgid) [[Unix](unix)] | Find an entry in `group` with the given group id. |
| [getgrnam](unixlabels#VALgetgrnam) [[UnixLabels](unixlabels)] | Find an entry in `group` with the given name. |
| [getgrnam](unix#VALgetgrnam) [[Unix](unix)] | Find an entry in `group` with the given name. |
| [getgroups](unixlabels#VALgetgroups) [[UnixLabels](unixlabels)] | Return the list of groups to which the user executing the process belongs. |
| [getgroups](unix#VALgetgroups) [[Unix](unix)] | Return the list of groups to which the user executing the process belongs. |
| [gethostbyaddr](unixlabels#VALgethostbyaddr) [[UnixLabels](unixlabels)] | Find an entry in `hosts` with the given address. |
| [gethostbyaddr](unix#VALgethostbyaddr) [[Unix](unix)] | Find an entry in `hosts` with the given address. |
| [gethostbyname](unixlabels#VALgethostbyname) [[UnixLabels](unixlabels)] | Find an entry in `hosts` with the given name. |
| [gethostbyname](unix#VALgethostbyname) [[Unix](unix)] | Find an entry in `hosts` with the given name. |
| [gethostname](unixlabels#VALgethostname) [[UnixLabels](unixlabels)] | Return the name of the local host. |
| [gethostname](unix#VALgethostname) [[Unix](unix)] | Return the name of the local host. |
| [getitimer](unixlabels#VALgetitimer) [[UnixLabels](unixlabels)] | Return the current status of the given interval timer. |
| [getitimer](unix#VALgetitimer) [[Unix](unix)] | Return the current status of the given interval timer. |
| [getlogin](unixlabels#VALgetlogin) [[UnixLabels](unixlabels)] | Return the login name of the user executing the process. |
| [getlogin](unix#VALgetlogin) [[Unix](unix)] | Return the login name of the user executing the process. |
| [getnameinfo](unixlabels#VALgetnameinfo) [[UnixLabels](unixlabels)] | `getnameinfo addr opts` returns the host name and service name corresponding to the socket address `addr`. |
| [getnameinfo](unix#VALgetnameinfo) [[Unix](unix)] | `getnameinfo addr opts` returns the host name and service name corresponding to the socket address `addr`. |
| [getpeername](unixlabels#VALgetpeername) [[UnixLabels](unixlabels)] | Return the address of the host connected to the given socket. |
| [getpeername](unix#VALgetpeername) [[Unix](unix)] | Return the address of the host connected to the given socket. |
| [getpid](unixlabels#VALgetpid) [[UnixLabels](unixlabels)] | Return the pid of the process. |
| [getpid](unix#VALgetpid) [[Unix](unix)] | Return the pid of the process. |
| [getppid](unixlabels#VALgetppid) [[UnixLabels](unixlabels)] | Return the pid of the parent process. |
| [getppid](unix#VALgetppid) [[Unix](unix)] | Return the pid of the parent process. |
| [getprotobyname](unixlabels#VALgetprotobyname) [[UnixLabels](unixlabels)] | Find an entry in `protocols` with the given name. |
| [getprotobyname](unix#VALgetprotobyname) [[Unix](unix)] | Find an entry in `protocols` with the given name. |
| [getprotobynumber](unixlabels#VALgetprotobynumber) [[UnixLabels](unixlabels)] | Find an entry in `protocols` with the given protocol number. |
| [getprotobynumber](unix#VALgetprotobynumber) [[Unix](unix)] | Find an entry in `protocols` with the given protocol number. |
| [getpwnam](unixlabels#VALgetpwnam) [[UnixLabels](unixlabels)] | Find an entry in `passwd` with the given name. |
| [getpwnam](unix#VALgetpwnam) [[Unix](unix)] | Find an entry in `passwd` with the given name. |
| [getpwuid](unixlabels#VALgetpwuid) [[UnixLabels](unixlabels)] | Find an entry in `passwd` with the given user id. |
| [getpwuid](unix#VALgetpwuid) [[Unix](unix)] | Find an entry in `passwd` with the given user id. |
| [getservbyname](unixlabels#VALgetservbyname) [[UnixLabels](unixlabels)] | Find an entry in `services` with the given name. |
| [getservbyname](unix#VALgetservbyname) [[Unix](unix)] | Find an entry in `services` with the given name. |
| [getservbyport](unixlabels#VALgetservbyport) [[UnixLabels](unixlabels)] | Find an entry in `services` with the given service number. |
| [getservbyport](unix#VALgetservbyport) [[Unix](unix)] | Find an entry in `services` with the given service number. |
| [getsockname](unixlabels#VALgetsockname) [[UnixLabels](unixlabels)] | Return the address of the given socket. |
| [getsockname](unix#VALgetsockname) [[Unix](unix)] | Return the address of the given socket. |
| [getsockopt](unixlabels#VALgetsockopt) [[UnixLabels](unixlabels)] | Return the current status of a boolean-valued option in the given socket. |
| [getsockopt](unix#VALgetsockopt) [[Unix](unix)] | Return the current status of a boolean-valued option in the given socket. |
| [getsockopt\_error](unixlabels#VALgetsockopt_error) [[UnixLabels](unixlabels)] | Return the error condition associated with the given socket, and clear it. |
| [getsockopt\_error](unix#VALgetsockopt_error) [[Unix](unix)] | Return the error condition associated with the given socket, and clear it. |
| [getsockopt\_float](unixlabels#VALgetsockopt_float) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) for a socket option whose value is a floating-point number. |
| [getsockopt\_float](unix#VALgetsockopt_float) [[Unix](unix)] | Same as [`Unix.getsockopt`](unix#VALgetsockopt) for a socket option whose value is a floating-point number. |
| [getsockopt\_int](unixlabels#VALgetsockopt_int) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) for an integer-valued socket option. |
| [getsockopt\_int](unix#VALgetsockopt_int) [[Unix](unix)] | Same as [`Unix.getsockopt`](unix#VALgetsockopt) for an integer-valued socket option. |
| [getsockopt\_optint](unixlabels#VALgetsockopt_optint) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) for a socket option whose value is an `int option`. |
| [getsockopt\_optint](unix#VALgetsockopt_optint) [[Unix](unix)] | Same as [`Unix.getsockopt`](unix#VALgetsockopt) for a socket option whose value is an `int option`. |
| [gettimeofday](unixlabels#VALgettimeofday) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.time`](unixlabels#VALtime), but with resolution better than 1 second. |
| [gettimeofday](unix#VALgettimeofday) [[Unix](unix)] | Same as [`Unix.time`](unix#VALtime), but with resolution better than 1 second. |
| [getuid](unixlabels#VALgetuid) [[UnixLabels](unixlabels)] | Return the user id of the user executing the process. |
| [getuid](unix#VALgetuid) [[Unix](unix)] | Return the user id of the user executing the process. |
| [global\_replace](str#VALglobal_replace) [[Str](str)] | `global_replace regexp templ s` returns a string identical to `s`, except that all substrings of `s` that match `regexp` have been replaced by `templ`. |
| [global\_substitute](str#VALglobal_substitute) [[Str](str)] | `global_substitute regexp subst s` returns a string identical to `s`, except that all substrings of `s` that match `regexp` have been replaced by the result of function `subst`. |
| [gmtime](unixlabels#VALgmtime) [[UnixLabels](unixlabels)] | Convert a time in seconds, as returned by [`UnixLabels.time`](unixlabels#VALtime), into a date and a time. |
| [gmtime](unix#VALgmtime) [[Unix](unix)] | Convert a time in seconds, as returned by [`Unix.time`](unix#VALtime), into a date and a time. |
| [group](seq#VALgroup) [[Seq](seq)] | Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`. |
| [group\_beginning](str#VALgroup_beginning) [[Str](str)] | `group_beginning n` returns the position of the first character of the substring that was matched by the `n`th group of the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). |
| [group\_end](str#VALgroup_end) [[Str](str)] | `group_end n` returns the position of the character following the last character of substring that was matched by the `n`th group of the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). |
| [guard](event#VALguard) [[Event](event)] | `guard fn` returns the event that, when synchronized, computes `fn()` and behaves as the resulting event. |
| H |
| [handle\_unix\_error](unixlabels#VALhandle_unix_error) [[UnixLabels](unixlabels)] | `handle_unix_error f x` applies `f` to `x` and returns the result. |
| [handle\_unix\_error](unix#VALhandle_unix_error) [[Unix](unix)] | `handle_unix_error f x` applies `f` to `x` and returns the result. |
| [has\_symlink](unixlabels#VALhas_symlink) [[UnixLabels](unixlabels)] | Returns `true` if the user is able to create symbolic links. |
| [has\_symlink](unix#VALhas_symlink) [[Unix](unix)] | Returns `true` if the user is able to create symbolic links. |
| [hash](uchar#VALhash) [[Uchar](uchar)] | `hash u` associates a non-negative integer to `u`. |
| [hash](string#VALhash) [[String](string)] | An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](hashtbl#VALhash). |
| [hash](stringlabels#VALhash) [[StringLabels](stringlabels)] | An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](hashtbl#VALhash). |
| [hash](morelabels.hashtbl.hashedtype#VALhash) [[MoreLabels.Hashtbl.HashedType](morelabels.hashtbl.hashedtype)] | A hashing function on keys. |
| [hash](morelabels.hashtbl#VALhash) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.hash x` associates a nonnegative integer to any value of any type. |
| [hash](hashtbl.hashedtype#VALhash) [[Hashtbl.HashedType](hashtbl.hashedtype)] | A hashing function on keys. |
| [hash](hashtbl#VALhash) [[Hashtbl](hashtbl)] | `Hashtbl.hash x` associates a nonnegative integer to any value of any type. |
| [hash](float#VALhash) [[Float](float)] | The hash function for floating-point numbers. |
| [hash\_param](morelabels.hashtbl#VALhash_param) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. |
| [hash\_param](hashtbl#VALhash_param) [[Hashtbl](hashtbl)] | `Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. |
| [hd](listlabels#VALhd) [[ListLabels](listlabels)] | Return the first element of the given list. |
| [hd](list#VALhd) [[List](list)] | Return the first element of the given list. |
| [header\_size](marshal#VALheader_size) [[Marshal](marshal)] | The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. |
| [hypot](float#VALhypot) [[Float](float)] | `hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. |
| [hypot](stdlib#VALhypot) [[Stdlib](stdlib)] | `hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. |
| I |
| [i](complex#VALi) [[Complex](complex)] | The complex number `i`. |
| [ibprintf](printf#VALibprintf) [[Printf](printf)] | Same as [`Printf.bprintf`](printf#VALbprintf), but does not print anything. |
| [id](thread#VALid) [[Thread](thread)] | Return the identifier of the given thread. |
| [id](oo#VALid) [[Oo](oo)] | Return an integer identifying this object, unique for the current execution of the program. |
| [id](obj.extension_constructor#VALid) [[Obj.Extension\_constructor](obj.extension_constructor)] | |
| [id](fun#VALid) [[Fun](fun)] | `id` is the identity function. |
| [ifprintf](printf#VALifprintf) [[Printf](printf)] | Same as [`Printf.fprintf`](printf#VALfprintf), but does not print anything. |
| [ifprintf](format#VALifprintf) [[Format](format)] | Same as `fprintf` above, but does not print anything. |
| [ignore](stdlib#VALignore) [[Stdlib](stdlib)] | Discard the value of its argument and return `()`. |
| [ikbprintf](printf#VALikbprintf) [[Printf](printf)] | Same as `kbprintf` above, but does not print anything. |
| [ikfprintf](printf#VALikfprintf) [[Printf](printf)] | Same as `kfprintf` above, but does not print anything. |
| [ikfprintf](format#VALikfprintf) [[Format](format)] | Same as `kfprintf` above, but does not print anything. |
| [in\_channel\_length](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html#VALin_channel_length) [[Stdlib.LargeFile](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html)] | |
| [in\_channel\_length](stdlib#VALin_channel_length) [[Stdlib](stdlib)] | Return the size (number of characters) of the regular file on which the given channel is opened. |
| [in\_channel\_of\_descr](unixlabels#VALin_channel_of_descr) [[UnixLabels](unixlabels)] | Create an input channel reading from the given descriptor. |
| [in\_channel\_of\_descr](unix#VALin_channel_of_descr) [[Unix](unix)] | Create an input channel reading from the given descriptor. |
| [incr](atomic#VALincr) [[Atomic](atomic)] | `incr r` atomically increments the value of `r` by `1`. |
| [incr](stdlib#VALincr) [[Stdlib](stdlib)] | Increment the integer contained in the given reference. |
| [index](string#VALindex) [[String](string)] | `index s c` is [`String.index_from`](string#VALindex_from)`s 0 c`. |
| [index](stringlabels#VALindex) [[StringLabels](stringlabels)] | `index s c` is [`String.index_from`](string#VALindex_from)`s 0 c`. |
| [index](byteslabels#VALindex) [[BytesLabels](byteslabels)] | `index s c` returns the index of the first occurrence of byte `c` in `s`. |
| [index](bytes#VALindex) [[Bytes](bytes)] | `index s c` returns the index of the first occurrence of byte `c` in `s`. |
| [index\_from](string#VALindex_from) [[String](string)] | `index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. |
| [index\_from](stringlabels#VALindex_from) [[StringLabels](stringlabels)] | `index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. |
| [index\_from](byteslabels#VALindex_from) [[BytesLabels](byteslabels)] | `index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. |
| [index\_from](bytes#VALindex_from) [[Bytes](bytes)] | `index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. |
| [index\_from\_opt](string#VALindex_from_opt) [[String](string)] | `index_from_opt s i c` is the index of the first occurrence of `c` in `s` after position `i` (if any). |
| [index\_from\_opt](stringlabels#VALindex_from_opt) [[StringLabels](stringlabels)] | `index_from_opt s i c` is the index of the first occurrence of `c` in `s` after position `i` (if any). |
| [index\_from\_opt](byteslabels#VALindex_from_opt) [[BytesLabels](byteslabels)] | `index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. |
| [index\_from\_opt](bytes#VALindex_from_opt) [[Bytes](bytes)] | `index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. |
| [index\_opt](string#VALindex_opt) [[String](string)] | `index_opt s c` is [`String.index_from_opt`](string#VALindex_from_opt)`s 0 c`. |
| [index\_opt](stringlabels#VALindex_opt) [[StringLabels](stringlabels)] | `index_opt s c` is [`String.index_from_opt`](string#VALindex_from_opt)`s 0 c`. |
| [index\_opt](byteslabels#VALindex_opt) [[BytesLabels](byteslabels)] | `index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. |
| [index\_opt](bytes#VALindex_opt) [[Bytes](bytes)] | `index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. |
| [inet6\_addr\_any](unixlabels#VALinet6_addr_any) [[UnixLabels](unixlabels)] | A special IPv6 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses. |
| [inet6\_addr\_any](unix#VALinet6_addr_any) [[Unix](unix)] | A special IPv6 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses. |
| [inet6\_addr\_loopback](unixlabels#VALinet6_addr_loopback) [[UnixLabels](unixlabels)] | A special IPv6 address representing the host machine (`::1`). |
| [inet6\_addr\_loopback](unix#VALinet6_addr_loopback) [[Unix](unix)] | A special IPv6 address representing the host machine (`::1`). |
| [inet\_addr\_any](unixlabels#VALinet_addr_any) [[UnixLabels](unixlabels)] | A special IPv4 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses. |
| [inet\_addr\_any](unix#VALinet_addr_any) [[Unix](unix)] | A special IPv4 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses. |
| [inet\_addr\_loopback](unixlabels#VALinet_addr_loopback) [[UnixLabels](unixlabels)] | A special IPv4 address representing the host machine (`127.0.0.1`). |
| [inet\_addr\_loopback](unix#VALinet_addr_loopback) [[Unix](unix)] | A special IPv4 address representing the host machine (`127.0.0.1`). |
| [inet\_addr\_of\_string](unixlabels#VALinet_addr_of_string) [[UnixLabels](unixlabels)] | Conversion from the printable representation of an Internet address to its internal representation. |
| [inet\_addr\_of\_string](unix#VALinet_addr_of_string) [[Unix](unix)] | Conversion from the printable representation of an Internet address to its internal representation. |
| [infinity](float#VALinfinity) [[Float](float)] | Positive infinity. |
| [infinity](stdlib#VALinfinity) [[Stdlib](stdlib)] | Positive infinity. |
| [infix\_tag](obj#VALinfix_tag) [[Obj](obj)] | |
| [info](obj.closure#VALinfo) [[Obj.Closure](obj.closure)] | |
| [inherits](camlinternaloo#VALinherits) [[CamlinternalOO](camlinternaloo)] | |
| [init](string#VALinit) [[String](string)] | `init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). |
| [init](stringlabels#VALinit) [[StringLabels](stringlabels)] | `init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). |
| [init](seq#VALinit) [[Seq](seq)] | `init n f` is the sequence `f 0; f 1; ...; f (n-1)`. |
| [init](random#VALinit) [[Random](random)] | Initialize the domain-local generator, using the argument as a seed. |
| [init](listlabels#VALinit) [[ListLabels](listlabels)] | `init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. |
| [init](list#VALinit) [[List](list)] | `init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. |
| [init](float.arraylabels#VALinit) [[Float.ArrayLabels](float.arraylabels)] | `init n ~f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. |
| [init](float.array#VALinit) [[Float.Array](float.array)] | `init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. |
| [init](byteslabels#VALinit) [[BytesLabels](byteslabels)] | `init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). |
| [init](bytes#VALinit) [[Bytes](bytes)] | `init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). |
| [init](bigarray.array3#VALinit) [[Bigarray.Array3](bigarray.array3)] | `Array3.init kind layout dim1 dim2 dim3 f` returns a new Bigarray `b` of three dimensions, whose size is `dim1` in the first dimension, `dim2` in the second dimension, and `dim3` in the third. |
| [init](bigarray.array2#VALinit) [[Bigarray.Array2](bigarray.array2)] | `Array2.init kind layout dim1 dim2 f` returns a new Bigarray `b` of two dimensions, whose size is `dim2` in the first dimension and `dim2` in the second dimension. |
| [init](bigarray.array1#VALinit) [[Bigarray.Array1](bigarray.array1)] | `Array1.init kind layout dim f` returns a new Bigarray `b` of one dimension, whose size is `dim`. |
| [init](bigarray.array0#VALinit) [[Bigarray.Array0](bigarray.array0)] | `Array0.init kind layout v` behaves like `Array0.create kind layout` except that the element is additionally initialized to the value `v`. |
| [init](bigarray.genarray#VALinit) [[Bigarray.Genarray](bigarray.genarray)] | `Genarray.init kind layout dimensions f` returns a new Bigarray `b` whose element kind is determined by the parameter `kind` (one of `float32`, `float64`, `int8_signed`, etc) and whose layout is determined by the parameter `layout` (one of `c_layout` or `fortran_layout`). |
| [init](arraylabels#VALinit) [[ArrayLabels](arraylabels)] | `init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. |
| [init](array#VALinit) [[Array](array)] | `init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. |
| [init\_class](camlinternaloo#VALinit_class) [[CamlinternalOO](camlinternaloo)] | |
| [init\_mod](camlinternalmod#VALinit_mod) [[CamlinternalMod](camlinternalmod)] | |
| [initgroups](unixlabels#VALinitgroups) [[UnixLabels](unixlabels)] | `initgroups user group` initializes the group access list by reading the group database /etc/group and using all groups of which `user` is a member. |
| [initgroups](unix#VALinitgroups) [[Unix](unix)] | `initgroups user group` initializes the group access list by reading the group database /etc/group and using all groups of which `user` is a member. |
| [input](in_channel#VALinput) [[In\_channel](in_channel)] | `input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. |
| [input](digest#VALinput) [[Digest](digest)] | Read a digest from the given input channel. |
| [input](stdlib#VALinput) [[Stdlib](stdlib)] | `input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. |
| [input\_all](in_channel#VALinput_all) [[In\_channel](in_channel)] | `input_all ic` reads all remaining data from `ic`. |
| [input\_binary\_int](stdlib#VALinput_binary_int) [[Stdlib](stdlib)] | Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. |
| [input\_byte](in_channel#VALinput_byte) [[In\_channel](in_channel)] | Same as [`In\_channel.input_char`](in_channel#VALinput_char), but return the 8-bit integer representing the character. |
| [input\_byte](stdlib#VALinput_byte) [[Stdlib](stdlib)] | Same as [`input_char`](stdlib#VALinput_char), but return the 8-bit integer representing the character. |
| [input\_char](in_channel#VALinput_char) [[In\_channel](in_channel)] | Read one character from the given input channel. |
| [input\_char](stdlib#VALinput_char) [[Stdlib](stdlib)] | Read one character from the given input channel. |
| [input\_line](in_channel#VALinput_line) [[In\_channel](in_channel)] | `input_line ic` reads characters from `ic` until a newline or the end of file is reached. |
| [input\_line](stdlib#VALinput_line) [[Stdlib](stdlib)] | Read characters from the given input channel, until a newline character is encountered. |
| [input\_value](stdlib#VALinput_value) [[Stdlib](stdlib)] | Read the representation of a structured value, as produced by [`output_value`](stdlib#VALoutput_value), and return the corresponding value. |
| [int](random.state#VALint) [[Random.State](random.state)] | |
| [int](random#VALint) [[Random](random)] | `Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). |
| [int](bigarray#VALint) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int16\_signed](bigarray#VALint16_signed) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int16\_unsigned](bigarray#VALint16_unsigned) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int32](random.state#VALint32) [[Random.State](random.state)] | |
| [int32](random#VALint32) [[Random](random)] | `Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). |
| [int32](bigarray#VALint32) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int64](random.state#VALint64) [[Random.State](random.state)] | |
| [int64](random#VALint64) [[Random](random)] | `Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). |
| [int64](bigarray#VALint64) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int8\_signed](bigarray#VALint8_signed) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int8\_unsigned](bigarray#VALint8_unsigned) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [int\_of\_char](stdlib#VALint_of_char) [[Stdlib](stdlib)] | Return the ASCII code of the argument. |
| [int\_of\_float](stdlib#VALint_of_float) [[Stdlib](stdlib)] | Truncate the given floating-point number to an integer. |
| [int\_of\_string](stdlib#VALint_of_string) [[Stdlib](stdlib)] | Same as [`int_of_string_opt`](stdlib#VALint_of_string_opt), but raise `Failure "int\_of\_string"` instead of returning `None`. |
| [int\_of\_string\_opt](stdlib#VALint_of_string_opt) [[Stdlib](stdlib)] | Convert the given string to an integer. |
| [int\_size](sys#VALint_size) [[Sys](sys)] | Size of `int`, in bits. |
| [int\_tag](obj#VALint_tag) [[Obj](obj)] | |
| [inter](set.s#VALinter) [[Set.S](set.s)] | Set intersection. |
| [inter](morelabels.set.s#VALinter) [[MoreLabels.Set.S](morelabels.set.s)] | Set intersection. |
| [interactive](sys#VALinteractive) [[Sys](sys)] | This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`. |
| [interleave](seq#VALinterleave) [[Seq](seq)] | `interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on. |
| [ints](seq#VALints) [[Seq](seq)] | `ints i` is the infinite sequence of the integers beginning at `i` and counting up. |
| [inv](complex#VALinv) [[Complex](complex)] | Multiplicative inverse (`1/z`). |
| [invalid\_arg](stdlib#VALinvalid_arg) [[Stdlib](stdlib)] | Raise exception `Invalid\_argument` with the given string. |
| [is\_block](obj#VALis_block) [[Obj](obj)] | |
| [is\_buffered](out_channel#VALis_buffered) [[Out\_channel](out_channel)] | `is_buffered oc` returns whether the channel `oc` is buffered (see [`Out\_channel.set_buffered`](out_channel#VALset_buffered)). |
| [is\_char](uchar#VALis_char) [[Uchar](uchar)] | `is_char u` is `true` if and only if `u` is a latin1 OCaml character. |
| [is\_directory](sys#VALis_directory) [[Sys](sys)] | Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file. |
| [is\_empty](stack#VALis_empty) [[Stack](stack)] | Return `true` if the given stack is empty, `false` otherwise. |
| [is\_empty](set.s#VALis_empty) [[Set.S](set.s)] | Test whether a set is empty or not. |
| [is\_empty](seq#VALis_empty) [[Seq](seq)] | `is_empty xs` determines whether the sequence `xs` is empty. |
| [is\_empty](queue#VALis_empty) [[Queue](queue)] | Return `true` if the given queue is empty, `false` otherwise. |
| [is\_empty](morelabels.set.s#VALis_empty) [[MoreLabels.Set.S](morelabels.set.s)] | Test whether a set is empty or not. |
| [is\_empty](morelabels.map.s#VALis_empty) [[MoreLabels.Map.S](morelabels.map.s)] | Test whether a map is empty or not. |
| [is\_empty](map.s#VALis_empty) [[Map.S](map.s)] | Test whether a map is empty or not. |
| [is\_error](result#VALis_error) [[Result](result)] | `is_error r` is `true` if and only if `r` is `Error _`. |
| [is\_finite](float#VALis_finite) [[Float](float)] | `is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`Float.nan`](float#VALnan). |
| [is\_implicit](filename#VALis_implicit) [[Filename](filename)] | Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory. |
| [is\_in\_char\_set](camlinternalformat#VALis_in_char_set) [[CamlinternalFormat](camlinternalformat)] | |
| [is\_inet6\_addr](unixlabels#VALis_inet6_addr) [[UnixLabels](unixlabels)] | Whether the given `inet_addr` is an IPv6 address. |
| [is\_inet6\_addr](unix#VALis_inet6_addr) [[Unix](unix)] | Whether the given `inet_addr` is an IPv6 address. |
| [is\_infinite](float#VALis_infinite) [[Float](float)] | `is_infinite x` is `true` if and only if `x` is [`Float.infinity`](float#VALinfinity) or [`Float.neg_infinity`](float#VALneg_infinity). |
| [is\_inline](printexc.slot#VALis_inline) [[Printexc.Slot](printexc.slot)] | `is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context. |
| [is\_int](obj#VALis_int) [[Obj](obj)] | |
| [is\_integer](float#VALis_integer) [[Float](float)] | `is_integer x` is `true` if and only if `x` is an integer. |
| [is\_left](either#VALis_left) [[Either](either)] | `is_left (Left v)` is `true`, `is_left (Right v)` is `false`. |
| [is\_main\_domain](domain#VALis_main_domain) [[Domain](domain)] | `is_main_domain ()` returns true if called from the initial domain. |
| [is\_nan](float#VALis_nan) [[Float](float)] | `is_nan x` is `true` if and only if `x` is not a number (see [`Float.nan`](float#VALnan)). |
| [is\_native](dynlink#VALis_native) [[Dynlink](dynlink)] | `true` if the program is native, `false` if the program is bytecode. |
| [is\_none](option#VALis_none) [[Option](option)] | `is_none o` is `true` if and only if `o` is `None`. |
| [is\_ok](result#VALis_ok) [[Result](result)] | `is_ok r` is `true` if and only if `r` is `Ok _`. |
| [is\_raise](printexc.slot#VALis_raise) [[Printexc.Slot](printexc.slot)] | `is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call. |
| [is\_randomized](morelabels.hashtbl#VALis_randomized) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. |
| [is\_randomized](hashtbl#VALis_randomized) [[Hashtbl](hashtbl)] | Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. |
| [is\_relative](filename#VALis_relative) [[Filename](filename)] | Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. |
| [is\_right](either#VALis_right) [[Either](either)] | `is_right (Left v)` is `false`, `is_right (Right v)` is `true`. |
| [is\_shared](obj#VALis_shared) [[Obj](obj)] | |
| [is\_some](option#VALis_some) [[Option](option)] | `is_some o` is `true` if and only if `o` is `Some o`. |
| [is\_val](lazy#VALis_val) [[Lazy](lazy)] | `is_val x` returns `true` if `x` has already been forced and did not raise an exception. |
| [is\_valid](uchar#VALis_valid) [[Uchar](uchar)] | `is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. |
| [is\_valid\_utf\_16be](string#VALis_valid_utf_16be) [[String](string)] | `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. |
| [is\_valid\_utf\_16be](stringlabels#VALis_valid_utf_16be) [[StringLabels](stringlabels)] | `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. |
| [is\_valid\_utf\_16be](byteslabels#VALis_valid_utf_16be) [[BytesLabels](byteslabels)] | `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. |
| [is\_valid\_utf\_16be](bytes#VALis_valid_utf_16be) [[Bytes](bytes)] | `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. |
| [is\_valid\_utf\_16le](string#VALis_valid_utf_16le) [[String](string)] | `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. |
| [is\_valid\_utf\_16le](stringlabels#VALis_valid_utf_16le) [[StringLabels](stringlabels)] | `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. |
| [is\_valid\_utf\_16le](byteslabels#VALis_valid_utf_16le) [[BytesLabels](byteslabels)] | `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. |
| [is\_valid\_utf\_16le](bytes#VALis_valid_utf_16le) [[Bytes](bytes)] | `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. |
| [is\_valid\_utf\_8](string#VALis_valid_utf_8) [[String](string)] | `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. |
| [is\_valid\_utf\_8](stringlabels#VALis_valid_utf_8) [[StringLabels](stringlabels)] | `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. |
| [is\_valid\_utf\_8](byteslabels#VALis_valid_utf_8) [[BytesLabels](byteslabels)] | `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. |
| [is\_valid\_utf\_8](bytes#VALis_valid_utf_8) [[Bytes](bytes)] | `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. |
| [isatty](unixlabels#VALisatty) [[UnixLabels](unixlabels)] | Return `true` if the given file descriptor refers to a terminal or console window, `false` otherwise. |
| [isatty](unix#VALisatty) [[Unix](unix)] | Return `true` if the given file descriptor refers to a terminal or console window, `false` otherwise. |
| [iter](weak.s#VALiter) [[Weak.S](weak.s)] | `iter f t` calls `f` on each element of `t`, in some unspecified order. |
| [iter](string#VALiter) [[String](string)] | `iter f s` applies function `f` in turn to all the characters of `s`. |
| [iter](stringlabels#VALiter) [[StringLabels](stringlabels)] | `iter ~f s` applies function `f` in turn to all the characters of `s`. |
| [iter](stack#VALiter) [[Stack](stack)] | `iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. |
| [iter](set.s#VALiter) [[Set.S](set.s)] | `iter f s` applies `f` in turn to all elements of `s`. |
| [iter](seq#VALiter) [[Seq](seq)] | `iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right. |
| [iter](result#VALiter) [[Result](result)] | `iter f r` is `f v` if `r` is `Ok v` and `()` otherwise. |
| [iter](queue#VALiter) [[Queue](queue)] | `iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. |
| [iter](option#VALiter) [[Option](option)] | `iter f o` is `f v` if `o` is `Some v` and `()` otherwise. |
| [iter](morelabels.set.s#VALiter) [[MoreLabels.Set.S](morelabels.set.s)] | `iter ~f s` applies `f` in turn to all elements of `s`. |
| [iter](morelabels.map.s#VALiter) [[MoreLabels.Map.S](morelabels.map.s)] | `iter ~f m` applies `f` to all bindings in map `m`. |
| [iter](morelabels.hashtbl.seededs#VALiter) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [iter](morelabels.hashtbl.s#VALiter) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [iter](morelabels.hashtbl#VALiter) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. |
| [iter](map.s#VALiter) [[Map.S](map.s)] | `iter f m` applies `f` to all bindings in map `m`. |
| [iter](listlabels#VALiter) [[ListLabels](listlabels)] | `iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. |
| [iter](list#VALiter) [[List](list)] | `iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. |
| [iter](hashtbl.seededs#VALiter) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [iter](hashtbl.s#VALiter) [[Hashtbl.S](hashtbl.s)] | |
| [iter](hashtbl#VALiter) [[Hashtbl](hashtbl)] | `Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. |
| [iter](float.arraylabels#VALiter) [[Float.ArrayLabels](float.arraylabels)] | `iter ~f a` applies function `f` in turn to all the elements of `a`. |
| [iter](float.array#VALiter) [[Float.Array](float.array)] | `iter f a` applies function `f` in turn to all the elements of `a`. |
| [iter](either#VALiter) [[Either](either)] | `iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`. |
| [iter](byteslabels#VALiter) [[BytesLabels](byteslabels)] | `iter ~f s` applies function `f` in turn to all the bytes of `s`. |
| [iter](bytes#VALiter) [[Bytes](bytes)] | `iter f s` applies function `f` in turn to all the bytes of `s`. |
| [iter](arraylabels#VALiter) [[ArrayLabels](arraylabels)] | `iter ~f a` applies function `f` in turn to all the elements of `a`. |
| [iter](array#VALiter) [[Array](array)] | `iter f a` applies function `f` in turn to all the elements of `a`. |
| [iter2](seq#VALiter2) [[Seq](seq)] | `iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. |
| [iter2](listlabels#VALiter2) [[ListLabels](listlabels)] | `iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. |
| [iter2](list#VALiter2) [[List](list)] | `iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. |
| [iter2](float.arraylabels#VALiter2) [[Float.ArrayLabels](float.arraylabels)] | `Array.iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. |
| [iter2](float.array#VALiter2) [[Float.Array](float.array)] | `Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`. |
| [iter2](arraylabels#VALiter2) [[ArrayLabels](arraylabels)] | `iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. |
| [iter2](array#VALiter2) [[Array](array)] | `iter2 f a b` applies function `f` to all the elements of `a` and `b`. |
| [iter\_error](result#VALiter_error) [[Result](result)] | `iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise. |
| [iterate](seq#VALiterate) [[Seq](seq)] | `iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on. |
| [iteri](string#VALiteri) [[String](string)] | `iteri` is like [`String.iter`](string#VALiter), but the function is also given the corresponding character index. |
| [iteri](stringlabels#VALiteri) [[StringLabels](stringlabels)] | `iteri` is like [`StringLabels.iter`](stringlabels#VALiter), but the function is also given the corresponding character index. |
| [iteri](seq#VALiteri) [[Seq](seq)] | `iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`. |
| [iteri](listlabels#VALiteri) [[ListLabels](listlabels)] | Same as [`ListLabels.iter`](listlabels#VALiter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. |
| [iteri](list#VALiteri) [[List](list)] | Same as [`List.iter`](list#VALiter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. |
| [iteri](float.arraylabels#VALiteri) [[Float.ArrayLabels](float.arraylabels)] | Same as [`Float.ArrayLabels.iter`](float.arraylabels#VALiter), but the function is applied with the index of the element as first argument, and the element itself as second argument. |
| [iteri](float.array#VALiteri) [[Float.Array](float.array)] | Same as [`Float.Array.iter`](float.array#VALiter), but the function is applied with the index of the element as first argument, and the element itself as second argument. |
| [iteri](byteslabels#VALiteri) [[BytesLabels](byteslabels)] | Same as [`BytesLabels.iter`](byteslabels#VALiter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. |
| [iteri](bytes#VALiteri) [[Bytes](bytes)] | Same as [`Bytes.iter`](bytes#VALiter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. |
| [iteri](arraylabels#VALiteri) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.iter`](arraylabels#VALiter), but the function is applied to the index of the element as first argument, and the element itself as second argument. |
| [iteri](array#VALiteri) [[Array](array)] | Same as [`Array.iter`](array#VALiter), but the function is applied to the index of the element as first argument, and the element itself as second argument. |
| J |
| [join](thread#VALjoin) [[Thread](thread)] | `join th` suspends the execution of the calling thread until the thread `th` has terminated. |
| [join](result#VALjoin) [[Result](result)] | `join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`. |
| [join](option#VALjoin) [[Option](option)] | `join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise. |
| [join](domain#VALjoin) [[Domain](domain)] | `join d` blocks until domain `d` runs to completion. |
| K |
| [kasprintf](format#VALkasprintf) [[Format](format)] | Same as `asprintf` above, but instead of returning the string, passes it to the first argument. |
| [kbprintf](printf#VALkbprintf) [[Printf](printf)] | Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing. |
| [kdprintf](format#VALkdprintf) [[Format](format)] | Same as [`Format.dprintf`](format#VALdprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing. |
| [kfprintf](printf#VALkfprintf) [[Printf](printf)] | Same as `fprintf`, but instead of returning immediately, passes the out channel to its first argument at the end of printing. |
| [kfprintf](format#VALkfprintf) [[Format](format)] | Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing. |
| [kill](unixlabels#VALkill) [[UnixLabels](unixlabels)] | `kill ~pid ~signal` sends signal number `signal` to the process with id `pid`. |
| [kill](unix#VALkill) [[Unix](unix)] | `kill pid signal` sends signal number `signal` to the process with id `pid`. |
| [kind](bigarray.array3#VALkind) [[Bigarray.Array3](bigarray.array3)] | Return the kind of the given Bigarray. |
| [kind](bigarray.array2#VALkind) [[Bigarray.Array2](bigarray.array2)] | Return the kind of the given Bigarray. |
| [kind](bigarray.array1#VALkind) [[Bigarray.Array1](bigarray.array1)] | Return the kind of the given Bigarray. |
| [kind](bigarray.array0#VALkind) [[Bigarray.Array0](bigarray.array0)] | Return the kind of the given Bigarray. |
| [kind](bigarray.genarray#VALkind) [[Bigarray.Genarray](bigarray.genarray)] | Return the kind of the given Bigarray. |
| [kind\_size\_in\_bytes](bigarray#VALkind_size_in_bytes) [[Bigarray](bigarray)] | `kind_size_in_bytes k` is the number of bytes used to store an element of type `k`. |
| [kprintf](printf#VALkprintf) [[Printf](printf)] | A deprecated synonym for `ksprintf`.
|
| [kscanf](scanf#VALkscanf) [[Scanf](scanf)] | Same as [`Scanf.bscanf`](scanf#VALbscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments. |
| [ksprintf](printf#VALksprintf) [[Printf](printf)] | Same as `sprintf` above, but instead of returning the string, passes it to the first argument. |
| [ksprintf](format#VALksprintf) [[Format](format)] | Same as `sprintf` above, but instead of returning the string, passes it to the first argument. |
| [ksscanf](scanf#VALksscanf) [[Scanf](scanf)] | Same as [`Scanf.kscanf`](scanf#VALkscanf) but reads from the given string. |
| L |
| [last\_chars](str#VALlast_chars) [[Str](str)] | `last_chars s n` returns the last `n` characters of `s`. |
| [last\_non\_constant\_constructor\_tag](obj#VALlast_non_constant_constructor_tag) [[Obj](obj)] | |
| [layout](bigarray.array3#VALlayout) [[Bigarray.Array3](bigarray.array3)] | Return the layout of the given Bigarray. |
| [layout](bigarray.array2#VALlayout) [[Bigarray.Array2](bigarray.array2)] | Return the layout of the given Bigarray. |
| [layout](bigarray.array1#VALlayout) [[Bigarray.Array1](bigarray.array1)] | Return the layout of the given Bigarray. |
| [layout](bigarray.array0#VALlayout) [[Bigarray.Array0](bigarray.array0)] | Return the layout of the given Bigarray. |
| [layout](bigarray.genarray#VALlayout) [[Bigarray.Genarray](bigarray.genarray)] | Return the layout of the given Bigarray. |
| [lazy\_tag](obj#VALlazy_tag) [[Obj](obj)] | |
| [ldexp](float#VALldexp) [[Float](float)] | `ldexp x n` returns `x *. 2 ** n`. |
| [ldexp](stdlib#VALldexp) [[Stdlib](stdlib)] | `ldexp x n` returns `x *. 2 ** n`. |
| [left](either#VALleft) [[Either](either)] | `left v` is `Left v`. |
| [length](weak#VALlength) [[Weak](weak)] | `Weak.length ar` returns the length (number of elements) of `ar`. |
| [length](string#VALlength) [[String](string)] | `length s` is the length (number of bytes/characters) of `s`. |
| [length](stringlabels#VALlength) [[StringLabels](stringlabels)] | `length s` is the length (number of bytes/characters) of `s`. |
| [length](stack#VALlength) [[Stack](stack)] | Return the number of elements in a stack. |
| [length](seq#VALlength) [[Seq](seq)] | `length xs` is the length of the sequence `xs`. |
| [length](queue#VALlength) [[Queue](queue)] | Return the number of elements in a queue. |
| [length](out_channel#VALlength) [[Out\_channel](out_channel)] | Return the size (number of characters) of the regular file on which the given channel is opened. |
| [length](obj.ephemeron#VALlength) [[Obj.Ephemeron](obj.ephemeron)] | return the number of keys |
| [length](morelabels.hashtbl.seededs#VALlength) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [length](morelabels.hashtbl.s#VALlength) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [length](morelabels.hashtbl#VALlength) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.length tbl` returns the number of bindings in `tbl`. |
| [length](listlabels#VALlength) [[ListLabels](listlabels)] | Return the length (number of elements) of the given list. |
| [length](list#VALlength) [[List](list)] | Return the length (number of elements) of the given list. |
| [length](in_channel#VALlength) [[In\_channel](in_channel)] | Return the size (number of characters) of the regular file on which the given channel is opened. |
| [length](hashtbl.seededs#VALlength) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [length](hashtbl.s#VALlength) [[Hashtbl.S](hashtbl.s)] | |
| [length](hashtbl#VALlength) [[Hashtbl](hashtbl)] | `Hashtbl.length tbl` returns the number of bindings in `tbl`. |
| [length](float.arraylabels#VALlength) [[Float.ArrayLabels](float.arraylabels)] | Return the length (number of elements) of the given floatarray. |
| [length](float.array#VALlength) [[Float.Array](float.array)] | Return the length (number of elements) of the given floatarray. |
| [length](ephemeron.kn.bucket#VALlength) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | Returns an upper bound on the length of the bucket. |
| [length](ephemeron.k2.bucket#VALlength) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | Returns an upper bound on the length of the bucket. |
| [length](ephemeron.k1.bucket#VALlength) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | Returns an upper bound on the length of the bucket. |
| [length](ephemeron.seededs#VALlength) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [length](ephemeron.s#VALlength) [[Ephemeron.S](ephemeron.s)] | |
| [length](byteslabels#VALlength) [[BytesLabels](byteslabels)] | Return the length (number of bytes) of the argument. |
| [length](bytes#VALlength) [[Bytes](bytes)] | Return the length (number of bytes) of the argument. |
| [length](buffer#VALlength) [[Buffer](buffer)] | Return the number of characters currently contained in the buffer. |
| [length](arraylabels#VALlength) [[ArrayLabels](arraylabels)] | Return the length (number of elements) of the given array. |
| [length](array#VALlength) [[Array](array)] | Return the length (number of elements) of the given array. |
| [lexeme](lexing#VALlexeme) [[Lexing](lexing)] | `Lexing.lexeme lexbuf` returns the string matched by the regular expression. |
| [lexeme\_char](lexing#VALlexeme_char) [[Lexing](lexing)] | `Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string. |
| [lexeme\_end](lexing#VALlexeme_end) [[Lexing](lexing)] | `Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. |
| [lexeme\_end\_p](lexing#VALlexeme_end_p) [[Lexing](lexing)] | Like `lexeme_end`, but return a complete `position` instead of an offset. |
| [lexeme\_start](lexing#VALlexeme_start) [[Lexing](lexing)] | `Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. |
| [lexeme\_start\_p](lexing#VALlexeme_start_p) [[Lexing](lexing)] | Like `lexeme_start`, but return a complete `position` instead of an offset. |
| [lifecycle\_name](runtime_events#VALlifecycle_name) [[Runtime\_events](runtime_events)] | Return a string representation of a given lifecycle event type |
| [link](unixlabels#VALlink) [[UnixLabels](unixlabels)] | `link ?follow ~src ~dst` creates a hard link named `dst` to the file named `src`. |
| [link](unix#VALlink) [[Unix](unix)] | `link ?follow src dst` creates a hard link named `dst` to the file named `src`. |
| [listen](unixlabels#VALlisten) [[UnixLabels](unixlabels)] | Set up a socket for receiving connection requests. |
| [listen](unix#VALlisten) [[Unix](unix)] | Set up a socket for receiving connection requests. |
| [lnot](stdlib#VALlnot) [[Stdlib](stdlib)] | Bitwise logical negation. |
| [loadfile](dynlink#VALloadfile) [[Dynlink](dynlink)] | In bytecode: load the given bytecode object file (`.cmo` file) or bytecode library file (`.cma` file), and link it with the running program. |
| [loadfile\_private](dynlink#VALloadfile_private) [[Dynlink](dynlink)] | Same as `loadfile`, except that the compilation units just loaded are hidden (cannot be referenced) from other modules dynamically loaded afterwards. |
| [localtime](unixlabels#VALlocaltime) [[UnixLabels](unixlabels)] | Convert a time in seconds, as returned by [`UnixLabels.time`](unixlabels#VALtime), into a date and a time. |
| [localtime](unix#VALlocaltime) [[Unix](unix)] | Convert a time in seconds, as returned by [`Unix.time`](unix#VALtime), into a date and a time. |
| [location](printexc.slot#VALlocation) [[Printexc.Slot](printexc.slot)] | `location slot` returns the location information of the slot, if available, and `None` otherwise. |
| [lock](mutex#VALlock) [[Mutex](mutex)] | Lock the given mutex. |
| [lockf](unixlabels#VALlockf) [[UnixLabels](unixlabels)] | `lockf fd ~mode ~len` puts a lock on a region of the file opened as `fd`. |
| [lockf](unix#VALlockf) [[Unix](unix)] | `lockf fd mode len` puts a lock on a region of the file opened as `fd`. |
| [log](float#VALlog) [[Float](float)] | Natural logarithm. |
| [log](complex#VALlog) [[Complex](complex)] | Natural logarithm (in base `e`). |
| [log](stdlib#VALlog) [[Stdlib](stdlib)] | Natural logarithm. |
| [log10](float#VALlog10) [[Float](float)] | Base 10 logarithm. |
| [log10](stdlib#VALlog10) [[Stdlib](stdlib)] | Base 10 logarithm. |
| [log1p](float#VALlog1p) [[Float](float)] | `log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. |
| [log1p](stdlib#VALlog1p) [[Stdlib](stdlib)] | `log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. |
| [log2](float#VALlog2) [[Float](float)] | Base 2 logarithm. |
| [logand](nativeint#VALlogand) [[Nativeint](nativeint)] | Bitwise logical and. |
| [logand](int64#VALlogand) [[Int64](int64)] | Bitwise logical and. |
| [logand](int32#VALlogand) [[Int32](int32)] | Bitwise logical and. |
| [logand](int#VALlogand) [[Int](int)] | `logand x y` is the bitwise logical and of `x` and `y`. |
| [lognot](nativeint#VALlognot) [[Nativeint](nativeint)] | Bitwise logical negation. |
| [lognot](int64#VALlognot) [[Int64](int64)] | Bitwise logical negation. |
| [lognot](int32#VALlognot) [[Int32](int32)] | Bitwise logical negation. |
| [lognot](int#VALlognot) [[Int](int)] | `lognot x` is the bitwise logical negation of `x`. |
| [logor](nativeint#VALlogor) [[Nativeint](nativeint)] | Bitwise logical or. |
| [logor](int64#VALlogor) [[Int64](int64)] | Bitwise logical or. |
| [logor](int32#VALlogor) [[Int32](int32)] | Bitwise logical or. |
| [logor](int#VALlogor) [[Int](int)] | `logor x y` is the bitwise logical or of `x` and `y`. |
| [logxor](nativeint#VALlogxor) [[Nativeint](nativeint)] | Bitwise logical exclusive or. |
| [logxor](int64#VALlogxor) [[Int64](int64)] | Bitwise logical exclusive or. |
| [logxor](int32#VALlogxor) [[Int32](int32)] | Bitwise logical exclusive or. |
| [logxor](int#VALlogxor) [[Int](int)] | `logxor x y` is the bitwise logical exclusive or of `x` and `y`. |
| [lookup\_tables](camlinternaloo#VALlookup_tables) [[CamlinternalOO](camlinternaloo)] | |
| [lowercase\_ascii](string#VALlowercase_ascii) [[String](string)] | `lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. |
| [lowercase\_ascii](stringlabels#VALlowercase_ascii) [[StringLabels](stringlabels)] | `lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. |
| [lowercase\_ascii](char#VALlowercase_ascii) [[Char](char)] | Convert the given character to its equivalent lowercase character, using the US-ASCII character set. |
| [lowercase\_ascii](byteslabels#VALlowercase_ascii) [[BytesLabels](byteslabels)] | Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. |
| [lowercase\_ascii](bytes#VALlowercase_ascii) [[Bytes](bytes)] | Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. |
| [lseek](unixlabels.largefile#VALlseek) [[UnixLabels.LargeFile](unixlabels.largefile)] | See `lseek`. |
| [lseek](unixlabels#VALlseek) [[UnixLabels](unixlabels)] | Set the current position for a file descriptor, and return the resulting offset (from the beginning of the file). |
| [lseek](unix.largefile#VALlseek) [[Unix.LargeFile](unix.largefile)] | See `lseek`. |
| [lseek](unix#VALlseek) [[Unix](unix)] | Set the current position for a file descriptor, and return the resulting offset (from the beginning of the file). |
| [lstat](unixlabels.largefile#VALlstat) [[UnixLabels.LargeFile](unixlabels.largefile)] | |
| [lstat](unixlabels#VALlstat) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.stat`](unixlabels#VALstat), but in case the file is a symbolic link, return the information for the link itself. |
| [lstat](unix.largefile#VALlstat) [[Unix.LargeFile](unix.largefile)] | |
| [lstat](unix#VALlstat) [[Unix](unix)] | Same as [`Unix.stat`](unix#VALstat), but in case the file is a symbolic link, return the information for the link itself. |
| M |
| [magic](obj#VALmagic) [[Obj](obj)] | |
| [main\_program\_units](dynlink#VALmain_program_units) [[Dynlink](dynlink)] | Return the list of compilation units that form the main program (i.e. |
| [major](gc#VALmajor) [[Gc](gc)] | Do a minor collection and finish the current major collection cycle. |
| [major\_slice](gc#VALmajor_slice) [[Gc](gc)] | `major_slice n` Do a minor collection and a slice of major collection. |
| [make](string#VALmake) [[String](string)] | `make n c` is a string of length `n` with each index holding the character `c`. |
| [make](stringlabels#VALmake) [[StringLabels](stringlabels)] | `make n c` is a string of length `n` with each index holding the character `c`. |
| [make](semaphore.binary#VALmake) [[Semaphore.Binary](semaphore.binary)] | `make b` returns a new binary semaphore. |
| [make](semaphore.counting#VALmake) [[Semaphore.Counting](semaphore.counting)] | `make n` returns a new counting semaphore, with initial value `n`. |
| [make](random.state#VALmake) [[Random.State](random.state)] | Create a new state and initialize it with the given seed. |
| [make](float.arraylabels#VALmake) [[Float.ArrayLabels](float.arraylabels)] | `make n x` returns a fresh floatarray of length `n`, initialized with `x`. |
| [make](float.array#VALmake) [[Float.Array](float.array)] | `make n x` returns a fresh floatarray of length `n`, initialized with `x`. |
| [make](ephemeron.kn.bucket#VALmake) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | Create a new bucket. |
| [make](ephemeron.kn#VALmake) [[Ephemeron.Kn](ephemeron.kn)] | Same as [`Ephemeron.K1.make`](ephemeron.k1#VALmake) |
| [make](ephemeron.k2.bucket#VALmake) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | Create a new bucket. |
| [make](ephemeron.k2#VALmake) [[Ephemeron.K2](ephemeron.k2)] | Same as [`Ephemeron.K1.make`](ephemeron.k1#VALmake) |
| [make](ephemeron.k1.bucket#VALmake) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | Create a new bucket. |
| [make](ephemeron.k1#VALmake) [[Ephemeron.K1](ephemeron.k1)] | `Ephemeron.K1.make k d` creates an ephemeron with key `k` and data `d`. |
| [make](byteslabels#VALmake) [[BytesLabels](byteslabels)] | `make n c` returns a new byte sequence of length `n`, filled with the byte `c`. |
| [make](bytes#VALmake) [[Bytes](bytes)] | `make n c` returns a new byte sequence of length `n`, filled with the byte `c`. |
| [make](atomic#VALmake) [[Atomic](atomic)] | Create an atomic reference. |
| [make](arraylabels#VALmake) [[ArrayLabels](arraylabels)] | `make n x` returns a fresh array of length `n`, initialized with `x`. |
| [make](array#VALmake) [[Array](array)] | `make n x` returns a fresh array of length `n`, initialized with `x`. |
| [make\_class](camlinternaloo#VALmake_class) [[CamlinternalOO](camlinternaloo)] | |
| [make\_class\_store](camlinternaloo#VALmake_class_store) [[CamlinternalOO](camlinternaloo)] | |
| [make\_formatter](format#VALmake_formatter) [[Format](format)] | `make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`. |
| [make\_iprintf](camlinternalformat#VALmake_iprintf) [[CamlinternalFormat](camlinternalformat)] | |
| [make\_matrix](arraylabels#VALmake_matrix) [[ArrayLabels](arraylabels)] | `make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. |
| [make\_matrix](array#VALmake_matrix) [[Array](array)] | `make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. |
| [make\_printf](camlinternalformat#VALmake_printf) [[CamlinternalFormat](camlinternalformat)] | |
| [make\_self\_init](random.state#VALmake_self_init) [[Random.State](random.state)] | Create a new state and initialize it with a random seed chosen in a system-dependent way. |
| [make\_symbolic\_output\_buffer](format#VALmake_symbolic_output_buffer) [[Format](format)] | `make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output. |
| [make\_synchronized\_formatter](format#VALmake_synchronized_formatter) [[Format](format)] | `make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`. |
| [map](string#VALmap) [[String](string)] | `map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. |
| [map](stringlabels#VALmap) [[StringLabels](stringlabels)] | `map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. |
| [map](set.s#VALmap) [[Set.S](set.s)] | `map f s` is the set whose elements are `f a0`,`f a1`... |
| [map](seq#VALmap) [[Seq](seq)] | `map f xs` is the image of the sequence `xs` through the transformation `f`. |
| [map](result#VALmap) [[Result](result)] | `map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`. |
| [map](option#VALmap) [[Option](option)] | `map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`. |
| [map](morelabels.set.s#VALmap) [[MoreLabels.Set.S](morelabels.set.s)] | `map ~f s` is the set whose elements are `f a0`,`f a1`... |
| [map](morelabels.map.s#VALmap) [[MoreLabels.Map.S](morelabels.map.s)] | `map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. |
| [map](map.s#VALmap) [[Map.S](map.s)] | `map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. |
| [map](listlabels#VALmap) [[ListLabels](listlabels)] | `map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. |
| [map](list#VALmap) [[List](list)] | `map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. |
| [map](lazy#VALmap) [[Lazy](lazy)] | `map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value. |
| [map](float.arraylabels#VALmap) [[Float.ArrayLabels](float.arraylabels)] | `map ~f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. |
| [map](float.array#VALmap) [[Float.Array](float.array)] | `map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. |
| [map](either#VALmap) [[Either](either)] | `map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`. |
| [map](byteslabels#VALmap) [[BytesLabels](byteslabels)] | `map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. |
| [map](bytes#VALmap) [[Bytes](bytes)] | `map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. |
| [map](arraylabels#VALmap) [[ArrayLabels](arraylabels)] | `map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. |
| [map](array#VALmap) [[Array](array)] | `map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. |
| [map2](seq#VALmap2) [[Seq](seq)] | `map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`. |
| [map2](listlabels#VALmap2) [[ListLabels](listlabels)] | `map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. |
| [map2](list#VALmap2) [[List](list)] | `map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. |
| [map2](float.arraylabels#VALmap2) [[Float.ArrayLabels](float.arraylabels)] | `map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. |
| [map2](float.array#VALmap2) [[Float.Array](float.array)] | `map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. |
| [map2](arraylabels#VALmap2) [[ArrayLabels](arraylabels)] | `map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. |
| [map2](array#VALmap2) [[Array](array)] | `map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. |
| [map\_error](result#VALmap_error) [[Result](result)] | `map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`. |
| [map\_file](unixlabels#VALmap_file) [[UnixLabels](unixlabels)] | Memory mapping of a file as a Bigarray. |
| [map\_file](unix#VALmap_file) [[Unix](unix)] | Memory mapping of a file as a Bigarray. |
| [map\_from\_array](float.arraylabels#VALmap_from_array) [[Float.ArrayLabels](float.arraylabels)] | `map_from_array ~f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. |
| [map\_from\_array](float.array#VALmap_from_array) [[Float.Array](float.array)] | `map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. |
| [map\_left](either#VALmap_left) [[Either](either)] | `map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`. |
| [map\_product](seq#VALmap_product) [[Seq](seq)] | The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`. |
| [map\_right](either#VALmap_right) [[Either](either)] | `map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`. |
| [map\_to\_array](float.arraylabels#VALmap_to_array) [[Float.ArrayLabels](float.arraylabels)] | `map_to_array ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. |
| [map\_to\_array](float.array#VALmap_to_array) [[Float.Array](float.array)] | `map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. |
| [map\_val](lazy#VALmap_val) [[Lazy](lazy)] | `map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`. |
| [mapi](string#VALmapi) [[String](string)] | `mapi f s` is like [`String.map`](string#VALmap) but the index of the character is also passed to `f`. |
| [mapi](stringlabels#VALmapi) [[StringLabels](stringlabels)] | `mapi ~f s` is like [`StringLabels.map`](stringlabels#VALmap) but the index of the character is also passed to `f`. |
| [mapi](seq#VALmapi) [[Seq](seq)] | `mapi` is analogous to `map`, but applies the function `f` to an index and an element. |
| [mapi](morelabels.map.s#VALmapi) [[MoreLabels.Map.S](morelabels.map.s)] | Same as [`MoreLabels.Map.S.map`](morelabels.map.s#VALmap), but the function receives as arguments both the key and the associated value for each binding of the map. |
| [mapi](map.s#VALmapi) [[Map.S](map.s)] | Same as [`Map.S.map`](map.s#VALmap), but the function receives as arguments both the key and the associated value for each binding of the map. |
| [mapi](listlabels#VALmapi) [[ListLabels](listlabels)] | Same as [`ListLabels.map`](listlabels#VALmap), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. |
| [mapi](list#VALmapi) [[List](list)] | Same as [`List.map`](list#VALmap), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. |
| [mapi](float.arraylabels#VALmapi) [[Float.ArrayLabels](float.arraylabels)] | Same as [`Float.ArrayLabels.map`](float.arraylabels#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument. |
| [mapi](float.array#VALmapi) [[Float.Array](float.array)] | Same as [`Float.Array.map`](float.array#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument. |
| [mapi](byteslabels#VALmapi) [[BytesLabels](byteslabels)] | `mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. |
| [mapi](bytes#VALmapi) [[Bytes](bytes)] | `mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. |
| [mapi](arraylabels#VALmapi) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.map`](arraylabels#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument. |
| [mapi](array#VALmapi) [[Array](array)] | Same as [`Array.map`](array#VALmap), but the function is applied to the index of the element as first argument, and the element itself as second argument. |
| [match\_beginning](str#VALmatch_beginning) [[Str](str)] | `match_beginning()` returns the position of the first character of the substring that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). |
| [match\_end](str#VALmatch_end) [[Str](str)] | `match_end()` returns the position of the character following the last character of the substring that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). |
| [match\_with](effect.deep#VALmatch_with) [[Effect.Deep](effect.deep)] | `match_with f v h` runs the computation `f v` in the handler `h`. |
| [matched\_group](str#VALmatched_group) [[Str](str)] | `matched_group n s` returns the substring of `s` that was matched by the `n`th group `\(...\)` of the regular expression that was matched by the last call to a matching or searching function (see [`Str.matched_string`](str#VALmatched_string) for details). |
| [matched\_string](str#VALmatched_string) [[Str](str)] | `matched_string s` returns the substring of `s` that was matched by the last call to one of the following matching or searching functions: [`Str.string_match`](str#VALstring_match), [`Str.search_forward`](str#VALsearch_forward), [`Str.search_backward`](str#VALsearch_backward), [`Str.string_partial_match`](str#VALstring_partial_match), [`Str.global_substitute`](str#VALglobal_substitute), [`Str.substitute_first`](str#VALsubstitute_first) provided that none of the following functions was called in between: [`Str.global_replace`](str#VALglobal_replace), [`Str.replace_first`](str#VALreplace_first), [`Str.split`](str#VALsplit), [`Str.bounded_split`](str#VALbounded_split), [`Str.split_delim`](str#VALsplit_delim), [`Str.bounded_split_delim`](str#VALbounded_split_delim), [`Str.full_split`](str#VALfull_split), [`Str.bounded_full_split`](str#VALbounded_full_split) Note: in the case of `global_substitute` and `substitute_first`, a call to `matched_string` is only valid within the `subst` argument, not after `global_substitute` or `substitute_first` returns. |
| [max](uchar#VALmax) [[Uchar](uchar)] | `max` is U+10FFFF. |
| [max](nativeint#VALmax) [[Nativeint](nativeint)] | Return the greater of the two arguments. |
| [max](int64#VALmax) [[Int64](int64)] | Return the greater of the two arguments. |
| [max](int32#VALmax) [[Int32](int32)] | Return the greater of the two arguments. |
| [max](int#VALmax) [[Int](int)] | Return the greater of the two arguments. |
| [max](float#VALmax) [[Float](float)] | `max x y` returns the maximum of `x` and `y`. |
| [max](stdlib#VALmax) [[Stdlib](stdlib)] | Return the greater of the two arguments. |
| [max\_array\_length](sys#VALmax_array_length) [[Sys](sys)] | Maximum length of a normal array (i.e. |
| [max\_binding](morelabels.map.s#VALmax_binding) [[MoreLabels.Map.S](morelabels.map.s)] | Same as [`MoreLabels.Map.S.min_binding`](morelabels.map.s#VALmin_binding), but returns the binding with the largest key in the given map. |
| [max\_binding](map.s#VALmax_binding) [[Map.S](map.s)] | Same as [`Map.S.min_binding`](map.s#VALmin_binding), but returns the binding with the largest key in the given map. |
| [max\_binding\_opt](morelabels.map.s#VALmax_binding_opt) [[MoreLabels.Map.S](morelabels.map.s)] | Same as [`MoreLabels.Map.S.min_binding_opt`](morelabels.map.s#VALmin_binding_opt), but returns the binding with the largest key in the given map. |
| [max\_binding\_opt](map.s#VALmax_binding_opt) [[Map.S](map.s)] | Same as [`Map.S.min_binding_opt`](map.s#VALmin_binding_opt), but returns the binding with the largest key in the given map. |
| [max\_elt](set.s#VALmax_elt) [[Set.S](set.s)] | Same as [`Set.S.min_elt`](set.s#VALmin_elt), but returns the largest element of the given set. |
| [max\_elt](morelabels.set.s#VALmax_elt) [[MoreLabels.Set.S](morelabels.set.s)] | Same as [`MoreLabels.Set.S.min_elt`](morelabels.set.s#VALmin_elt), but returns the largest element of the given set. |
| [max\_elt\_opt](set.s#VALmax_elt_opt) [[Set.S](set.s)] | Same as [`Set.S.min_elt_opt`](set.s#VALmin_elt_opt), but returns the largest element of the given set. |
| [max\_elt\_opt](morelabels.set.s#VALmax_elt_opt) [[MoreLabels.Set.S](morelabels.set.s)] | Same as [`MoreLabels.Set.S.min_elt_opt`](morelabels.set.s#VALmin_elt_opt), but returns the largest element of the given set. |
| [max\_ephe\_length](obj.ephemeron#VALmax_ephe_length) [[Obj.Ephemeron](obj.ephemeron)] | Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain |
| [max\_float](float#VALmax_float) [[Float](float)] | The largest positive finite value of type `float`. |
| [max\_float](stdlib#VALmax_float) [[Stdlib](stdlib)] | The largest positive finite value of type `float`. |
| [max\_floatarray\_length](sys#VALmax_floatarray_length) [[Sys](sys)] | Maximum length of a floatarray. |
| [max\_int](nativeint#VALmax_int) [[Nativeint](nativeint)] | The greatest representable native integer, either 231 - 1 on a 32-bit platform, or 263 - 1 on a 64-bit platform. |
| [max\_int](int64#VALmax_int) [[Int64](int64)] | The greatest representable 64-bit integer, 263 - 1. |
| [max\_int](int32#VALmax_int) [[Int32](int32)] | The greatest representable 32-bit integer, 231 - 1. |
| [max\_int](int#VALmax_int) [[Int](int)] | `max_int` is the greatest representable integer, `2{^[Sys.int_size - 1]} - 1`. |
| [max\_int](stdlib#VALmax_int) [[Stdlib](stdlib)] | The greatest representable integer. |
| [max\_num](float#VALmax_num) [[Float](float)] | `max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. |
| [max\_string\_length](sys#VALmax_string_length) [[Sys](sys)] | Maximum length of strings and byte sequences. |
| [mem](weak.s#VALmem) [[Weak.S](weak.s)] | `mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. |
| [mem](set.s#VALmem) [[Set.S](set.s)] | `mem x s` tests whether `x` belongs to the set `s`. |
| [mem](morelabels.set.s#VALmem) [[MoreLabels.Set.S](morelabels.set.s)] | `mem x s` tests whether `x` belongs to the set `s`. |
| [mem](morelabels.map.s#VALmem) [[MoreLabels.Map.S](morelabels.map.s)] | `mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. |
| [mem](morelabels.hashtbl.seededs#VALmem) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [mem](morelabels.hashtbl.s#VALmem) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [mem](morelabels.hashtbl#VALmem) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. |
| [mem](map.s#VALmem) [[Map.S](map.s)] | `mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. |
| [mem](listlabels#VALmem) [[ListLabels](listlabels)] | `mem a ~set` is true if and only if `a` is equal to an element of `set`. |
| [mem](list#VALmem) [[List](list)] | `mem a set` is true if and only if `a` is equal to an element of `set`. |
| [mem](hashtbl.seededs#VALmem) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [mem](hashtbl.s#VALmem) [[Hashtbl.S](hashtbl.s)] | |
| [mem](hashtbl#VALmem) [[Hashtbl](hashtbl)] | `Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. |
| [mem](float.arraylabels#VALmem) [[Float.ArrayLabels](float.arraylabels)] | `mem a ~set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. |
| [mem](float.array#VALmem) [[Float.Array](float.array)] | `mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. |
| [mem](ephemeron.seededs#VALmem) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [mem](ephemeron.s#VALmem) [[Ephemeron.S](ephemeron.s)] | |
| [mem](arraylabels#VALmem) [[ArrayLabels](arraylabels)] | `mem a ~set` is true if and only if `a` is structurally equal to an element of `l` (i.e. |
| [mem](array#VALmem) [[Array](array)] | `mem a set` is true if and only if `a` is structurally equal to an element of `l` (i.e. |
| [mem\_assoc](listlabels#VALmem_assoc) [[ListLabels](listlabels)] | Same as [`ListLabels.assoc`](listlabels#VALassoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. |
| [mem\_assoc](list#VALmem_assoc) [[List](list)] | Same as [`List.assoc`](list#VALassoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. |
| [mem\_assq](listlabels#VALmem_assq) [[ListLabels](listlabels)] | Same as [`ListLabels.mem_assoc`](listlabels#VALmem_assoc), but uses physical equality instead of structural equality to compare keys. |
| [mem\_assq](list#VALmem_assq) [[List](list)] | Same as [`List.mem_assoc`](list#VALmem_assoc), but uses physical equality instead of structural equality to compare keys. |
| [mem\_ieee](float.arraylabels#VALmem_ieee) [[Float.ArrayLabels](float.arraylabels)] | Same as [`Float.ArrayLabels.mem`](float.arraylabels#VALmem), but uses IEEE equality instead of structural equality. |
| [mem\_ieee](float.array#VALmem_ieee) [[Float.Array](float.array)] | Same as [`Float.Array.mem`](float.array#VALmem), but uses IEEE equality instead of structural equality. |
| [memoize](seq#VALmemoize) [[Seq](seq)] | The sequence `memoize xs` has the same elements as the sequence `xs`. |
| [memq](listlabels#VALmemq) [[ListLabels](listlabels)] | Same as [`ListLabels.mem`](listlabels#VALmem), but uses physical equality instead of structural equality to compare list elements. |
| [memq](list#VALmemq) [[List](list)] | Same as [`List.mem`](list#VALmem), but uses physical equality instead of structural equality to compare list elements. |
| [memq](arraylabels#VALmemq) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.mem`](arraylabels#VALmem), but uses physical equality instead of structural equality to compare list elements. |
| [memq](array#VALmemq) [[Array](array)] | Same as [`Array.mem`](array#VALmem), but uses physical equality instead of structural equality to compare list elements. |
| [merge](weak.s#VALmerge) [[Weak.S](weak.s)] | `merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. |
| [merge](morelabels.map.s#VALmerge) [[MoreLabels.Map.S](morelabels.map.s)] | `merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. |
| [merge](map.s#VALmerge) [[Map.S](map.s)] | `merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. |
| [merge](listlabels#VALmerge) [[ListLabels](listlabels)] | Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. |
| [merge](list#VALmerge) [[List](list)] | Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. |
| [min](uchar#VALmin) [[Uchar](uchar)] | `min` is U+0000. |
| [min](nativeint#VALmin) [[Nativeint](nativeint)] | Return the smaller of the two arguments. |
| [min](int64#VALmin) [[Int64](int64)] | Return the smaller of the two arguments. |
| [min](int32#VALmin) [[Int32](int32)] | Return the smaller of the two arguments. |
| [min](int#VALmin) [[Int](int)] | Return the smaller of the two arguments. |
| [min](float#VALmin) [[Float](float)] | `min x y` returns the minimum of `x` and `y`. |
| [min](stdlib#VALmin) [[Stdlib](stdlib)] | Return the smaller of the two arguments. |
| [min\_binding](morelabels.map.s#VALmin_binding) [[MoreLabels.Map.S](morelabels.map.s)] | Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the map is empty. |
| [min\_binding](map.s#VALmin_binding) [[Map.S](map.s)] | Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the map is empty. |
| [min\_binding\_opt](morelabels.map.s#VALmin_binding_opt) [[MoreLabels.Map.S](morelabels.map.s)] | Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. |
| [min\_binding\_opt](map.s#VALmin_binding_opt) [[Map.S](map.s)] | Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. |
| [min\_elt](set.s#VALmin_elt) [[Set.S](set.s)] | Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the set is empty. |
| [min\_elt](morelabels.set.s#VALmin_elt) [[MoreLabels.Set.S](morelabels.set.s)] | Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the set is empty. |
| [min\_elt\_opt](set.s#VALmin_elt_opt) [[Set.S](set.s)] | Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. |
| [min\_elt\_opt](morelabels.set.s#VALmin_elt_opt) [[MoreLabels.Set.S](morelabels.set.s)] | Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. |
| [min\_float](float#VALmin_float) [[Float](float)] | The smallest positive, non-zero, non-denormalized value of type `float`. |
| [min\_float](stdlib#VALmin_float) [[Stdlib](stdlib)] | The smallest positive, non-zero, non-denormalized value of type `float`. |
| [min\_int](nativeint#VALmin_int) [[Nativeint](nativeint)] | The smallest representable native integer, either -231 on a 32-bit platform, or -263 on a 64-bit platform. |
| [min\_int](int64#VALmin_int) [[Int64](int64)] | The smallest representable 64-bit integer, -263. |
| [min\_int](int32#VALmin_int) [[Int32](int32)] | The smallest representable 32-bit integer, -231. |
| [min\_int](int#VALmin_int) [[Int](int)] | `min_int` is the smallest representable integer, `-2{^[Sys.int_size - 1]}`. |
| [min\_int](stdlib#VALmin_int) [[Stdlib](stdlib)] | The smallest representable integer. |
| [min\_max](float#VALmin_max) [[Float](float)] | `min_max x y` is `(min x y, max x y)`, just more efficient. |
| [min\_max\_num](float#VALmin_max_num) [[Float](float)] | `min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. |
| [min\_num](float#VALmin_num) [[Float](float)] | `min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. |
| [minor](gc#VALminor) [[Gc](gc)] | Trigger a minor collection. |
| [minor\_words](gc#VALminor_words) [[Gc](gc)] | Number of words allocated in the minor heap by this domain or potentially previous domains. |
| [minus\_one](nativeint#VALminus_one) [[Nativeint](nativeint)] | The native integer -1. |
| [minus\_one](int64#VALminus_one) [[Int64](int64)] | The 64-bit integer -1. |
| [minus\_one](int32#VALminus_one) [[Int32](int32)] | The 32-bit integer -1. |
| [minus\_one](int#VALminus_one) [[Int](int)] | `minus_one` is the integer `-1`. |
| [minus\_one](float#VALminus_one) [[Float](float)] | The floating-point -1. |
| [mkdir](unixlabels#VALmkdir) [[UnixLabels](unixlabels)] | Create a directory with the given permissions (see [`UnixLabels.umask`](unixlabels#VALumask)). |
| [mkdir](unix#VALmkdir) [[Unix](unix)] | Create a directory with the given permissions (see [`Unix.umask`](unix#VALumask)). |
| [mkdir](sys#VALmkdir) [[Sys](sys)] | Create a directory with the given permissions. |
| [mkfifo](unixlabels#VALmkfifo) [[UnixLabels](unixlabels)] | Create a named pipe with the given permissions (see [`UnixLabels.umask`](unixlabels#VALumask)). |
| [mkfifo](unix#VALmkfifo) [[Unix](unix)] | Create a named pipe with the given permissions (see [`Unix.umask`](unix#VALumask)). |
| [mktime](unixlabels#VALmktime) [[UnixLabels](unixlabels)] | Convert a date and time, specified by the `tm` argument, into a time in seconds, as returned by [`UnixLabels.time`](unixlabels#VALtime). |
| [mktime](unix#VALmktime) [[Unix](unix)] | Convert a date and time, specified by the `tm` argument, into a time in seconds, as returned by [`Unix.time`](unix#VALtime). |
| [mod\_float](stdlib#VALmod_float) [[Stdlib](stdlib)] | `mod_float a b` returns the remainder of `a` with respect to `b`. |
| [modf](float#VALmodf) [[Float](float)] | `modf f` returns the pair of the fractional and integral part of `f`. |
| [modf](stdlib#VALmodf) [[Stdlib](stdlib)] | `modf f` returns the pair of the fractional and integral part of `f`. |
| [mul](nativeint#VALmul) [[Nativeint](nativeint)] | Multiplication. |
| [mul](int64#VALmul) [[Int64](int64)] | Multiplication. |
| [mul](int32#VALmul) [[Int32](int32)] | Multiplication. |
| [mul](int#VALmul) [[Int](int)] | `mul x y` is the multiplication `x * y`. |
| [mul](float#VALmul) [[Float](float)] | Floating-point multiplication. |
| [mul](complex#VALmul) [[Complex](complex)] | Multiplication |
| N |
| [name](printexc.slot#VALname) [[Printexc.Slot](printexc.slot)] | `name slot` returns the name of the function or definition enclosing the location referred to by the slot. |
| [name](obj.extension_constructor#VALname) [[Obj.Extension\_constructor](obj.extension_constructor)] | |
| [name\_of\_input](scanf.scanning#VALname_of_input) [[Scanf.Scanning](scanf.scanning)] | `Scanning.name_of_input ic` returns the name of the character source for the given [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel. |
| [nan](float#VALnan) [[Float](float)] | A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. |
| [nan](stdlib#VALnan) [[Stdlib](stdlib)] | A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. |
| [narrow](camlinternaloo#VALnarrow) [[CamlinternalOO](camlinternaloo)] | |
| [nativebits](random.state#VALnativebits) [[Random.State](random.state)] | These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one. |
| [nativebits](random#VALnativebits) [[Random](random)] | `Random.nativebits ()` returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between [`Nativeint.min_int`](nativeint#VALmin_int) and [`Nativeint.max_int`](nativeint#VALmax_int). |
| [nativeint](random.state#VALnativeint) [[Random.State](random.state)] | |
| [nativeint](random#VALnativeint) [[Random](random)] | `Random.nativeint bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). |
| [nativeint](bigarray#VALnativeint) [[Bigarray](bigarray)] | See [`Bigarray.char`](bigarray#VALchar). |
| [neg](nativeint#VALneg) [[Nativeint](nativeint)] | Unary negation. |
| [neg](int64#VALneg) [[Int64](int64)] | Unary negation. |
| [neg](int32#VALneg) [[Int32](int32)] | Unary negation. |
| [neg](int#VALneg) [[Int](int)] | `neg x` is `~-x`. |
| [neg](float#VALneg) [[Float](float)] | Unary negation. |
| [neg](complex#VALneg) [[Complex](complex)] | Unary negation. |
| [neg\_infinity](float#VALneg_infinity) [[Float](float)] | Negative infinity. |
| [neg\_infinity](stdlib#VALneg_infinity) [[Stdlib](stdlib)] | Negative infinity. |
| [negate](fun#VALnegate) [[Fun](fun)] | `negate p` is the negation of the predicate function `p`. |
| [new\_block](obj#VALnew_block) [[Obj](obj)] | |
| [new\_channel](event#VALnew_channel) [[Event](event)] | Return a new channel. |
| [new\_key](domain.dls#VALnew_key) [[Domain.DLS](domain.dls)] | `new_key f` returns a new key bound to initialiser `f` for accessing , domain-local variables. |
| [new\_line](lexing#VALnew_line) [[Lexing](lexing)] | Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. |
| [new\_method](camlinternaloo#VALnew_method) [[CamlinternalOO](camlinternaloo)] | |
| [new\_methods\_variables](camlinternaloo#VALnew_methods_variables) [[CamlinternalOO](camlinternaloo)] | |
| [new\_variable](camlinternaloo#VALnew_variable) [[CamlinternalOO](camlinternaloo)] | |
| [next\_after](float#VALnext_after) [[Float](float)] | `next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. |
| [nice](unixlabels#VALnice) [[UnixLabels](unixlabels)] | Change the process priority. |
| [nice](unix#VALnice) [[Unix](unix)] | Change the process priority. |
| [no\_scan\_tag](obj#VALno_scan_tag) [[Obj](obj)] | |
| [none](option#VALnone) [[Option](option)] | `none` is `None`. |
| [norm](complex#VALnorm) [[Complex](complex)] | Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`. |
| [norm2](complex#VALnorm2) [[Complex](complex)] | Norm squared: given `x + i.y`, returns `x^2 + y^2`. |
| [not](bool#VALnot) [[Bool](bool)] | `not b` is the boolean negation of `b`. |
| [not](stdlib#VALnot) [[Stdlib](stdlib)] | The boolean negation. |
| [nth](listlabels#VALnth) [[ListLabels](listlabels)] | Return the `n`-th element of the given list. |
| [nth](list#VALnth) [[List](list)] | Return the `n`-th element of the given list. |
| [nth](buffer#VALnth) [[Buffer](buffer)] | Get the n-th character of the buffer. |
| [nth\_dim](bigarray.genarray#VALnth_dim) [[Bigarray.Genarray](bigarray.genarray)] | `Genarray.nth_dim a n` returns the `n`-th dimension of the Bigarray `a`. |
| [nth\_opt](listlabels#VALnth_opt) [[ListLabels](listlabels)] | Return the `n`-th element of the given list. |
| [nth\_opt](list#VALnth_opt) [[List](list)] | Return the `n`-th element of the given list. |
| [null](filename#VALnull) [[Filename](filename)] | `null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. |
| [null\_tracker](gc.memprof#VALnull_tracker) [[Gc.Memprof](gc.memprof)] | Default callbacks simply return `None` or `()` |
| [num\_dims](bigarray.genarray#VALnum_dims) [[Bigarray.Genarray](bigarray.genarray)] | Return the number of dimensions of the given Bigarray. |
| O |
| [obj](obj#VALobj) [[Obj](obj)] | |
| [object\_tag](obj#VALobject_tag) [[Obj](obj)] | |
| [ocaml\_release](sys#VALocaml_release) [[Sys](sys)] | `ocaml_release` is the version of OCaml. |
| [ocaml\_version](sys#VALocaml_version) [[Sys](sys)] | `ocaml_version` is the version of OCaml. |
| [of\_array](bigarray.array3#VALof_array) [[Bigarray.Array3](bigarray.array3)] | Build a three-dimensional Bigarray initialized from the given array of arrays of arrays. |
| [of\_array](bigarray.array2#VALof_array) [[Bigarray.Array2](bigarray.array2)] | Build a two-dimensional Bigarray initialized from the given array of arrays. |
| [of\_array](bigarray.array1#VALof_array) [[Bigarray.Array1](bigarray.array1)] | Build a one-dimensional Bigarray initialized from the given array. |
| [of\_bytes](string#VALof_bytes) [[String](string)] | Return a new string that contains the same bytes as the given byte sequence. |
| [of\_bytes](stringlabels#VALof_bytes) [[StringLabels](stringlabels)] | Return a new string that contains the same bytes as the given byte sequence. |
| [of\_char](uchar#VALof_char) [[Uchar](uchar)] | `of_char c` is `c` as a Unicode character. |
| [of\_dispenser](seq#VALof_dispenser) [[Seq](seq)] | `of_dispenser it` is the sequence of the elements produced by the dispenser `it`. |
| [of\_float](nativeint#VALof_float) [[Nativeint](nativeint)] | Convert the given floating-point number to a native integer, discarding the fractional part (truncate towards 0). |
| [of\_float](int64#VALof_float) [[Int64](int64)] | Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). |
| [of\_float](int32#VALof_float) [[Int32](int32)] | Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). |
| [of\_float](int#VALof_float) [[Int](int)] | `of_float x` truncates `x` to an integer. |
| [of\_int](uchar#VALof_int) [[Uchar](uchar)] | `of_int i` is `i` as a Unicode character. |
| [of\_int](nativeint#VALof_int) [[Nativeint](nativeint)] | Convert the given integer (type `int`) to a native integer (type `nativeint`). |
| [of\_int](int64#VALof_int) [[Int64](int64)] | Convert the given integer (type `int`) to a 64-bit integer (type `int64`). |
| [of\_int](int32#VALof_int) [[Int32](int32)] | Convert the given integer (type `int`) to a 32-bit integer (type `int32`). |
| [of\_int](float#VALof_int) [[Float](float)] | Convert an integer to floating-point. |
| [of\_int32](nativeint#VALof_int32) [[Nativeint](nativeint)] | Convert the given 32-bit integer (type `int32`) to a native integer. |
| [of\_int32](int64#VALof_int32) [[Int64](int64)] | Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`). |
| [of\_list](set.s#VALof_list) [[Set.S](set.s)] | `of_list l` creates a set from a list of elements. |
| [of\_list](morelabels.set.s#VALof_list) [[MoreLabels.Set.S](morelabels.set.s)] | `of_list l` creates a set from a list of elements. |
| [of\_list](float.arraylabels#VALof_list) [[Float.ArrayLabels](float.arraylabels)] | `of_list l` returns a fresh floatarray containing the elements of `l`. |
| [of\_list](float.array#VALof_list) [[Float.Array](float.array)] | `of_list l` returns a fresh floatarray containing the elements of `l`. |
| [of\_list](arraylabels#VALof_list) [[ArrayLabels](arraylabels)] | `of_list l` returns a fresh array containing the elements of `l`. |
| [of\_list](array#VALof_list) [[Array](array)] | `of_list l` returns a fresh array containing the elements of `l`. |
| [of\_nativeint](int64#VALof_nativeint) [[Int64](int64)] | Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`). |
| [of\_seq](string#VALof_seq) [[String](string)] | `of_seq s` is a string made of the sequence's characters. |
| [of\_seq](stringlabels#VALof_seq) [[StringLabels](stringlabels)] | `of_seq s` is a string made of the sequence's characters. |
| [of\_seq](stack#VALof_seq) [[Stack](stack)] | Create a stack from the sequence. |
| [of\_seq](set.s#VALof_seq) [[Set.S](set.s)] | Build a set from the given bindings |
| [of\_seq](queue#VALof_seq) [[Queue](queue)] | Create a queue from a sequence. |
| [of\_seq](morelabels.set.s#VALof_seq) [[MoreLabels.Set.S](morelabels.set.s)] | Build a set from the given bindings |
| [of\_seq](morelabels.map.s#VALof_seq) [[MoreLabels.Map.S](morelabels.map.s)] | Build a map from the given bindings |
| [of\_seq](morelabels.hashtbl.seededs#VALof_seq) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [of\_seq](morelabels.hashtbl.s#VALof_seq) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [of\_seq](morelabels.hashtbl#VALof_seq) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Build a table from the given bindings. |
| [of\_seq](map.s#VALof_seq) [[Map.S](map.s)] | Build a map from the given bindings |
| [of\_seq](listlabels#VALof_seq) [[ListLabels](listlabels)] | Create a list from a sequence. |
| [of\_seq](list#VALof_seq) [[List](list)] | Create a list from a sequence. |
| [of\_seq](hashtbl.seededs#VALof_seq) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [of\_seq](hashtbl.s#VALof_seq) [[Hashtbl.S](hashtbl.s)] | |
| [of\_seq](hashtbl#VALof_seq) [[Hashtbl](hashtbl)] | Build a table from the given bindings. |
| [of\_seq](float.arraylabels#VALof_seq) [[Float.ArrayLabels](float.arraylabels)] | Create an array from the generator. |
| [of\_seq](float.array#VALof_seq) [[Float.Array](float.array)] | Create an array from the generator. |
| [of\_seq](ephemeron.seededs#VALof_seq) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [of\_seq](ephemeron.s#VALof_seq) [[Ephemeron.S](ephemeron.s)] | |
| [of\_seq](byteslabels#VALof_seq) [[BytesLabels](byteslabels)] | Create a string from the generator |
| [of\_seq](bytes#VALof_seq) [[Bytes](bytes)] | Create a string from the generator |
| [of\_seq](buffer#VALof_seq) [[Buffer](buffer)] | Create a buffer from the generator |
| [of\_seq](arraylabels#VALof_seq) [[ArrayLabels](arraylabels)] | Create an array from the generator |
| [of\_seq](array#VALof_seq) [[Array](array)] | Create an array from the generator |
| [of\_string](nativeint#VALof_string) [[Nativeint](nativeint)] | Convert the given string to a native integer. |
| [of\_string](int64#VALof_string) [[Int64](int64)] | Convert the given string to a 64-bit integer. |
| [of\_string](int32#VALof_string) [[Int32](int32)] | Convert the given string to a 32-bit integer. |
| [of\_string](float#VALof_string) [[Float](float)] | Convert the given string to a float. |
| [of\_string](byteslabels#VALof_string) [[BytesLabels](byteslabels)] | Return a new byte sequence that contains the same bytes as the given string. |
| [of\_string](bytes#VALof_string) [[Bytes](bytes)] | Return a new byte sequence that contains the same bytes as the given string. |
| [of\_string\_opt](nativeint#VALof_string_opt) [[Nativeint](nativeint)] | Same as `of_string`, but return `None` instead of raising. |
| [of\_string\_opt](int64#VALof_string_opt) [[Int64](int64)] | Same as `of_string`, but return `None` instead of raising. |
| [of\_string\_opt](int32#VALof_string_opt) [[Int32](int32)] | Same as `of_string`, but return `None` instead of raising. |
| [of\_string\_opt](float#VALof_string_opt) [[Float](float)] | Same as `of_string`, but returns `None` instead of raising. |
| [of\_val](obj.extension_constructor#VALof_val) [[Obj.Extension\_constructor](obj.extension_constructor)] | |
| [of\_value](bigarray.array0#VALof_value) [[Bigarray.Array0](bigarray.array0)] | Build a zero-dimensional Bigarray initialized from the given value. |
| [ok](result#VALok) [[Result](result)] | `ok v` is `Ok v`. |
| [once](seq#VALonce) [[Seq](seq)] | The sequence `once xs` has the same elements as the sequence `xs`. |
| [one](nativeint#VALone) [[Nativeint](nativeint)] | The native integer 1. |
| [one](int64#VALone) [[Int64](int64)] | The 64-bit integer 1. |
| [one](int32#VALone) [[Int32](int32)] | The 32-bit integer 1. |
| [one](int#VALone) [[Int](int)] | `one` is the integer `1`. |
| [one](float#VALone) [[Float](float)] | The floating-point 1. |
| [one](complex#VALone) [[Complex](complex)] | The complex number `1`. |
| [opaque\_identity](sys#VALopaque_identity) [[Sys](sys)] | For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function. |
| [open\_bin](out_channel#VALopen_bin) [[Out\_channel](out_channel)] | Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. |
| [open\_bin](in_channel#VALopen_bin) [[In\_channel](in_channel)] | Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. |
| [open\_box](format#VALopen_box) [[Format](format)] | `pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`. |
| [open\_box\_of\_string](camlinternalformat#VALopen_box_of_string) [[CamlinternalFormat](camlinternalformat)] | |
| [open\_connection](unixlabels#VALopen_connection) [[UnixLabels](unixlabels)] | Connect to a server at the given address. |
| [open\_connection](unix#VALopen_connection) [[Unix](unix)] | Connect to a server at the given address. |
| [open\_gen](out_channel#VALopen_gen) [[Out\_channel](out_channel)] | `open_gen mode perm filename` opens the named file for writing, as described above. |
| [open\_gen](in_channel#VALopen_gen) [[In\_channel](in_channel)] | `open_gen mode perm filename` opens the named file for reading, as described above. |
| [open\_hbox](format#VALopen_hbox) [[Format](format)] | `pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box. |
| [open\_hovbox](format#VALopen_hovbox) [[Format](format)] | `pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`. |
| [open\_hvbox](format#VALopen_hvbox) [[Format](format)] | `pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`. |
| [open\_in](scanf.scanning#VALopen_in) [[Scanf.Scanning](scanf.scanning)] | `Scanning.open_in fname` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel for bufferized reading in text mode from file `fname`. |
| [open\_in](stdlib#VALopen_in) [[Stdlib](stdlib)] | Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. |
| [open\_in\_bin](scanf.scanning#VALopen_in_bin) [[Scanf.Scanning](scanf.scanning)] | `Scanning.open_in_bin fname` returns a [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel for bufferized reading in binary mode from file `fname`. |
| [open\_in\_bin](stdlib#VALopen_in_bin) [[Stdlib](stdlib)] | Same as [`open_in`](stdlib#VALopen_in), but the file is opened in binary mode, so that no translation takes place during reads. |
| [open\_in\_gen](stdlib#VALopen_in_gen) [[Stdlib](stdlib)] | `open_in_gen mode perm filename` opens the named file for reading, as described above. |
| [open\_out](stdlib#VALopen_out) [[Stdlib](stdlib)] | Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. |
| [open\_out\_bin](stdlib#VALopen_out_bin) [[Stdlib](stdlib)] | Same as [`open_out`](stdlib#VALopen_out), but the file is opened in binary mode, so that no translation takes place during writes. |
| [open\_out\_gen](stdlib#VALopen_out_gen) [[Stdlib](stdlib)] | `open_out_gen mode perm filename` opens the named file for writing, as described above. |
| [open\_process](unixlabels#VALopen_process) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out), but redirects both the standard input and standard output of the command to pipes connected to the two returned channels. |
| [open\_process](unix#VALopen_process) [[Unix](unix)] | Same as [`Unix.open_process_out`](unix#VALopen_process_out), but redirects both the standard input and standard output of the command to pipes connected to the two returned channels. |
| [open\_process\_args](unixlabels#VALopen_process_args) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.open_process_args_out`](unixlabels#VALopen_process_args_out), but redirects both the standard input and standard output of the new process to pipes connected to the two returned channels. |
| [open\_process\_args](unix#VALopen_process_args) [[Unix](unix)] | Same as [`Unix.open_process_args_out`](unix#VALopen_process_args_out), but redirects both the standard input and standard output of the new process to pipes connected to the two returned channels. |
| [open\_process\_args\_full](unixlabels#VALopen_process_args_full) [[UnixLabels](unixlabels)] | Similar to [`UnixLabels.open_process_args`](unixlabels#VALopen_process_args), but the third argument specifies the environment passed to the new process. |
| [open\_process\_args\_full](unix#VALopen_process_args_full) [[Unix](unix)] | Similar to [`Unix.open_process_args`](unix#VALopen_process_args), but the third argument specifies the environment passed to the new process. |
| [open\_process\_args\_in](unixlabels#VALopen_process_args_in) [[UnixLabels](unixlabels)] | `open_process_args_in prog args` runs the program `prog` with arguments `args`. |
| [open\_process\_args\_in](unix#VALopen_process_args_in) [[Unix](unix)] | `open_process_args_in prog args` runs the program `prog` with arguments `args`. |
| [open\_process\_args\_out](unixlabels#VALopen_process_args_out) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.open_process_args_in`](unixlabels#VALopen_process_args_in), but redirect the standard input of the new process to a pipe. |
| [open\_process\_args\_out](unix#VALopen_process_args_out) [[Unix](unix)] | Same as [`Unix.open_process_args_in`](unix#VALopen_process_args_in), but redirect the standard input of the new process to a pipe. |
| [open\_process\_full](unixlabels#VALopen_process_full) [[UnixLabels](unixlabels)] | Similar to [`UnixLabels.open_process`](unixlabels#VALopen_process), but the second argument specifies the environment passed to the command. |
| [open\_process\_full](unix#VALopen_process_full) [[Unix](unix)] | Similar to [`Unix.open_process`](unix#VALopen_process), but the second argument specifies the environment passed to the command. |
| [open\_process\_in](unixlabels#VALopen_process_in) [[UnixLabels](unixlabels)] | High-level pipe and process management. |
| [open\_process\_in](unix#VALopen_process_in) [[Unix](unix)] | High-level pipe and process management. |
| [open\_process\_out](unixlabels#VALopen_process_out) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in), but redirect the standard input of the command to a pipe. |
| [open\_process\_out](unix#VALopen_process_out) [[Unix](unix)] | Same as [`Unix.open_process_in`](unix#VALopen_process_in), but redirect the standard input of the command to a pipe. |
| [open\_stag](format#VALopen_stag) [[Format](format)] | `pp_open_stag ppf t` opens the semantic tag named `t`. |
| [open\_tbox](format#VALopen_tbox) [[Format](format)] | `open_tbox ()` opens a new tabulation box. |
| [open\_temp\_file](filename#VALopen_temp_file) [[Filename](filename)] | Same as [`Filename.temp_file`](filename#VALtemp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. |
| [open\_text](out_channel#VALopen_text) [[Out\_channel](out_channel)] | Same as [`Out\_channel.open_bin`](out_channel#VALopen_bin), but the file is opened in text mode, so that newline translation takes place during writes. |
| [open\_text](in_channel#VALopen_text) [[In\_channel](in_channel)] | Same as [`In\_channel.open_bin`](in_channel#VALopen_bin), but the file is opened in text mode, so that newline translation takes place during reads. |
| [open\_vbox](format#VALopen_vbox) [[Format](format)] | `pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`. |
| [opendir](unixlabels#VALopendir) [[UnixLabels](unixlabels)] | Open a descriptor on a directory |
| [opendir](unix#VALopendir) [[Unix](unix)] | Open a descriptor on a directory |
| [openfile](unixlabels#VALopenfile) [[UnixLabels](unixlabels)] | Open the named file with the given flags. |
| [openfile](unix#VALopenfile) [[Unix](unix)] | Open the named file with the given flags. |
| [os\_type](sys#VALos_type) [[Sys](sys)] | Operating system currently executing the OCaml program. |
| [out\_channel\_length](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html#VALout_channel_length) [[Stdlib.LargeFile](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html)] | |
| [out\_channel\_length](stdlib#VALout_channel_length) [[Stdlib](stdlib)] | Return the size (number of characters) of the regular file on which the given channel is opened. |
| [out\_channel\_of\_descr](unixlabels#VALout_channel_of_descr) [[UnixLabels](unixlabels)] | Create an output channel writing on the given descriptor. |
| [out\_channel\_of\_descr](unix#VALout_channel_of_descr) [[Unix](unix)] | Create an output channel writing on the given descriptor. |
| [out\_of\_heap\_tag](obj#VALout_of_heap_tag) [[Obj](obj)] | |
| [output](out_channel#VALoutput) [[Out\_channel](out_channel)] | `output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. |
| [output](digest#VALoutput) [[Digest](digest)] | Write a digest on the given output channel. |
| [output](stdlib#VALoutput) [[Stdlib](stdlib)] | `output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. |
| [output\_acc](camlinternalformat#VALoutput_acc) [[CamlinternalFormat](camlinternalformat)] | |
| [output\_binary\_int](stdlib#VALoutput_binary_int) [[Stdlib](stdlib)] | Write one integer in binary format (4 bytes, big-endian) on the given output channel. |
| [output\_buffer](buffer#VALoutput_buffer) [[Buffer](buffer)] | `output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`. |
| [output\_byte](out_channel#VALoutput_byte) [[Out\_channel](out_channel)] | Write one 8-bit integer (as the single character with that code) on the given output channel. |
| [output\_byte](stdlib#VALoutput_byte) [[Stdlib](stdlib)] | Write one 8-bit integer (as the single character with that code) on the given output channel. |
| [output\_bytes](out_channel#VALoutput_bytes) [[Out\_channel](out_channel)] | Write the byte sequence on the given output channel. |
| [output\_bytes](stdlib#VALoutput_bytes) [[Stdlib](stdlib)] | Write the byte sequence on the given output channel. |
| [output\_char](out_channel#VALoutput_char) [[Out\_channel](out_channel)] | Write the character on the given output channel. |
| [output\_char](stdlib#VALoutput_char) [[Stdlib](stdlib)] | Write the character on the given output channel. |
| [output\_string](out_channel#VALoutput_string) [[Out\_channel](out_channel)] | Write the string on the given output channel. |
| [output\_string](stdlib#VALoutput_string) [[Stdlib](stdlib)] | Write the string on the given output channel. |
| [output\_substring](out_channel#VALoutput_substring) [[Out\_channel](out_channel)] | Same as [`Out\_channel.output`](out_channel#VALoutput) but take a string as argument instead of a byte sequence. |
| [output\_substring](stdlib#VALoutput_substring) [[Stdlib](stdlib)] | Same as `output` but take a string as argument instead of a byte sequence. |
| [output\_value](stdlib#VALoutput_value) [[Stdlib](stdlib)] | Write the representation of a structured value of any type to a channel. |
| [over\_max\_boxes](format#VALover_max_boxes) [[Format](format)] | Tests if the maximum number of pretty-printing boxes allowed have already been opened. |
| P |
| [param\_format\_of\_ignored\_format](camlinternalformat#VALparam_format_of_ignored_format) [[CamlinternalFormat](camlinternalformat)] | |
| [params](camlinternaloo#VALparams) [[CamlinternalOO](camlinternaloo)] | |
| [parent\_dir\_name](filename#VALparent_dir_name) [[Filename](filename)] | The conventional name for the parent of the current directory (e.g. |
| [parse](arg#VALparse) [[Arg](arg)] | `Arg.parse speclist anon_fun usage_msg` parses the command line. |
| [parse\_and\_expand\_argv\_dynamic](arg#VALparse_and_expand_argv_dynamic) [[Arg](arg)] | Same as [`Arg.parse_argv_dynamic`](arg#VALparse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. |
| [parse\_argv](arg#VALparse_argv) [[Arg](arg)] | `Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. |
| [parse\_argv\_dynamic](arg#VALparse_argv_dynamic) [[Arg](arg)] | Same as [`Arg.parse_argv`](arg#VALparse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. |
| [parse\_dynamic](arg#VALparse_dynamic) [[Arg](arg)] | Same as [`Arg.parse`](arg#VALparse), except that the `speclist` argument is a reference and may be updated during the parsing. |
| [parse\_expand](arg#VALparse_expand) [[Arg](arg)] | Same as [`Arg.parse`](arg#VALparse), except that the `Expand` arguments are allowed and the [`Arg.current`](arg#VALcurrent) reference is not updated. |
| [partition](set.s#VALpartition) [[Set.S](set.s)] | `partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. |
| [partition](seq#VALpartition) [[Seq](seq)] | `partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`. |
| [partition](morelabels.set.s#VALpartition) [[MoreLabels.Set.S](morelabels.set.s)] | `partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. |
| [partition](morelabels.map.s#VALpartition) [[MoreLabels.Map.S](morelabels.map.s)] | `partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. |
| [partition](map.s#VALpartition) [[Map.S](map.s)] | `partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. |
| [partition](listlabels#VALpartition) [[ListLabels](listlabels)] | `partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. |
| [partition](list#VALpartition) [[List](list)] | `partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. |
| [partition\_map](seq#VALpartition_map) [[Seq](seq)] | `partition_map f xs` returns a pair of sequences `(ys, zs)`, where: |
| [partition\_map](listlabels#VALpartition_map) [[ListLabels](listlabels)] | `partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: if `f x` is `Left y1`, then `y1` is in `l1`, and, if `f x` is `Right y2`, then `y2` is in `l2`. The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. |
| [partition\_map](list#VALpartition_map) [[List](list)] | `partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: if `f x` is `Left y1`, then `y1` is in `l1`, and, if `f x` is `Right y2`, then `y2` is in `l2`. The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. |
| [pause](runtime_events#VALpause) [[Runtime\_events](runtime_events)] | `pause ()` will pause the collection of events in the runtime. |
| [pause](unixlabels#VALpause) [[UnixLabels](unixlabels)] | Wait until a non-ignored, non-blocked signal is delivered. |
| [pause](unix#VALpause) [[Unix](unix)] | Wait until a non-ignored, non-blocked signal is delivered. |
| [peek](queue#VALpeek) [[Queue](queue)] | `peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Queue.Empty`](queue#EXCEPTIONEmpty) if the queue is empty. |
| [peek\_opt](queue#VALpeek_opt) [[Queue](queue)] | `peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty. |
| [perform](effect#VALperform) [[Effect](effect)] | `perform e` performs an effect `e`. |
| [pi](float#VALpi) [[Float](float)] | The constant pi. |
| [pipe](unixlabels#VALpipe) [[UnixLabels](unixlabels)] | Create a pipe. |
| [pipe](unix#VALpipe) [[Unix](unix)] | Create a pipe. |
| [polar](complex#VALpolar) [[Complex](complex)] | `polar norm arg` returns the complex having norm `norm` and argument `arg`. |
| [poll](event#VALpoll) [[Event](event)] | Non-blocking version of [`Event.sync`](event#VALsync): offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return `Some r` where `r` is the result value of that communication. |
| [pop](stack#VALpop) [[Stack](stack)] | `pop s` removes and returns the topmost element in stack `s`, or raises [`Stack.Empty`](stack#EXCEPTIONEmpty) if the stack is empty. |
| [pop](queue#VALpop) [[Queue](queue)] | `pop` is a synonym for `take`. |
| [pop\_opt](stack#VALpop_opt) [[Stack](stack)] | `pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty. |
| [pos](out_channel#VALpos) [[Out\_channel](out_channel)] | Return the current writing position for the given channel. |
| [pos](in_channel#VALpos) [[In\_channel](in_channel)] | Return the current reading position for the given channel. |
| [pos\_in](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html#VALpos_in) [[Stdlib.LargeFile](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html)] | |
| [pos\_in](stdlib#VALpos_in) [[Stdlib](stdlib)] | Return the current reading position for the given channel. |
| [pos\_out](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html#VALpos_out) [[Stdlib.LargeFile](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html)] | |
| [pos\_out](stdlib#VALpos_out) [[Stdlib](stdlib)] | Return the current writing position for the given channel. |
| [pow](float#VALpow) [[Float](float)] | Exponentiation. |
| [pow](complex#VALpow) [[Complex](complex)] | Power function. |
| [pp\_close\_box](format#VALpp_close_box) [[Format](format)] | |
| [pp\_close\_stag](format#VALpp_close_stag) [[Format](format)] | |
| [pp\_close\_tbox](format#VALpp_close_tbox) [[Format](format)] | |
| [pp\_force\_newline](format#VALpp_force_newline) [[Format](format)] | |
| [pp\_get\_ellipsis\_text](format#VALpp_get_ellipsis_text) [[Format](format)] | |
| [pp\_get\_formatter\_out\_functions](format#VALpp_get_formatter_out_functions) [[Format](format)] | |
| [pp\_get\_formatter\_output\_functions](format#VALpp_get_formatter_output_functions) [[Format](format)] | |
| [pp\_get\_formatter\_stag\_functions](format#VALpp_get_formatter_stag_functions) [[Format](format)] | |
| [pp\_get\_geometry](format#VALpp_get_geometry) [[Format](format)] | |
| [pp\_get\_margin](format#VALpp_get_margin) [[Format](format)] | |
| [pp\_get\_mark\_tags](format#VALpp_get_mark_tags) [[Format](format)] | |
| [pp\_get\_max\_boxes](format#VALpp_get_max_boxes) [[Format](format)] | |
| [pp\_get\_max\_indent](format#VALpp_get_max_indent) [[Format](format)] | |
| [pp\_get\_print\_tags](format#VALpp_get_print_tags) [[Format](format)] | |
| [pp\_open\_box](format#VALpp_open_box) [[Format](format)] | |
| [pp\_open\_hbox](format#VALpp_open_hbox) [[Format](format)] | |
| [pp\_open\_hovbox](format#VALpp_open_hovbox) [[Format](format)] | |
| [pp\_open\_hvbox](format#VALpp_open_hvbox) [[Format](format)] | |
| [pp\_open\_stag](format#VALpp_open_stag) [[Format](format)] | |
| [pp\_open\_tbox](format#VALpp_open_tbox) [[Format](format)] | |
| [pp\_open\_vbox](format#VALpp_open_vbox) [[Format](format)] | |
| [pp\_over\_max\_boxes](format#VALpp_over_max_boxes) [[Format](format)] | |
| [pp\_print\_as](format#VALpp_print_as) [[Format](format)] | |
| [pp\_print\_bool](format#VALpp_print_bool) [[Format](format)] | |
| [pp\_print\_break](format#VALpp_print_break) [[Format](format)] | |
| [pp\_print\_bytes](format#VALpp_print_bytes) [[Format](format)] | |
| [pp\_print\_char](format#VALpp_print_char) [[Format](format)] | |
| [pp\_print\_custom\_break](format#VALpp_print_custom_break) [[Format](format)] | `pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point. |
| [pp\_print\_cut](format#VALpp_print_cut) [[Format](format)] | |
| [pp\_print\_either](format#VALpp_print_either) [[Format](format)] | `pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`. |
| [pp\_print\_float](format#VALpp_print_float) [[Format](format)] | |
| [pp\_print\_flush](format#VALpp_print_flush) [[Format](format)] | |
| [pp\_print\_if\_newline](format#VALpp_print_if_newline) [[Format](format)] | |
| [pp\_print\_int](format#VALpp_print_int) [[Format](format)] | |
| [pp\_print\_list](format#VALpp_print_list) [[Format](format)] | `pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`Format.pp_print_cut`](format#VALpp_print_cut). |
| [pp\_print\_newline](format#VALpp_print_newline) [[Format](format)] | |
| [pp\_print\_option](format#VALpp_print_option) [[Format](format)] | `pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. |
| [pp\_print\_result](format#VALpp_print_result) [[Format](format)] | `pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`. |
| [pp\_print\_seq](format#VALpp_print_seq) [[Format](format)] | `pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`Format.pp_print_cut`](format#VALpp_print_cut). |
| [pp\_print\_space](format#VALpp_print_space) [[Format](format)] | |
| [pp\_print\_string](format#VALpp_print_string) [[Format](format)] | |
| [pp\_print\_tab](format#VALpp_print_tab) [[Format](format)] | |
| [pp\_print\_tbreak](format#VALpp_print_tbreak) [[Format](format)] | |
| [pp\_print\_text](format#VALpp_print_text) [[Format](format)] | `pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`Format.pp_print_space`](format#VALpp_print_space) and [`Format.pp_force_newline`](format#VALpp_force_newline). |
| [pp\_safe\_set\_geometry](format#VALpp_safe_set_geometry) [[Format](format)] | |
| [pp\_set\_ellipsis\_text](format#VALpp_set_ellipsis_text) [[Format](format)] | |
| [pp\_set\_formatter\_out\_channel](format#VALpp_set_formatter_out_channel) [[Format](format)] | Redirecting the standard formatter output |
| [pp\_set\_formatter\_out\_functions](format#VALpp_set_formatter_out_functions) [[Format](format)] | |
| [pp\_set\_formatter\_output\_functions](format#VALpp_set_formatter_output_functions) [[Format](format)] | |
| [pp\_set\_formatter\_stag\_functions](format#VALpp_set_formatter_stag_functions) [[Format](format)] | |
| [pp\_set\_geometry](format#VALpp_set_geometry) [[Format](format)] | |
| [pp\_set\_margin](format#VALpp_set_margin) [[Format](format)] | |
| [pp\_set\_mark\_tags](format#VALpp_set_mark_tags) [[Format](format)] | |
| [pp\_set\_max\_boxes](format#VALpp_set_max_boxes) [[Format](format)] | |
| [pp\_set\_max\_indent](format#VALpp_set_max_indent) [[Format](format)] | |
| [pp\_set\_print\_tags](format#VALpp_set_print_tags) [[Format](format)] | |
| [pp\_set\_tab](format#VALpp_set_tab) [[Format](format)] | |
| [pp\_set\_tags](format#VALpp_set_tags) [[Format](format)] | |
| [pp\_update\_geometry](format#VALpp_update_geometry) [[Format](format)] | `pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields. |
| [pred](uchar#VALpred) [[Uchar](uchar)] | `pred u` is the scalar value before `u` in the set of Unicode scalar values. |
| [pred](nativeint#VALpred) [[Nativeint](nativeint)] | Predecessor. |
| [pred](int64#VALpred) [[Int64](int64)] | Predecessor. |
| [pred](int32#VALpred) [[Int32](int32)] | Predecessor. |
| [pred](int#VALpred) [[Int](int)] | `pred x` is `sub x 1`. |
| [pred](float#VALpred) [[Float](float)] | `pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. |
| [pred](stdlib#VALpred) [[Stdlib](stdlib)] | `pred x` is `x - 1`. |
| [prerr\_bytes](stdlib#VALprerr_bytes) [[Stdlib](stdlib)] | Print a byte sequence on standard error. |
| [prerr\_char](stdlib#VALprerr_char) [[Stdlib](stdlib)] | Print a character on standard error. |
| [prerr\_endline](stdlib#VALprerr_endline) [[Stdlib](stdlib)] | Print a string, followed by a newline character on standard error and flush standard error. |
| [prerr\_float](stdlib#VALprerr_float) [[Stdlib](stdlib)] | Print a floating-point number, in decimal, on standard error. |
| [prerr\_int](stdlib#VALprerr_int) [[Stdlib](stdlib)] | Print an integer, in decimal, on standard error. |
| [prerr\_newline](stdlib#VALprerr_newline) [[Stdlib](stdlib)] | Print a newline character on standard error, and flush standard error. |
| [prerr\_string](stdlib#VALprerr_string) [[Stdlib](stdlib)] | Print a string on standard error. |
| [print](printexc#VALprint) [[Printexc](printexc)] | `Printexc.print fn x` applies `fn` to `x` and returns the result. |
| [print\_as](format#VALprint_as) [[Format](format)] | `pp_print_as ppf len s` prints `s` in the current pretty-printing box. |
| [print\_backtrace](printexc#VALprint_backtrace) [[Printexc](printexc)] | `Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. |
| [print\_bool](format#VALprint_bool) [[Format](format)] | Print a boolean in the current pretty-printing box. |
| [print\_break](format#VALprint_break) [[Format](format)] | `pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces. |
| [print\_bytes](format#VALprint_bytes) [[Format](format)] | `pp_print_bytes ppf b` prints `b` in the current pretty-printing box. |
| [print\_bytes](stdlib#VALprint_bytes) [[Stdlib](stdlib)] | Print a byte sequence on standard output. |
| [print\_char](format#VALprint_char) [[Format](format)] | Print a character in the current pretty-printing box. |
| [print\_char](stdlib#VALprint_char) [[Stdlib](stdlib)] | Print a character on standard output. |
| [print\_cut](format#VALprint_cut) [[Format](format)] | `pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing. |
| [print\_endline](stdlib#VALprint_endline) [[Stdlib](stdlib)] | Print a string, followed by a newline character, on standard output and flush standard output. |
| [print\_float](format#VALprint_float) [[Format](format)] | Print a floating point number in the current pretty-printing box. |
| [print\_float](stdlib#VALprint_float) [[Stdlib](stdlib)] | Print a floating-point number, in decimal, on standard output. |
| [print\_flush](format#VALprint_flush) [[Format](format)] | End of pretty-printing: resets the pretty-printer to initial state. |
| [print\_if\_newline](format#VALprint_if_newline) [[Format](format)] | Execute the next formatting command if the preceding line has just been split. |
| [print\_int](format#VALprint_int) [[Format](format)] | Print an integer in the current pretty-printing box. |
| [print\_int](stdlib#VALprint_int) [[Stdlib](stdlib)] | Print an integer, in decimal, on standard output. |
| [print\_newline](format#VALprint_newline) [[Format](format)] | End of pretty-printing: resets the pretty-printer to initial state. |
| [print\_newline](stdlib#VALprint_newline) [[Stdlib](stdlib)] | Print a newline character on standard output, and flush standard output. |
| [print\_raw\_backtrace](printexc#VALprint_raw_backtrace) [[Printexc](printexc)] | Print a raw backtrace in the same format `Printexc.print_backtrace` uses. |
| [print\_space](format#VALprint_space) [[Format](format)] | `pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space. |
| [print\_stat](gc#VALprint_stat) [[Gc](gc)] | Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument. |
| [print\_string](format#VALprint_string) [[Format](format)] | `pp_print_string ppf s` prints `s` in the current pretty-printing box. |
| [print\_string](stdlib#VALprint_string) [[Stdlib](stdlib)] | Print a string on standard output. |
| [print\_tab](format#VALprint_tab) [[Format](format)] | `print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. |
| [print\_tbreak](format#VALprint_tbreak) [[Format](format)] | `print_tbreak nspaces offset` emits a 'full' tabulation break hint. |
| [printf](printf#VALprintf) [[Printf](printf)] | Same as [`Printf.fprintf`](printf#VALfprintf), but output on `stdout`. |
| [printf](format#VALprintf) [[Format](format)] | Same as `fprintf` above, but output on `get_std_formatter ()`. |
| [process\_full\_pid](unixlabels#VALprocess_full_pid) [[UnixLabels](unixlabels)] | Return the pid of a process opened via [`UnixLabels.open_process_full`](unixlabels#VALopen_process_full) or [`UnixLabels.open_process_args_full`](unixlabels#VALopen_process_args_full). |
| [process\_full\_pid](unix#VALprocess_full_pid) [[Unix](unix)] | Return the pid of a process opened via [`Unix.open_process_full`](unix#VALopen_process_full) or [`Unix.open_process_args_full`](unix#VALopen_process_args_full). |
| [process\_in\_pid](unixlabels#VALprocess_in_pid) [[UnixLabels](unixlabels)] | Return the pid of a process opened via [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in) or [`UnixLabels.open_process_args_in`](unixlabels#VALopen_process_args_in). |
| [process\_in\_pid](unix#VALprocess_in_pid) [[Unix](unix)] | Return the pid of a process opened via [`Unix.open_process_in`](unix#VALopen_process_in) or [`Unix.open_process_args_in`](unix#VALopen_process_args_in). |
| [process\_out\_pid](unixlabels#VALprocess_out_pid) [[UnixLabels](unixlabels)] | Return the pid of a process opened via [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out) or [`UnixLabels.open_process_args_out`](unixlabels#VALopen_process_args_out). |
| [process\_out\_pid](unix#VALprocess_out_pid) [[Unix](unix)] | Return the pid of a process opened via [`Unix.open_process_out`](unix#VALopen_process_out) or [`Unix.open_process_args_out`](unix#VALopen_process_args_out). |
| [process\_pid](unixlabels#VALprocess_pid) [[UnixLabels](unixlabels)] | Return the pid of a process opened via [`UnixLabels.open_process`](unixlabels#VALopen_process) or [`UnixLabels.open_process_args`](unixlabels#VALopen_process_args). |
| [process\_pid](unix#VALprocess_pid) [[Unix](unix)] | Return the pid of a process opened via [`Unix.open_process`](unix#VALopen_process) or [`Unix.open_process_args`](unix#VALopen_process_args). |
| [product](seq#VALproduct) [[Seq](seq)] | `product xs ys` is the Cartesian product of the sequences `xs` and `ys`. |
| [prohibit](dynlink#VALprohibit) [[Dynlink](dynlink)] | `prohibit units` prohibits dynamically-linked units from referencing the units named in list `units` by removing such units from the allowed units list. |
| [protect](fun#VALprotect) [[Fun](fun)] | `protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. |
| [public\_dynamically\_loaded\_units](dynlink#VALpublic_dynamically_loaded_units) [[Dynlink](dynlink)] | Return the list of compilation units that have been dynamically loaded via `loadfile` (and not via `loadfile_private`). |
| [public\_method\_label](camlinternaloo#VALpublic_method_label) [[CamlinternalOO](camlinternaloo)] | |
| [push](stack#VALpush) [[Stack](stack)] | `push x s` adds the element `x` at the top of stack `s`. |
| [push](queue#VALpush) [[Queue](queue)] | `push` is a synonym for `add`. |
| [putenv](unixlabels#VALputenv) [[UnixLabels](unixlabels)] | `putenv name value` sets the value associated to a variable in the process environment. |
| [putenv](unix#VALputenv) [[Unix](unix)] | `putenv name value` sets the value associated to a variable in the process environment. |
| Q |
| [query](ephemeron.kn#VALquery) [[Ephemeron.Kn](ephemeron.kn)] | Same as [`Ephemeron.K1.query`](ephemeron.k1#VALquery) |
| [query](ephemeron.k2#VALquery) [[Ephemeron.K2](ephemeron.k2)] | Same as [`Ephemeron.K1.query`](ephemeron.k1#VALquery) |
| [query](ephemeron.k1#VALquery) [[Ephemeron.K1](ephemeron.k1)] | `Ephemeron.K1.query eph key` returns `Some x` (where `x` is the ephemeron's data) if `key` is physically equal to `eph`'s key, and `None` if `eph` is empty or `key` is not equal to `eph`'s key. |
| [quick\_stat](gc#VALquick_stat) [[Gc](gc)] | Same as `stat` except that `live_words`, `live_blocks`, `free_words`, `free_blocks`, `largest_free`, and `fragments` are set to 0. |
| [quote](str#VALquote) [[Str](str)] | `Str.quote s` returns a regexp string that matches exactly `s` and nothing else. |
| [quote](filename#VALquote) [[Filename](filename)] | Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. |
| [quote\_command](filename#VALquote_command) [[Filename](filename)] | `quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](sys#VALcommand), [`Unix.system`](unix#VALsystem), and the [`Unix.open_process`](unix#VALopen_process) functions. |
| R |
| [raise](stdlib#VALraise) [[Stdlib](stdlib)] | Raise the given exception value |
| [raise\_notrace](stdlib#VALraise_notrace) [[Stdlib](stdlib)] | A faster version `raise` which does not record the backtrace. |
| [raise\_with\_backtrace](printexc#VALraise_with_backtrace) [[Printexc](printexc)] | Reraise the exception using the given raw\_backtrace for the origin of the exception |
| [randomize](morelabels.hashtbl#VALrandomize) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`MoreLabels.Hashtbl.create`](morelabels.hashtbl#VALcreate) returns randomized hash tables, unless the `~random:false` optional parameter is given. |
| [randomize](hashtbl#VALrandomize) [[Hashtbl](hashtbl)] | After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`Hashtbl.create`](hashtbl#VALcreate) returns randomized hash tables, unless the `~random:false` optional parameter is given. |
| [raw\_backtrace\_entries](printexc#VALraw_backtrace_entries) [[Printexc](printexc)] | |
| [raw\_backtrace\_length](printexc#VALraw_backtrace_length) [[Printexc](printexc)] | `raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`. |
| [raw\_backtrace\_to\_string](printexc#VALraw_backtrace_to_string) [[Printexc](printexc)] | Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses. |
| [raw\_field](obj#VALraw_field) [[Obj](obj)] | |
| [rcontains\_from](string#VALrcontains_from) [[String](string)] | `rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. |
| [rcontains\_from](stringlabels#VALrcontains_from) [[StringLabels](stringlabels)] | `rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. |
| [rcontains\_from](byteslabels#VALrcontains_from) [[BytesLabels](byteslabels)] | `rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. |
| [rcontains\_from](bytes#VALrcontains_from) [[Bytes](bytes)] | `rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. |
| [reachable\_words](obj#VALreachable_words) [[Obj](obj)] | Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. |
| [read](unixlabels#VALread) [[UnixLabels](unixlabels)] | `read fd ~buf ~pos ~len` reads `len` bytes from descriptor `fd`, storing them in byte sequence `buf`, starting at position `pos` in `buf`. |
| [read](unix#VALread) [[Unix](unix)] | `read fd buf pos len` reads `len` bytes from descriptor `fd`, storing them in byte sequence `buf`, starting at position `pos` in `buf`. |
| [read\_arg](arg#VALread_arg) [[Arg](arg)] | `Arg.read_arg file` reads newline-terminated command line arguments from file `file`. |
| [read\_arg0](arg#VALread_arg0) [[Arg](arg)] | Identical to [`Arg.read_arg`](arg#VALread_arg) but assumes null character terminated command line arguments. |
| [read\_float](stdlib#VALread_float) [[Stdlib](stdlib)] | Same as [`read_float_opt`](stdlib#VALread_float_opt), but raise `Failure "float\_of\_string"` instead of returning `None`. |
| [read\_float\_opt](stdlib#VALread_float_opt) [[Stdlib](stdlib)] | Flush standard output, then read one line from standard input and convert it to a floating-point number. |
| [read\_int](stdlib#VALread_int) [[Stdlib](stdlib)] | Same as [`read_int_opt`](stdlib#VALread_int_opt), but raise `Failure "int\_of\_string"` instead of returning `None`. |
| [read\_int\_opt](stdlib#VALread_int_opt) [[Stdlib](stdlib)] | Flush standard output, then read one line from standard input and convert it to an integer. |
| [read\_line](stdlib#VALread_line) [[Stdlib](stdlib)] | Flush standard output, then read characters from standard input until a newline character is encountered. |
| [read\_poll](runtime_events#VALread_poll) [[Runtime\_events](runtime_events)] | `read_poll cursor callbacks max_option` calls the corresponding functions on `callbacks` for up to `max_option` events read off `cursor`'s runtime\_events and returns the number of events read. |
| [readdir](unixlabels#VALreaddir) [[UnixLabels](unixlabels)] | Return the next entry in a directory. |
| [readdir](unix#VALreaddir) [[Unix](unix)] | Return the next entry in a directory. |
| [readdir](sys#VALreaddir) [[Sys](sys)] | Return the names of all files present in the given directory. |
| [readlink](unixlabels#VALreadlink) [[UnixLabels](unixlabels)] | Read the contents of a symbolic link. |
| [readlink](unix#VALreadlink) [[Unix](unix)] | Read the contents of a symbolic link. |
| [really\_input](in_channel#VALreally_input) [[In\_channel](in_channel)] | `really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. |
| [really\_input](stdlib#VALreally_input) [[Stdlib](stdlib)] | `really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. |
| [really\_input\_string](in_channel#VALreally_input_string) [[In\_channel](in_channel)] | `really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. |
| [really\_input\_string](stdlib#VALreally_input_string) [[Stdlib](stdlib)] | `really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. |
| [realpath](unixlabels#VALrealpath) [[UnixLabels](unixlabels)] | `realpath p` is an absolute pathname for `p` obtained by resolving all extra `/` characters, relative path segments and symbolic links. |
| [realpath](unix#VALrealpath) [[Unix](unix)] | `realpath p` is an absolute pathname for `p` obtained by resolving all extra `/` characters, relative path segments and symbolic links. |
| [rebuild](morelabels.hashtbl#VALrebuild) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Return a copy of the given hashtable. |
| [rebuild](hashtbl#VALrebuild) [[Hashtbl](hashtbl)] | Return a copy of the given hashtable. |
| [recast](camlinternalformat#VALrecast) [[CamlinternalFormat](camlinternalformat)] | |
| [receive](event#VALreceive) [[Event](event)] | `receive ch` returns the event consisting in receiving a value from the channel `ch`. |
| [recommended\_domain\_count](domain#VALrecommended_domain_count) [[Domain](domain)] | The recommended maximum number of domains which should be running simultaneously (including domains already running). |
| [record\_backtrace](printexc#VALrecord_backtrace) [[Printexc](printexc)] | `Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). |
| [recv](unixlabels#VALrecv) [[UnixLabels](unixlabels)] | Receive data from a connected socket. |
| [recv](unix#VALrecv) [[Unix](unix)] | Receive data from a connected socket. |
| [recvfrom](unixlabels#VALrecvfrom) [[UnixLabels](unixlabels)] | Receive data from an unconnected socket. |
| [recvfrom](unix#VALrecvfrom) [[Unix](unix)] | Receive data from an unconnected socket. |
| [ref](stdlib#VALref) [[Stdlib](stdlib)] | Return a fresh reference containing the given value. |
| [regexp](str#VALregexp) [[Str](str)] | Compile a regular expression. |
| [regexp\_case\_fold](str#VALregexp_case_fold) [[Str](str)] | Same as `regexp`, but the compiled expression will match text in a case-insensitive way: uppercase and lowercase letters will be considered equivalent. |
| [regexp\_string](str#VALregexp_string) [[Str](str)] | `Str.regexp_string s` returns a regular expression that matches exactly `s` and nothing else. |
| [regexp\_string\_case\_fold](str#VALregexp_string_case_fold) [[Str](str)] | `Str.regexp_string_case_fold` is similar to [`Str.regexp_string`](str#VALregexp_string), but the regexp matches in a case-insensitive way. |
| [register](callback#VALregister) [[Callback](callback)] | `Callback.register n v` registers the value `v` under the name `n`. |
| [register\_exception](callback#VALregister_exception) [[Callback](callback)] | `Callback.register_exception n exn` registers the exception contained in the exception value `exn` under the name `n`. |
| [register\_printer](printexc#VALregister_printer) [[Printexc](printexc)] | `Printexc.register_printer fn` registers `fn` as an exception printer. |
| [release](semaphore.binary#VALrelease) [[Semaphore.Binary](semaphore.binary)] | `release s` sets the value of semaphore `s` to 1, putting it in the "available" state. |
| [release](semaphore.counting#VALrelease) [[Semaphore.Counting](semaphore.counting)] | `release s` increments the value of semaphore `s`. |
| [rem](nativeint#VALrem) [[Nativeint](nativeint)] | Integer remainder. |
| [rem](int64#VALrem) [[Int64](int64)] | Integer remainder. |
| [rem](int32#VALrem) [[Int32](int32)] | Integer remainder. |
| [rem](int#VALrem) [[Int](int)] | `rem x y` is the remainder `x mod y`. |
| [rem](float#VALrem) [[Float](float)] | `rem a b` returns the remainder of `a` with respect to `b`. |
| [remove](weak.s#VALremove) [[Weak.S](weak.s)] | `remove t x` removes from `t` one instance of `x`. |
| [remove](sys#VALremove) [[Sys](sys)] | Remove the given file name from the file system. |
| [remove](set.s#VALremove) [[Set.S](set.s)] | `remove x s` returns a set containing all elements of `s`, except `x`. |
| [remove](morelabels.set.s#VALremove) [[MoreLabels.Set.S](morelabels.set.s)] | `remove x s` returns a set containing all elements of `s`, except `x`. |
| [remove](morelabels.map.s#VALremove) [[MoreLabels.Map.S](morelabels.map.s)] | `remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. |
| [remove](morelabels.hashtbl.seededs#VALremove) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [remove](morelabels.hashtbl.s#VALremove) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [remove](morelabels.hashtbl#VALremove) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. |
| [remove](map.s#VALremove) [[Map.S](map.s)] | `remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. |
| [remove](hashtbl.seededs#VALremove) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [remove](hashtbl.s#VALremove) [[Hashtbl.S](hashtbl.s)] | |
| [remove](hashtbl#VALremove) [[Hashtbl](hashtbl)] | `Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. |
| [remove](ephemeron.kn.bucket#VALremove) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | `remove b k` removes from `b` the most-recently added ephemeron with keys `k`, or does nothing if there is no such ephemeron. |
| [remove](ephemeron.k2.bucket#VALremove) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | `remove b k1 k2` removes from `b` the most-recently added ephemeron with keys `k1` and `k2`, or does nothing if there is no such ephemeron. |
| [remove](ephemeron.k1.bucket#VALremove) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | `remove b k` removes from `b` the most-recently added ephemeron with key `k`, or does nothing if there is no such ephemeron. |
| [remove](ephemeron.seededs#VALremove) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [remove](ephemeron.s#VALremove) [[Ephemeron.S](ephemeron.s)] | |
| [remove\_assoc](listlabels#VALremove_assoc) [[ListLabels](listlabels)] | `remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. |
| [remove\_assoc](list#VALremove_assoc) [[List](list)] | `remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. |
| [remove\_assq](listlabels#VALremove_assq) [[ListLabels](listlabels)] | Same as [`ListLabels.remove_assoc`](listlabels#VALremove_assoc), but uses physical equality instead of structural equality to compare keys. |
| [remove\_assq](list#VALremove_assq) [[List](list)] | Same as [`List.remove_assoc`](list#VALremove_assoc), but uses physical equality instead of structural equality to compare keys. |
| [remove\_extension](filename#VALremove_extension) [[Filename](filename)] | Return the given file name without its extension, as defined in [`Filename.extension`](filename#VALextension). |
| [rename](unixlabels#VALrename) [[UnixLabels](unixlabels)] | `rename ~src ~dst` changes the name of a file from `src` to `dst`, moving it between directories if needed. |
| [rename](unix#VALrename) [[Unix](unix)] | `rename src dst` changes the name of a file from `src` to `dst`, moving it between directories if needed. |
| [rename](sys#VALrename) [[Sys](sys)] | Rename a file. |
| [rep](uchar#VALrep) [[Uchar](uchar)] | `rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character. |
| [repeat](seq#VALrepeat) [[Seq](seq)] | `repeat x` is the infinite sequence where the element `x` is repeated indefinitely. |
| [replace](morelabels.hashtbl.seededs#VALreplace) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [replace](morelabels.hashtbl.s#VALreplace) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [replace](morelabels.hashtbl#VALreplace) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. |
| [replace](hashtbl.seededs#VALreplace) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [replace](hashtbl.s#VALreplace) [[Hashtbl.S](hashtbl.s)] | |
| [replace](hashtbl#VALreplace) [[Hashtbl](hashtbl)] | `Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. |
| [replace](ephemeron.seededs#VALreplace) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [replace](ephemeron.s#VALreplace) [[Ephemeron.S](ephemeron.s)] | |
| [replace\_first](str#VALreplace_first) [[Str](str)] | Same as [`Str.global_replace`](str#VALglobal_replace), except that only the first substring matching the regular expression is replaced. |
| [replace\_matched](str#VALreplace_matched) [[Str](str)] | `replace_matched repl s` returns the replacement text `repl` in which `\1`, `\2`, etc. |
| [replace\_seq](morelabels.hashtbl.seededs#VALreplace_seq) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [replace\_seq](morelabels.hashtbl.s#VALreplace_seq) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [replace\_seq](morelabels.hashtbl#VALreplace_seq) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Add the given bindings to the table, using [`MoreLabels.Hashtbl.replace`](morelabels.hashtbl#VALreplace) |
| [replace\_seq](hashtbl.seededs#VALreplace_seq) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [replace\_seq](hashtbl.s#VALreplace_seq) [[Hashtbl.S](hashtbl.s)] | |
| [replace\_seq](hashtbl#VALreplace_seq) [[Hashtbl](hashtbl)] | Add the given bindings to the table, using [`Hashtbl.replace`](hashtbl#VALreplace) |
| [replace\_seq](ephemeron.seededs#VALreplace_seq) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [replace\_seq](ephemeron.s#VALreplace_seq) [[Ephemeron.S](ephemeron.s)] | |
| [repr](sys.immediate64.make#VALrepr) [[Sys.Immediate64.Make](sys.immediate64.make)] | |
| [repr](obj#VALrepr) [[Obj](obj)] | |
| [reset](morelabels.hashtbl.seededs#VALreset) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [reset](morelabels.hashtbl.s#VALreset) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [reset](morelabels.hashtbl#VALreset) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Empty a hash table and shrink the size of the bucket table to its initial size. |
| [reset](hashtbl.seededs#VALreset) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [reset](hashtbl.s#VALreset) [[Hashtbl.S](hashtbl.s)] | |
| [reset](hashtbl#VALreset) [[Hashtbl](hashtbl)] | Empty a hash table and shrink the size of the bucket table to its initial size. |
| [reset](ephemeron.seededs#VALreset) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [reset](ephemeron.s#VALreset) [[Ephemeron.S](ephemeron.s)] | |
| [reset](buffer#VALreset) [[Buffer](buffer)] | Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](buffer#VALcreate) `n`. |
| [reshape](bigarray#VALreshape) [[Bigarray](bigarray)] | `reshape b [|d1;...;dN|]` converts the Bigarray `b` to a `N`-dimensional array of dimensions `d1`... |
| [reshape\_0](bigarray#VALreshape_0) [[Bigarray](bigarray)] | Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to zero-dimensional arrays. |
| [reshape\_1](bigarray#VALreshape_1) [[Bigarray](bigarray)] | Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to one-dimensional arrays. |
| [reshape\_2](bigarray#VALreshape_2) [[Bigarray](bigarray)] | Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to two-dimensional arrays. |
| [reshape\_3](bigarray#VALreshape_3) [[Bigarray](bigarray)] | Specialized version of [`Bigarray.reshape`](bigarray#VALreshape) for reshaping to three-dimensional arrays. |
| [resume](runtime_events#VALresume) [[Runtime\_events](runtime_events)] | `resume ()` will resume the collection of events in the runtime. |
| [return](seq#VALreturn) [[Seq](seq)] | `return x` is the sequence whose sole element is `x`. |
| [rev](listlabels#VALrev) [[ListLabels](listlabels)] | List reversal. |
| [rev](list#VALrev) [[List](list)] | List reversal. |
| [rev\_append](listlabels#VALrev_append) [[ListLabels](listlabels)] | `rev_append l1 l2` reverses `l1` and concatenates it with `l2`. |
| [rev\_append](list#VALrev_append) [[List](list)] | `rev_append l1 l2` reverses `l1` and concatenates it with `l2`. |
| [rev\_char\_set](camlinternalformat#VALrev_char_set) [[CamlinternalFormat](camlinternalformat)] | |
| [rev\_map](listlabels#VALrev_map) [[ListLabels](listlabels)] | `rev_map ~f l` gives the same result as [`ListLabels.rev`](listlabels#VALrev)`(`[`ListLabels.map`](listlabels#VALmap)`f l)`, but is tail-recursive and more efficient. |
| [rev\_map](list#VALrev_map) [[List](list)] | `rev_map f l` gives the same result as [`List.rev`](list#VALrev)`(`[`List.map`](list#VALmap)`f l)`, but is tail-recursive and more efficient. |
| [rev\_map2](listlabels#VALrev_map2) [[ListLabels](listlabels)] | `rev_map2 ~f l1 l2` gives the same result as [`ListLabels.rev`](listlabels#VALrev)`(`[`ListLabels.map2`](listlabels#VALmap2)`f l1 l2)`, but is tail-recursive and more efficient. |
| [rev\_map2](list#VALrev_map2) [[List](list)] | `rev_map2 f l1 l2` gives the same result as [`List.rev`](list#VALrev)`(`[`List.map2`](list#VALmap2)`f l1 l2)`, but is tail-recursive and more efficient. |
| [rewinddir](unixlabels#VALrewinddir) [[UnixLabels](unixlabels)] | Reposition the descriptor to the beginning of the directory |
| [rewinddir](unix#VALrewinddir) [[Unix](unix)] | Reposition the descriptor to the beginning of the directory |
| [rhs\_end](parsing#VALrhs_end) [[Parsing](parsing)] | See [`Parsing.rhs_start`](parsing#VALrhs_start). |
| [rhs\_end\_pos](parsing#VALrhs_end_pos) [[Parsing](parsing)] | Same as `rhs_end`, but return a `position` instead of an offset. |
| [rhs\_start](parsing#VALrhs_start) [[Parsing](parsing)] | Same as [`Parsing.symbol_start`](parsing#VALsymbol_start) and [`Parsing.symbol_end`](parsing#VALsymbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. |
| [rhs\_start\_pos](parsing#VALrhs_start_pos) [[Parsing](parsing)] | Same as `rhs_start`, but return a `position` instead of an offset. |
| [right](either#VALright) [[Either](either)] | `right v` is `Right v`. |
| [rindex](string#VALrindex) [[String](string)] | `rindex s c` is [`String.rindex_from`](string#VALrindex_from)`s (length s - 1) c`. |
| [rindex](stringlabels#VALrindex) [[StringLabels](stringlabels)] | `rindex s c` is [`String.rindex_from`](string#VALrindex_from)`s (length s - 1) c`. |
| [rindex](byteslabels#VALrindex) [[BytesLabels](byteslabels)] | `rindex s c` returns the index of the last occurrence of byte `c` in `s`. |
| [rindex](bytes#VALrindex) [[Bytes](bytes)] | `rindex s c` returns the index of the last occurrence of byte `c` in `s`. |
| [rindex\_from](string#VALrindex_from) [[String](string)] | `rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. |
| [rindex\_from](stringlabels#VALrindex_from) [[StringLabels](stringlabels)] | `rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. |
| [rindex\_from](byteslabels#VALrindex_from) [[BytesLabels](byteslabels)] | `rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. |
| [rindex\_from](bytes#VALrindex_from) [[Bytes](bytes)] | `rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. |
| [rindex\_from\_opt](string#VALrindex_from_opt) [[String](string)] | `rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). |
| [rindex\_from\_opt](stringlabels#VALrindex_from_opt) [[StringLabels](stringlabels)] | `rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). |
| [rindex\_from\_opt](byteslabels#VALrindex_from_opt) [[BytesLabels](byteslabels)] | `rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. |
| [rindex\_from\_opt](bytes#VALrindex_from_opt) [[Bytes](bytes)] | `rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. |
| [rindex\_opt](string#VALrindex_opt) [[String](string)] | `rindex_opt s c` is [`String.rindex_from_opt`](string#VALrindex_from_opt)`s (length s - 1) c`. |
| [rindex\_opt](stringlabels#VALrindex_opt) [[StringLabels](stringlabels)] | `rindex_opt s c` is [`String.rindex_from_opt`](string#VALrindex_from_opt)`s (length s - 1) c`. |
| [rindex\_opt](byteslabels#VALrindex_opt) [[BytesLabels](byteslabels)] | `rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. |
| [rindex\_opt](bytes#VALrindex_opt) [[Bytes](bytes)] | `rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. |
| [rmdir](unixlabels#VALrmdir) [[UnixLabels](unixlabels)] | Remove an empty directory. |
| [rmdir](unix#VALrmdir) [[Unix](unix)] | Remove an empty directory. |
| [rmdir](sys#VALrmdir) [[Sys](sys)] | Remove an empty directory. |
| [round](float#VALround) [[Float](float)] | `round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. |
| [run\_initializers](camlinternaloo#VALrun_initializers) [[CamlinternalOO](camlinternaloo)] | |
| [run\_initializers\_opt](camlinternaloo#VALrun_initializers_opt) [[CamlinternalOO](camlinternaloo)] | |
| [runtime\_counter\_name](runtime_events#VALruntime_counter_name) [[Runtime\_events](runtime_events)] | Return a string representation of a given runtime counter type |
| [runtime\_parameters](sys#VALruntime_parameters) [[Sys](sys)] | Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable. |
| [runtime\_phase\_name](runtime_events#VALruntime_phase_name) [[Runtime\_events](runtime_events)] | Return a string representation of a given runtime phase event type |
| [runtime\_variant](sys#VALruntime_variant) [[Sys](sys)] | Return the name of the runtime variant the program is running on. |
| [runtime\_warnings\_enabled](sys#VALruntime_warnings_enabled) [[Sys](sys)] | Return whether runtime warnings are currently enabled. |
| S |
| [safe\_set\_geometry](format#VALsafe_set_geometry) [[Format](format)] | `pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`. |
| [scan](seq#VALscan) [[Seq](seq)] | If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on. |
| [scanf](scanf#VALscanf) [[Scanf](scanf)] | Same as [`Scanf.bscanf`](scanf#VALbscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](scanf.scanning#VALstdin) that is connected to [`stdin`](stdlib#VALstdin). |
| [scanf\_opt](scanf#VALscanf_opt) [[Scanf](scanf)] | Same as [`Scanf.scanf`](scanf#VALscanf), but returns `None` in case of scanning failure. |
| [search\_backward](str#VALsearch_backward) [[Str](str)] | `search_backward r s last` searches the string `s` for a substring matching the regular expression `r`. |
| [search\_forward](str#VALsearch_forward) [[Str](str)] | `search_forward r s start` searches the string `s` for a substring matching the regular expression `r`. |
| [seeded\_hash](string#VALseeded_hash) [[String](string)] | A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash). |
| [seeded\_hash](stringlabels#VALseeded_hash) [[StringLabels](stringlabels)] | A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash). |
| [seeded\_hash](morelabels.hashtbl.seededhashedtype#VALseeded_hash) [[MoreLabels.Hashtbl.SeededHashedType](morelabels.hashtbl.seededhashedtype)] | A seeded hashing function on keys. |
| [seeded\_hash](morelabels.hashtbl#VALseeded_hash) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | A variant of [`MoreLabels.Hashtbl.hash`](morelabels.hashtbl#VALhash) that is further parameterized by an integer seed. |
| [seeded\_hash](hashtbl.seededhashedtype#VALseeded_hash) [[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)] | A seeded hashing function on keys. |
| [seeded\_hash](hashtbl#VALseeded_hash) [[Hashtbl](hashtbl)] | A variant of [`Hashtbl.hash`](hashtbl#VALhash) that is further parameterized by an integer seed. |
| [seeded\_hash\_param](morelabels.hashtbl#VALseeded_hash_param) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | A variant of [`MoreLabels.Hashtbl.hash_param`](morelabels.hashtbl#VALhash_param) that is further parameterized by an integer seed. |
| [seeded\_hash\_param](hashtbl#VALseeded_hash_param) [[Hashtbl](hashtbl)] | A variant of [`Hashtbl.hash_param`](hashtbl#VALhash_param) that is further parameterized by an integer seed. |
| [seek](out_channel#VALseek) [[Out\_channel](out_channel)] | `seek chan pos` sets the current writing position to `pos` for channel `chan`. |
| [seek](in_channel#VALseek) [[In\_channel](in_channel)] | `seek chan pos` sets the current reading position to `pos` for channel `chan`. |
| [seek\_in](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html#VALseek_in) [[Stdlib.LargeFile](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html)] | |
| [seek\_in](stdlib#VALseek_in) [[Stdlib](stdlib)] | `seek_in chan pos` sets the current reading position to `pos` for channel `chan`. |
| [seek\_out](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html#VALseek_out) [[Stdlib.LargeFile](https://v2.ocaml.org/releases/5.0/htmlman/libref/Stdlib.LargeFile.html)] | |
| [seek\_out](stdlib#VALseek_out) [[Stdlib](stdlib)] | `seek_out chan pos` sets the current writing position to `pos` for channel `chan`. |
| [select](event#VALselect) [[Event](event)] | 'Synchronize' on an alternative of events. |
| [select](thread#VALselect) [[Thread](thread)] | Same function as [`Unix.select`](unix#VALselect).
|
| [select](unixlabels#VALselect) [[UnixLabels](unixlabels)] | Wait until some input/output operations become possible on some channels. |
| [select](unix#VALselect) [[Unix](unix)] | Wait until some input/output operations become possible on some channels. |
| [self](thread#VALself) [[Thread](thread)] | Return the handle for the thread currently executing. |
| [self](domain#VALself) [[Domain](domain)] | `self ()` is the identifier of the currently running domain |
| [self\_init](random#VALself_init) [[Random](random)] | Initialize the domain-local generator with a random seed chosen in a system-dependent way. |
| [send](event#VALsend) [[Event](event)] | `send ch v` returns the event consisting in sending the value `v` over the channel `ch`. |
| [send](unixlabels#VALsend) [[UnixLabels](unixlabels)] | Send data over a connected socket. |
| [send](unix#VALsend) [[Unix](unix)] | Send data over a connected socket. |
| [send](camlinternaloo#VALsend) [[CamlinternalOO](camlinternaloo)] | |
| [send\_substring](unixlabels#VALsend_substring) [[UnixLabels](unixlabels)] | Same as `send`, but take the data from a string instead of a byte sequence. |
| [send\_substring](unix#VALsend_substring) [[Unix](unix)] | Same as `send`, but take the data from a string instead of a byte sequence. |
| [sendcache](camlinternaloo#VALsendcache) [[CamlinternalOO](camlinternaloo)] | |
| [sendself](camlinternaloo#VALsendself) [[CamlinternalOO](camlinternaloo)] | |
| [sendto](unixlabels#VALsendto) [[UnixLabels](unixlabels)] | Send data over an unconnected socket. |
| [sendto](unix#VALsendto) [[Unix](unix)] | Send data over an unconnected socket. |
| [sendto\_substring](unixlabels#VALsendto_substring) [[UnixLabels](unixlabels)] | Same as `sendto`, but take the data from a string instead of a byte sequence. |
| [sendto\_substring](unix#VALsendto_substring) [[Unix](unix)] | Same as `sendto`, but take the data from a string instead of a byte sequence. |
| [set](weak#VALset) [[Weak](weak)] | `Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty. |
| [set](gc#VALset) [[Gc](gc)] | `set r` changes the GC parameters according to the `control` record `r`. |
| [set](float.arraylabels#VALset) [[Float.ArrayLabels](float.arraylabels)] | `set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. |
| [set](float.array#VALset) [[Float.Array](float.array)] | `set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. |
| [set](domain.dls#VALset) [[Domain.DLS](domain.dls)] | `set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. |
| [set](byteslabels#VALset) [[BytesLabels](byteslabels)] | `set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. |
| [set](bytes#VALset) [[Bytes](bytes)] | `set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. |
| [set](bigarray.array3#VALset) [[Bigarray.Array3](bigarray.array3)] | `Array3.set a x y v`, or alternatively `a.{x,y,z} <- v`, stores the value `v` at coordinates (`x`, `y`, `z`) in `a`. |
| [set](bigarray.array2#VALset) [[Bigarray.Array2](bigarray.array2)] | `Array2.set a x y v`, or alternatively `a.{x,y} <- v`, stores the value `v` at coordinates (`x`, `y`) in `a`. |
| [set](bigarray.array1#VALset) [[Bigarray.Array1](bigarray.array1)] | `Array1.set a x v`, also written `a.{x} <- v`, stores the value `v` at index `x` in `a`. |
| [set](bigarray.array0#VALset) [[Bigarray.Array0](bigarray.array0)] | `Array0.set a x v` stores the value `v` in `a`. |
| [set](bigarray.genarray#VALset) [[Bigarray.Genarray](bigarray.genarray)] | Assign an element of a generic Bigarray. |
| [set](atomic#VALset) [[Atomic](atomic)] | Set a new value for the atomic reference. |
| [set](arraylabels#VALset) [[ArrayLabels](arraylabels)] | `set a n x` modifies array `a` in place, replacing element number `n` with `x`. |
| [set](array#VALset) [[Array](array)] | `set a n x` modifies array `a` in place, replacing element number `n` with `x`. |
| [set\_allowed\_units](dynlink#VALset_allowed_units) [[Dynlink](dynlink)] | Set the list of compilation units that may be referenced from units that are dynamically loaded in the future to be exactly the given value. |
| [set\_binary\_mode](out_channel#VALset_binary_mode) [[Out\_channel](out_channel)] | `set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output. |
| [set\_binary\_mode](in_channel#VALset_binary_mode) [[In\_channel](in_channel)] | `set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input. |
| [set\_binary\_mode\_in](stdlib#VALset_binary_mode_in) [[Stdlib](stdlib)] | `set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. |
| [set\_binary\_mode\_out](stdlib#VALset_binary_mode_out) [[Stdlib](stdlib)] | `set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. |
| [set\_buffered](out_channel#VALset_buffered) [[Out\_channel](out_channel)] | `set_buffered oc true` sets the channel `oc` to *buffered* mode. |
| [set\_close\_on\_exec](unixlabels#VALset_close_on_exec) [[UnixLabels](unixlabels)] | Set the ``close-on-exec'' flag on the given descriptor. |
| [set\_close\_on\_exec](unix#VALset_close_on_exec) [[Unix](unix)] | Set the ``close-on-exec'' flag on the given descriptor. |
| [set\_data](obj.ephemeron#VALset_data) [[Obj.Ephemeron](obj.ephemeron)] | |
| [set\_double\_field](obj#VALset_double_field) [[Obj](obj)] | |
| [set\_ellipsis\_text](format#VALset_ellipsis_text) [[Format](format)] | Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default). |
| [set\_field](obj#VALset_field) [[Obj](obj)] | When using flambda: |
| [set\_filename](lexing#VALset_filename) [[Lexing](lexing)] | Set filename in the initial tracked position to `file` in `lexbuf`. |
| [set\_formatter\_out\_channel](format#VALset_formatter_out_channel) [[Format](format)] | Redirect the standard pretty-printer output to the given channel. |
| [set\_formatter\_out\_functions](format#VALset_formatter_out_functions) [[Format](format)] | `pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`, |
| [set\_formatter\_output\_functions](format#VALset_formatter_output_functions) [[Format](format)] | `pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`. |
| [set\_formatter\_stag\_functions](format#VALset_formatter_stag_functions) [[Format](format)] | `pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`. |
| [set\_geometry](format#VALset_geometry) [[Format](format)] | |
| [set\_int16\_be](byteslabels#VALset_int16_be) [[BytesLabels](byteslabels)] | `set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. |
| [set\_int16\_be](bytes#VALset_int16_be) [[Bytes](bytes)] | `set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. |
| [set\_int16\_le](byteslabels#VALset_int16_le) [[BytesLabels](byteslabels)] | `set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. |
| [set\_int16\_le](bytes#VALset_int16_le) [[Bytes](bytes)] | `set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. |
| [set\_int16\_ne](byteslabels#VALset_int16_ne) [[BytesLabels](byteslabels)] | `set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. |
| [set\_int16\_ne](bytes#VALset_int16_ne) [[Bytes](bytes)] | `set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. |
| [set\_int32\_be](byteslabels#VALset_int32_be) [[BytesLabels](byteslabels)] | `set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. |
| [set\_int32\_be](bytes#VALset_int32_be) [[Bytes](bytes)] | `set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. |
| [set\_int32\_le](byteslabels#VALset_int32_le) [[BytesLabels](byteslabels)] | `set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. |
| [set\_int32\_le](bytes#VALset_int32_le) [[Bytes](bytes)] | `set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. |
| [set\_int32\_ne](byteslabels#VALset_int32_ne) [[BytesLabels](byteslabels)] | `set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. |
| [set\_int32\_ne](bytes#VALset_int32_ne) [[Bytes](bytes)] | `set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. |
| [set\_int64\_be](byteslabels#VALset_int64_be) [[BytesLabels](byteslabels)] | `set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. |
| [set\_int64\_be](bytes#VALset_int64_be) [[Bytes](bytes)] | `set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. |
| [set\_int64\_le](byteslabels#VALset_int64_le) [[BytesLabels](byteslabels)] | `set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. |
| [set\_int64\_le](bytes#VALset_int64_le) [[Bytes](bytes)] | `set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. |
| [set\_int64\_ne](byteslabels#VALset_int64_ne) [[BytesLabels](byteslabels)] | `set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. |
| [set\_int64\_ne](bytes#VALset_int64_ne) [[Bytes](bytes)] | `set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. |
| [set\_int8](byteslabels#VALset_int8) [[BytesLabels](byteslabels)] | `set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. |
| [set\_int8](bytes#VALset_int8) [[Bytes](bytes)] | `set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. |
| [set\_key](obj.ephemeron#VALset_key) [[Obj.Ephemeron](obj.ephemeron)] | |
| [set\_margin](format#VALset_margin) [[Format](format)] | `pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. |
| [set\_mark\_tags](format#VALset_mark_tags) [[Format](format)] | `pp_set_mark_tags ppf b` turns on or off the tag-marking operations. |
| [set\_max\_boxes](format#VALset_max_boxes) [[Format](format)] | `pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open. |
| [set\_max\_indent](format#VALset_max_indent) [[Format](format)] | `pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. |
| [set\_method](camlinternaloo#VALset_method) [[CamlinternalOO](camlinternaloo)] | |
| [set\_methods](camlinternaloo#VALset_methods) [[CamlinternalOO](camlinternaloo)] | |
| [set\_nonblock](unixlabels#VALset_nonblock) [[UnixLabels](unixlabels)] | Set the ``non-blocking'' flag on the given descriptor. |
| [set\_nonblock](unix#VALset_nonblock) [[Unix](unix)] | Set the ``non-blocking'' flag on the given descriptor. |
| [set\_position](lexing#VALset_position) [[Lexing](lexing)] | Set the initial tracked input position for `lexbuf` to a custom value. |
| [set\_print\_tags](format#VALset_print_tags) [[Format](format)] | `pp_set_print_tags ppf b` turns on or off the tag-printing operations. |
| [set\_raw\_field](obj#VALset_raw_field) [[Obj](obj)] | |
| [set\_signal](sys#VALset_signal) [[Sys](sys)] | Same as [`Sys.signal`](sys#VALsignal) but return value is ignored. |
| [set\_state](random#VALset_state) [[Random](random)] | `set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. |
| [set\_tab](format#VALset_tab) [[Format](format)] | Sets a tabulation marker at current insertion point. |
| [set\_tags](format#VALset_tags) [[Format](format)] | `pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off). |
| [set\_temp\_dir\_name](filename#VALset_temp_dir_name) [[Filename](filename)] | Change the temporary directory returned by [`Filename.get_temp_dir_name`](filename#VALget_temp_dir_name) and used by [`Filename.temp_file`](filename#VALtemp_file) and [`Filename.open_temp_file`](filename#VALopen_temp_file). |
| [set\_trace](parsing#VALset_trace) [[Parsing](parsing)] | Control debugging support for `ocamlyacc`-generated parsers. |
| [set\_uint16\_be](byteslabels#VALset_uint16_be) [[BytesLabels](byteslabels)] | `set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. |
| [set\_uint16\_be](bytes#VALset_uint16_be) [[Bytes](bytes)] | `set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. |
| [set\_uint16\_le](byteslabels#VALset_uint16_le) [[BytesLabels](byteslabels)] | `set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. |
| [set\_uint16\_le](bytes#VALset_uint16_le) [[Bytes](bytes)] | `set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. |
| [set\_uint16\_ne](byteslabels#VALset_uint16_ne) [[BytesLabels](byteslabels)] | `set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. |
| [set\_uint16\_ne](bytes#VALset_uint16_ne) [[Bytes](bytes)] | `set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. |
| [set\_uint8](byteslabels#VALset_uint8) [[BytesLabels](byteslabels)] | `set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. |
| [set\_uint8](bytes#VALset_uint8) [[Bytes](bytes)] | `set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. |
| [set\_uncaught\_exception\_handler](thread#VALset_uncaught_exception_handler) [[Thread](thread)] | `Thread.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. |
| [set\_uncaught\_exception\_handler](printexc#VALset_uncaught_exception_handler) [[Printexc](printexc)] | `Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. |
| [set\_utf\_16be\_uchar](byteslabels#VALset_utf_16be_uchar) [[BytesLabels](byteslabels)] | `set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. |
| [set\_utf\_16be\_uchar](bytes#VALset_utf_16be_uchar) [[Bytes](bytes)] | `set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. |
| [set\_utf\_16le\_uchar](byteslabels#VALset_utf_16le_uchar) [[BytesLabels](byteslabels)] | `set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. |
| [set\_utf\_16le\_uchar](bytes#VALset_utf_16le_uchar) [[Bytes](bytes)] | `set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. |
| [set\_utf\_8\_uchar](byteslabels#VALset_utf_8_uchar) [[BytesLabels](byteslabels)] | `set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. |
| [set\_utf\_8\_uchar](bytes#VALset_utf_8_uchar) [[Bytes](bytes)] | `set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. |
| [setgid](unixlabels#VALsetgid) [[UnixLabels](unixlabels)] | Set the real group id and effective group id for the process. |
| [setgid](unix#VALsetgid) [[Unix](unix)] | Set the real group id and effective group id for the process. |
| [setgroups](unixlabels#VALsetgroups) [[UnixLabels](unixlabels)] | `setgroups groups` sets the supplementary group IDs for the calling process. |
| [setgroups](unix#VALsetgroups) [[Unix](unix)] | `setgroups groups` sets the supplementary group IDs for the calling process. |
| [setitimer](unixlabels#VALsetitimer) [[UnixLabels](unixlabels)] | `setitimer t s` sets the interval timer `t` and returns its previous status. |
| [setitimer](unix#VALsetitimer) [[Unix](unix)] | `setitimer t s` sets the interval timer `t` and returns its previous status. |
| [setsid](unixlabels#VALsetsid) [[UnixLabels](unixlabels)] | Put the calling process in a new session and detach it from its controlling terminal. |
| [setsid](unix#VALsetsid) [[Unix](unix)] | Put the calling process in a new session and detach it from its controlling terminal. |
| [setsockopt](unixlabels#VALsetsockopt) [[UnixLabels](unixlabels)] | Set or clear a boolean-valued option in the given socket. |
| [setsockopt](unix#VALsetsockopt) [[Unix](unix)] | Set or clear a boolean-valued option in the given socket. |
| [setsockopt\_float](unixlabels#VALsetsockopt_float) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt) for a socket option whose value is a floating-point number. |
| [setsockopt\_float](unix#VALsetsockopt_float) [[Unix](unix)] | Same as [`Unix.setsockopt`](unix#VALsetsockopt) for a socket option whose value is a floating-point number. |
| [setsockopt\_int](unixlabels#VALsetsockopt_int) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt) for an integer-valued socket option. |
| [setsockopt\_int](unix#VALsetsockopt_int) [[Unix](unix)] | Same as [`Unix.setsockopt`](unix#VALsetsockopt) for an integer-valued socket option. |
| [setsockopt\_optint](unixlabels#VALsetsockopt_optint) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt) for a socket option whose value is an `int option`. |
| [setsockopt\_optint](unix#VALsetsockopt_optint) [[Unix](unix)] | Same as [`Unix.setsockopt`](unix#VALsetsockopt) for a socket option whose value is an `int option`. |
| [setuid](unixlabels#VALsetuid) [[UnixLabels](unixlabels)] | Set the real user id and effective user id for the process. |
| [setuid](unix#VALsetuid) [[Unix](unix)] | Set the real user id and effective user id for the process. |
| [shift\_left](nativeint#VALshift_left) [[Nativeint](nativeint)] | `Nativeint.shift_left x y` shifts `x` to the left by `y` bits. |
| [shift\_left](int64#VALshift_left) [[Int64](int64)] | `Int64.shift_left x y` shifts `x` to the left by `y` bits. |
| [shift\_left](int32#VALshift_left) [[Int32](int32)] | `Int32.shift_left x y` shifts `x` to the left by `y` bits. |
| [shift\_left](int#VALshift_left) [[Int](int)] | `shift_left x n` shifts `x` to the left by `n` bits. |
| [shift\_right](nativeint#VALshift_right) [[Nativeint](nativeint)] | `Nativeint.shift_right x y` shifts `x` to the right by `y` bits. |
| [shift\_right](int64#VALshift_right) [[Int64](int64)] | `Int64.shift_right x y` shifts `x` to the right by `y` bits. |
| [shift\_right](int32#VALshift_right) [[Int32](int32)] | `Int32.shift_right x y` shifts `x` to the right by `y` bits. |
| [shift\_right](int#VALshift_right) [[Int](int)] | `shift_right x n` shifts `x` to the right by `n` bits. |
| [shift\_right\_logical](nativeint#VALshift_right_logical) [[Nativeint](nativeint)] | `Nativeint.shift_right_logical x y` shifts `x` to the right by `y` bits. |
| [shift\_right\_logical](int64#VALshift_right_logical) [[Int64](int64)] | `Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. |
| [shift\_right\_logical](int32#VALshift_right_logical) [[Int32](int32)] | `Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. |
| [shift\_right\_logical](int#VALshift_right_logical) [[Int](int)] | `shift_right x n` shifts `x` to the right by `n` bits. |
| [shutdown](unixlabels#VALshutdown) [[UnixLabels](unixlabels)] | Shutdown a socket connection. |
| [shutdown](unix#VALshutdown) [[Unix](unix)] | Shutdown a socket connection. |
| [shutdown\_connection](unixlabels#VALshutdown_connection) [[UnixLabels](unixlabels)] | ``Shut down'' a connection established with [`UnixLabels.open_connection`](unixlabels#VALopen_connection); that is, transmit an end-of-file condition to the server reading on the other side of the connection. |
| [shutdown\_connection](unix#VALshutdown_connection) [[Unix](unix)] | ``Shut down'' a connection established with [`Unix.open_connection`](unix#VALopen_connection); that is, transmit an end-of-file condition to the server reading on the other side of the connection. |
| [sigabrt](sys#VALsigabrt) [[Sys](sys)] | Abnormal termination |
| [sigalrm](sys#VALsigalrm) [[Sys](sys)] | Timeout |
| [sigbus](sys#VALsigbus) [[Sys](sys)] | Bus error |
| [sigchld](sys#VALsigchld) [[Sys](sys)] | Child process terminated |
| [sigcont](sys#VALsigcont) [[Sys](sys)] | Continue |
| [sigfpe](sys#VALsigfpe) [[Sys](sys)] | Arithmetic exception |
| [sighup](sys#VALsighup) [[Sys](sys)] | Hangup on controlling terminal |
| [sigill](sys#VALsigill) [[Sys](sys)] | Invalid hardware instruction |
| [sigint](sys#VALsigint) [[Sys](sys)] | Interactive interrupt (ctrl-C) |
| [sigkill](sys#VALsigkill) [[Sys](sys)] | Termination (cannot be ignored) |
| [sigmask](thread#VALsigmask) [[Thread](thread)] | `sigmask cmd sigs` changes the set of blocked signals for the calling thread. |
| [sign\_bit](float#VALsign_bit) [[Float](float)] | `sign_bit x` is `true` if and only if the sign bit of `x` is set. |
| [signal](sys#VALsignal) [[Sys](sys)] | Set the behavior of the system on receipt of a given signal. |
| [signal](condition#VALsignal) [[Condition](condition)] | `signal c` wakes up one of the threads waiting on the condition variable `c`, if there is one. |
| [sigpending](unixlabels#VALsigpending) [[UnixLabels](unixlabels)] | Return the set of blocked signals that are currently pending. |
| [sigpending](unix#VALsigpending) [[Unix](unix)] | Return the set of blocked signals that are currently pending. |
| [sigpipe](sys#VALsigpipe) [[Sys](sys)] | Broken pipe |
| [sigpoll](sys#VALsigpoll) [[Sys](sys)] | Pollable event |
| [sigprocmask](unixlabels#VALsigprocmask) [[UnixLabels](unixlabels)] | `sigprocmask ~mode sigs` changes the set of blocked signals. |
| [sigprocmask](unix#VALsigprocmask) [[Unix](unix)] | `sigprocmask mode sigs` changes the set of blocked signals. |
| [sigprof](sys#VALsigprof) [[Sys](sys)] | Profiling interrupt |
| [sigquit](sys#VALsigquit) [[Sys](sys)] | Interactive termination |
| [sigsegv](sys#VALsigsegv) [[Sys](sys)] | Invalid memory reference |
| [sigstop](sys#VALsigstop) [[Sys](sys)] | Stop |
| [sigsuspend](unixlabels#VALsigsuspend) [[UnixLabels](unixlabels)] | `sigsuspend sigs` atomically sets the blocked signals to `sigs` and waits for a non-ignored, non-blocked signal to be delivered. |
| [sigsuspend](unix#VALsigsuspend) [[Unix](unix)] | `sigsuspend sigs` atomically sets the blocked signals to `sigs` and waits for a non-ignored, non-blocked signal to be delivered. |
| [sigsys](sys#VALsigsys) [[Sys](sys)] | Bad argument to routine |
| [sigterm](sys#VALsigterm) [[Sys](sys)] | Termination |
| [sigtrap](sys#VALsigtrap) [[Sys](sys)] | Trace/breakpoint trap |
| [sigtstp](sys#VALsigtstp) [[Sys](sys)] | Interactive stop |
| [sigttin](sys#VALsigttin) [[Sys](sys)] | Terminal read from background process |
| [sigttou](sys#VALsigttou) [[Sys](sys)] | Terminal write from background process |
| [sigurg](sys#VALsigurg) [[Sys](sys)] | Urgent condition on socket |
| [sigusr1](sys#VALsigusr1) [[Sys](sys)] | Application-defined signal 1 |
| [sigusr2](sys#VALsigusr2) [[Sys](sys)] | Application-defined signal 2 |
| [sigvtalrm](sys#VALsigvtalrm) [[Sys](sys)] | Timeout in virtual time |
| [sigxcpu](sys#VALsigxcpu) [[Sys](sys)] | Timeout in cpu time |
| [sigxfsz](sys#VALsigxfsz) [[Sys](sys)] | File size limit exceeded |
| [sin](float#VALsin) [[Float](float)] | Sine. |
| [sin](stdlib#VALsin) [[Stdlib](stdlib)] | Sine. |
| [single\_write](unixlabels#VALsingle_write) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.write`](unixlabels#VALwrite), but attempts to write only once. |
| [single\_write](unix#VALsingle_write) [[Unix](unix)] | Same as [`Unix.write`](unix#VALwrite), but attempts to write only once. |
| [single\_write\_substring](unixlabels#VALsingle_write_substring) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.single_write`](unixlabels#VALsingle_write), but take the data from a string instead of a byte sequence. |
| [single\_write\_substring](unix#VALsingle_write_substring) [[Unix](unix)] | Same as [`Unix.single_write`](unix#VALsingle_write), but take the data from a string instead of a byte sequence. |
| [singleton](set.s#VALsingleton) [[Set.S](set.s)] | `singleton x` returns the one-element set containing only `x`. |
| [singleton](morelabels.set.s#VALsingleton) [[MoreLabels.Set.S](morelabels.set.s)] | `singleton x` returns the one-element set containing only `x`. |
| [singleton](morelabels.map.s#VALsingleton) [[MoreLabels.Map.S](morelabels.map.s)] | `singleton x y` returns the one-element map that contains a binding `y` for `x`. |
| [singleton](map.s#VALsingleton) [[Map.S](map.s)] | `singleton x y` returns the one-element map that contains a binding `y` for `x`. |
| [sinh](float#VALsinh) [[Float](float)] | Hyperbolic sine. |
| [sinh](stdlib#VALsinh) [[Stdlib](stdlib)] | Hyperbolic sine. |
| [size](obj#VALsize) [[Obj](obj)] | |
| [size](nativeint#VALsize) [[Nativeint](nativeint)] | The size in bits of a native integer. |
| [size\_in\_bytes](bigarray.array3#VALsize_in_bytes) [[Bigarray.Array3](bigarray.array3)] | `size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes). |
| [size\_in\_bytes](bigarray.array2#VALsize_in_bytes) [[Bigarray.Array2](bigarray.array2)] | `size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes). |
| [size\_in\_bytes](bigarray.array1#VALsize_in_bytes) [[Bigarray.Array1](bigarray.array1)] | `size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes). |
| [size\_in\_bytes](bigarray.array0#VALsize_in_bytes) [[Bigarray.Array0](bigarray.array0)] | `size_in_bytes a` is `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes). |
| [size\_in\_bytes](bigarray.genarray#VALsize_in_bytes) [[Bigarray.Genarray](bigarray.genarray)] | `size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes). |
| [sleep](unixlabels#VALsleep) [[UnixLabels](unixlabels)] | Stop execution for the given number of seconds. |
| [sleep](unix#VALsleep) [[Unix](unix)] | Stop execution for the given number of seconds. |
| [sleepf](unixlabels#VALsleepf) [[UnixLabels](unixlabels)] | Stop execution for the given number of seconds. |
| [sleepf](unix#VALsleepf) [[Unix](unix)] | Stop execution for the given number of seconds. |
| [slice](bigarray.array1#VALslice) [[Bigarray.Array1](bigarray.array1)] | Extract a scalar (zero-dimensional slice) of the given one-dimensional Bigarray. |
| [slice\_left](bigarray.array2#VALslice_left) [[Bigarray.Array2](bigarray.array2)] | Extract a row (one-dimensional slice) of the given two-dimensional Bigarray. |
| [slice\_left](bigarray.genarray#VALslice_left) [[Bigarray.Genarray](bigarray.genarray)] | Extract a sub-array of lower dimension from the given Bigarray by fixing one or several of the first (left-most) coordinates. |
| [slice\_left\_1](bigarray.array3#VALslice_left_1) [[Bigarray.Array3](bigarray.array3)] | Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the first two coordinates. |
| [slice\_left\_2](bigarray.array3#VALslice_left_2) [[Bigarray.Array3](bigarray.array3)] | Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the first coordinate. |
| [slice\_right](bigarray.array2#VALslice_right) [[Bigarray.Array2](bigarray.array2)] | Extract a column (one-dimensional slice) of the given two-dimensional Bigarray. |
| [slice\_right](bigarray.genarray#VALslice_right) [[Bigarray.Genarray](bigarray.genarray)] | Extract a sub-array of lower dimension from the given Bigarray by fixing one or several of the last (right-most) coordinates. |
| [slice\_right\_1](bigarray.array3#VALslice_right_1) [[Bigarray.Array3](bigarray.array3)] | Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the last two coordinates. |
| [slice\_right\_2](bigarray.array3#VALslice_right_2) [[Bigarray.Array3](bigarray.array3)] | Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the last coordinate. |
| [snd](stdlib#VALsnd) [[Stdlib](stdlib)] | Return the second component of a pair. |
| [socket](unixlabels#VALsocket) [[UnixLabels](unixlabels)] | Create a new socket in the given domain, and with the given kind. |
| [socket](unix#VALsocket) [[Unix](unix)] | Create a new socket in the given domain, and with the given kind. |
| [socketpair](unixlabels#VALsocketpair) [[UnixLabels](unixlabels)] | Create a pair of unnamed sockets, connected together. |
| [socketpair](unix#VALsocketpair) [[Unix](unix)] | Create a pair of unnamed sockets, connected together. |
| [some](option#VALsome) [[Option](option)] | `some v` is `Some v`. |
| [sort](listlabels#VALsort) [[ListLabels](listlabels)] | Sort a list in increasing order according to a comparison function. |
| [sort](list#VALsort) [[List](list)] | Sort a list in increasing order according to a comparison function. |
| [sort](float.arraylabels#VALsort) [[Float.ArrayLabels](float.arraylabels)] | Sort a floatarray in increasing order according to a comparison function. |
| [sort](float.array#VALsort) [[Float.Array](float.array)] | Sort a floatarray in increasing order according to a comparison function. |
| [sort](arraylabels#VALsort) [[ArrayLabels](arraylabels)] | Sort an array in increasing order according to a comparison function. |
| [sort](array#VALsort) [[Array](array)] | Sort an array in increasing order according to a comparison function. |
| [sort\_uniq](listlabels#VALsort_uniq) [[ListLabels](listlabels)] | Same as [`ListLabels.sort`](listlabels#VALsort), but also remove duplicates. |
| [sort\_uniq](list#VALsort_uniq) [[List](list)] | Same as [`List.sort`](list#VALsort), but also remove duplicates. |
| [sorted\_merge](seq#VALsorted_merge) [[Seq](seq)] | If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`. |
| [spawn](domain#VALspawn) [[Domain](domain)] | `spawn f` creates a new domain that runs in parallel with the current domain. |
| [split](str#VALsplit) [[Str](str)] | `split r s` splits `s` into substrings, taking as delimiters the substrings that match `r`, and returns the list of substrings. |
| [split](set.s#VALsplit) [[Set.S](set.s)] | `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. |
| [split](seq#VALsplit) [[Seq](seq)] | `split` is an alias for `unzip`. |
| [split](random.state#VALsplit) [[Random.State](random.state)] | Draw a fresh PRNG state from the given PRNG state. |
| [split](random#VALsplit) [[Random](random)] | Draw a fresh PRNG state from the current state of the domain-local generator used by the default functions. |
| [split](morelabels.set.s#VALsplit) [[MoreLabels.Set.S](morelabels.set.s)] | `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. |
| [split](morelabels.map.s#VALsplit) [[MoreLabels.Map.S](morelabels.map.s)] | `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. |
| [split](map.s#VALsplit) [[Map.S](map.s)] | `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. |
| [split](listlabels#VALsplit) [[ListLabels](listlabels)] | Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. |
| [split](list#VALsplit) [[List](list)] | Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. |
| [split](arraylabels#VALsplit) [[ArrayLabels](arraylabels)] | `split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. |
| [split](array#VALsplit) [[Array](array)] | `split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. |
| [split\_delim](str#VALsplit_delim) [[Str](str)] | Same as [`Str.split`](str#VALsplit) but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. |
| [split\_on\_char](string#VALsplit_on_char) [[String](string)] | `split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. |
| [split\_on\_char](stringlabels#VALsplit_on_char) [[StringLabels](stringlabels)] | `split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. |
| [split\_on\_char](byteslabels#VALsplit_on_char) [[BytesLabels](byteslabels)] | `split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. |
| [split\_on\_char](bytes#VALsplit_on_char) [[Bytes](bytes)] | `split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. |
| [sprintf](printf#VALsprintf) [[Printf](printf)] | Same as [`Printf.fprintf`](printf#VALfprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments. |
| [sprintf](format#VALsprintf) [[Format](format)] | Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. |
| [sqrt](float#VALsqrt) [[Float](float)] | Square root. |
| [sqrt](complex#VALsqrt) [[Complex](complex)] | Square root. |
| [sqrt](stdlib#VALsqrt) [[Stdlib](stdlib)] | Square root. |
| [sscanf](scanf#VALsscanf) [[Scanf](scanf)] | Same as [`Scanf.bscanf`](scanf#VALbscanf), but reads from the given string. |
| [sscanf\_format](scanf#VALsscanf_format) [[Scanf](scanf)] | Same as [`Scanf.bscanf_format`](scanf#VALbscanf_format), but reads from the given string. |
| [sscanf\_opt](scanf#VALsscanf_opt) [[Scanf](scanf)] | Same as [`Scanf.sscanf`](scanf#VALsscanf), but returns `None` in case of scanning failure. |
| [stable\_sort](listlabels#VALstable_sort) [[ListLabels](listlabels)] | Same as [`ListLabels.sort`](listlabels#VALsort), but the sorting algorithm is guaranteed to be stable (i.e. |
| [stable\_sort](list#VALstable_sort) [[List](list)] | Same as [`List.sort`](list#VALsort), but the sorting algorithm is guaranteed to be stable (i.e. |
| [stable\_sort](float.arraylabels#VALstable_sort) [[Float.ArrayLabels](float.arraylabels)] | Same as [`Float.ArrayLabels.sort`](float.arraylabels#VALsort), but the sorting algorithm is stable (i.e. |
| [stable\_sort](float.array#VALstable_sort) [[Float.Array](float.array)] | Same as [`Float.Array.sort`](float.array#VALsort), but the sorting algorithm is stable (i.e. |
| [stable\_sort](arraylabels#VALstable_sort) [[ArrayLabels](arraylabels)] | Same as [`ArrayLabels.sort`](arraylabels#VALsort), but the sorting algorithm is stable (i.e. |
| [stable\_sort](array#VALstable_sort) [[Array](array)] | Same as [`Array.sort`](array#VALsort), but the sorting algorithm is stable (i.e. |
| [start](runtime_events#VALstart) [[Runtime\_events](runtime_events)] | `start ()` will start the collection of events in the runtime if not already started. |
| [start](gc.memprof#VALstart) [[Gc.Memprof](gc.memprof)] | Start the sampling with the given parameters. |
| [starts\_with](string#VALstarts_with) [[String](string)] | `starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`. |
| [starts\_with](stringlabels#VALstarts_with) [[StringLabels](stringlabels)] | `starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`. |
| [starts\_with](byteslabels#VALstarts_with) [[BytesLabels](byteslabels)] | `starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`. |
| [starts\_with](bytes#VALstarts_with) [[Bytes](bytes)] | `starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`. |
| [stat](unixlabels.largefile#VALstat) [[UnixLabels.LargeFile](unixlabels.largefile)] | |
| [stat](unixlabels#VALstat) [[UnixLabels](unixlabels)] | Return the information for the named file. |
| [stat](unix.largefile#VALstat) [[Unix.LargeFile](unix.largefile)] | |
| [stat](unix#VALstat) [[Unix](unix)] | Return the information for the named file. |
| [stat](gc#VALstat) [[Gc](gc)] | Return the current values of the memory management counters in a `stat` record that represent the program's total memory stats. |
| [stats](camlinternaloo#VALstats) [[CamlinternalOO](camlinternaloo)] | |
| [stats](weak.s#VALstats) [[Weak.S](weak.s)] | Return statistics on the table. |
| [stats](morelabels.hashtbl.seededs#VALstats) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [stats](morelabels.hashtbl.s#VALstats) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [stats](morelabels.hashtbl#VALstats) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | `Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. |
| [stats](hashtbl.seededs#VALstats) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [stats](hashtbl.s#VALstats) [[Hashtbl.S](hashtbl.s)] | |
| [stats](hashtbl#VALstats) [[Hashtbl](hashtbl)] | `Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. |
| [stats](ephemeron.seededs#VALstats) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [stats](ephemeron.s#VALstats) [[Ephemeron.S](ephemeron.s)] | |
| [stats\_alive](ephemeron.seededs#VALstats_alive) [[Ephemeron.SeededS](ephemeron.seededs)] | same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings |
| [stats\_alive](ephemeron.s#VALstats_alive) [[Ephemeron.S](ephemeron.s)] | same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings |
| [std\_formatter](format#VALstd_formatter) [[Format](format)] | The initial domain's standard formatter to write to standard output. |
| [stdbuf](format#VALstdbuf) [[Format](format)] | The initial domain's string buffer in which `str_formatter` writes. |
| [stderr](unixlabels#VALstderr) [[UnixLabels](unixlabels)] | File descriptor for standard error. |
| [stderr](unix#VALstderr) [[Unix](unix)] | File descriptor for standard error. |
| [stderr](out_channel#VALstderr) [[Out\_channel](out_channel)] | The standard error output for the process. |
| [stderr](stdlib#VALstderr) [[Stdlib](stdlib)] | The standard error output for the process. |
| [stdin](unixlabels#VALstdin) [[UnixLabels](unixlabels)] | File descriptor for standard input. |
| [stdin](unix#VALstdin) [[Unix](unix)] | File descriptor for standard input. |
| [stdin](scanf.scanning#VALstdin) [[Scanf.Scanning](scanf.scanning)] | The standard input notion for the [`Scanf`](scanf) module. |
| [stdin](in_channel#VALstdin) [[In\_channel](in_channel)] | The standard input for the process. |
| [stdin](stdlib#VALstdin) [[Stdlib](stdlib)] | The standard input for the process. |
| [stdout](unixlabels#VALstdout) [[UnixLabels](unixlabels)] | File descriptor for standard output. |
| [stdout](unix#VALstdout) [[Unix](unix)] | File descriptor for standard output. |
| [stdout](out_channel#VALstdout) [[Out\_channel](out_channel)] | The standard output for the process. |
| [stdout](stdlib#VALstdout) [[Stdlib](stdlib)] | The standard output for the process. |
| [stop](gc.memprof#VALstop) [[Gc.Memprof](gc.memprof)] | Stop the sampling. |
| [str\_formatter](format#VALstr_formatter) [[Format](format)] | The initial domain's formatter to output to the [`Format.stdbuf`](format#VALstdbuf) string buffer. |
| [string](digest#VALstring) [[Digest](digest)] | Return the digest of the given string. |
| [string\_after](str#VALstring_after) [[Str](str)] | `string_after s n` returns the substring of all characters of `s` that follow position `n` (including the character at position `n`). |
| [string\_before](str#VALstring_before) [[Str](str)] | `string_before s n` returns the substring of all characters of `s` that precede position `n` (excluding the character at position `n`). |
| [string\_match](str#VALstring_match) [[Str](str)] | `string_match r s start` tests whether a substring of `s` that starts at position `start` matches the regular expression `r`. |
| [string\_of\_bool](stdlib#VALstring_of_bool) [[Stdlib](stdlib)] | Return the string representation of a boolean. |
| [string\_of\_float](stdlib#VALstring_of_float) [[Stdlib](stdlib)] | Return a string representation of a floating-point number. |
| [string\_of\_fmt](camlinternalformat#VALstring_of_fmt) [[CamlinternalFormat](camlinternalformat)] | |
| [string\_of\_fmtty](camlinternalformat#VALstring_of_fmtty) [[CamlinternalFormat](camlinternalformat)] | |
| [string\_of\_format](stdlib#VALstring_of_format) [[Stdlib](stdlib)] | Converts a format string into a string. |
| [string\_of\_formatting\_lit](camlinternalformat#VALstring_of_formatting_lit) [[CamlinternalFormat](camlinternalformat)] | |
| [string\_of\_inet\_addr](unixlabels#VALstring_of_inet_addr) [[UnixLabels](unixlabels)] | Return the printable representation of the given Internet address. |
| [string\_of\_inet\_addr](unix#VALstring_of_inet_addr) [[Unix](unix)] | Return the printable representation of the given Internet address. |
| [string\_of\_int](stdlib#VALstring_of_int) [[Stdlib](stdlib)] | Return the string representation of an integer, in decimal. |
| [string\_partial\_match](str#VALstring_partial_match) [[Str](str)] | Similar to [`Str.string_match`](str#VALstring_match), but also returns true if the argument string is a prefix of a string that matches. |
| [string\_tag](obj#VALstring_tag) [[Obj](obj)] | |
| [strput\_acc](camlinternalformat#VALstrput_acc) [[CamlinternalFormat](camlinternalformat)] | |
| [sub](string#VALsub) [[String](string)] | `sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. |
| [sub](stringlabels#VALsub) [[StringLabels](stringlabels)] | `sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. |
| [sub](nativeint#VALsub) [[Nativeint](nativeint)] | Subtraction. |
| [sub](int64#VALsub) [[Int64](int64)] | Subtraction. |
| [sub](int32#VALsub) [[Int32](int32)] | Subtraction. |
| [sub](int#VALsub) [[Int](int)] | `sub x y` is the subtraction `x - y`. |
| [sub](float.arraylabels#VALsub) [[Float.ArrayLabels](float.arraylabels)] | `sub a ~pos ~len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. |
| [sub](float.array#VALsub) [[Float.Array](float.array)] | `sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. |
| [sub](float#VALsub) [[Float](float)] | Floating-point subtraction. |
| [sub](complex#VALsub) [[Complex](complex)] | Subtraction |
| [sub](byteslabels#VALsub) [[BytesLabels](byteslabels)] | `sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. |
| [sub](bytes#VALsub) [[Bytes](bytes)] | `sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. |
| [sub](buffer#VALsub) [[Buffer](buffer)] | `Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`. |
| [sub](bigarray.array1#VALsub) [[Bigarray.Array1](bigarray.array1)] | Extract a sub-array of the given one-dimensional Bigarray. |
| [sub](arraylabels#VALsub) [[ArrayLabels](arraylabels)] | `sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. |
| [sub](array#VALsub) [[Array](array)] | `sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. |
| [sub\_left](bigarray.array3#VALsub_left) [[Bigarray.Array3](bigarray.array3)] | Extract a three-dimensional sub-array of the given three-dimensional Bigarray by restricting the first dimension. |
| [sub\_left](bigarray.array2#VALsub_left) [[Bigarray.Array2](bigarray.array2)] | Extract a two-dimensional sub-array of the given two-dimensional Bigarray by restricting the first dimension. |
| [sub\_left](bigarray.genarray#VALsub_left) [[Bigarray.Genarray](bigarray.genarray)] | Extract a sub-array of the given Bigarray by restricting the first (left-most) dimension. |
| [sub\_right](bigarray.array3#VALsub_right) [[Bigarray.Array3](bigarray.array3)] | Extract a three-dimensional sub-array of the given three-dimensional Bigarray by restricting the second dimension. |
| [sub\_right](bigarray.array2#VALsub_right) [[Bigarray.Array2](bigarray.array2)] | Extract a two-dimensional sub-array of the given two-dimensional Bigarray by restricting the second dimension. |
| [sub\_right](bigarray.genarray#VALsub_right) [[Bigarray.Genarray](bigarray.genarray)] | Extract a sub-array of the given Bigarray by restricting the last (right-most) dimension. |
| [sub\_string](byteslabels#VALsub_string) [[BytesLabels](byteslabels)] | Same as [`BytesLabels.sub`](byteslabels#VALsub) but return a string instead of a byte sequence. |
| [sub\_string](bytes#VALsub_string) [[Bytes](bytes)] | Same as [`Bytes.sub`](bytes#VALsub) but return a string instead of a byte sequence. |
| [subbytes](digest#VALsubbytes) [[Digest](digest)] | `Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. |
| [subset](set.s#VALsubset) [[Set.S](set.s)] | `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. |
| [subset](morelabels.set.s#VALsubset) [[MoreLabels.Set.S](morelabels.set.s)] | `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. |
| [substitute\_first](str#VALsubstitute_first) [[Str](str)] | Same as [`Str.global_substitute`](str#VALglobal_substitute), except that only the first substring matching the regular expression is replaced. |
| [substring](digest#VALsubstring) [[Digest](digest)] | `Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. |
| [succ](uchar#VALsucc) [[Uchar](uchar)] | `succ u` is the scalar value after `u` in the set of Unicode scalar values. |
| [succ](nativeint#VALsucc) [[Nativeint](nativeint)] | Successor. |
| [succ](int64#VALsucc) [[Int64](int64)] | Successor. |
| [succ](int32#VALsucc) [[Int32](int32)] | Successor. |
| [succ](int#VALsucc) [[Int](int)] | `succ x` is `add x 1`. |
| [succ](float#VALsucc) [[Float](float)] | `succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. |
| [succ](stdlib#VALsucc) [[Stdlib](stdlib)] | `succ x` is `x + 1`. |
| [symbol\_end](parsing#VALsymbol_end) [[Parsing](parsing)] | See [`Parsing.symbol_start`](parsing#VALsymbol_start). |
| [symbol\_end\_pos](parsing#VALsymbol_end_pos) [[Parsing](parsing)] | Same as `symbol_end`, but return a `position` instead of an offset. |
| [symbol\_start](parsing#VALsymbol_start) [[Parsing](parsing)] | `symbol_start` and [`Parsing.symbol_end`](parsing#VALsymbol_end) are to be called in the action part of a grammar rule only. |
| [symbol\_start\_pos](parsing#VALsymbol_start_pos) [[Parsing](parsing)] | Same as `symbol_start`, but return a `position` instead of an offset. |
| [symlink](unixlabels#VALsymlink) [[UnixLabels](unixlabels)] | `symlink ?to_dir ~src ~dst` creates the file `dst` as a symbolic link to the file `src`. |
| [symlink](unix#VALsymlink) [[Unix](unix)] | `symlink ?to_dir src dst` creates the file `dst` as a symbolic link to the file `src`. |
| [symm](camlinternalformat#VALsymm) [[CamlinternalFormat](camlinternalformat)] | |
| [sync](event#VALsync) [[Event](event)] | 'Synchronize' on an event: offer all the communication possibilities specified in the event to the outside world, and block until one of the communications succeed. |
| [synchronized\_formatter\_of\_out\_channel](format#VALsynchronized_formatter_of_out_channel) [[Format](format)] | `synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`. |
| [system](unixlabels#VALsystem) [[UnixLabels](unixlabels)] | Execute the given command, wait until it terminates, and return its termination status. |
| [system](unix#VALsystem) [[Unix](unix)] | Execute the given command, wait until it terminates, and return its termination status. |
| T |
| [tag](obj#VALtag) [[Obj](obj)] | |
| [take](seq#VALtake) [[Seq](seq)] | `take n xs` is the sequence of the first `n` elements of `xs`. |
| [take](queue#VALtake) [[Queue](queue)] | `take q` removes and returns the first element in queue `q`, or raises [`Queue.Empty`](queue#EXCEPTIONEmpty) if the queue is empty. |
| [take\_opt](queue#VALtake_opt) [[Queue](queue)] | `take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty. |
| [take\_while](seq#VALtake_while) [[Seq](seq)] | `take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`. |
| [tan](float#VALtan) [[Float](float)] | Tangent. |
| [tan](stdlib#VALtan) [[Stdlib](stdlib)] | Tangent. |
| [tanh](float#VALtanh) [[Float](float)] | Hyperbolic tangent. |
| [tanh](stdlib#VALtanh) [[Stdlib](stdlib)] | Hyperbolic tangent. |
| [tcdrain](unixlabels#VALtcdrain) [[UnixLabels](unixlabels)] | Waits until all output written on the given file descriptor has been transmitted. |
| [tcdrain](unix#VALtcdrain) [[Unix](unix)] | Waits until all output written on the given file descriptor has been transmitted. |
| [tcflow](unixlabels#VALtcflow) [[UnixLabels](unixlabels)] | Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: `TCOOFF` suspends output, `TCOON` restarts output, `TCIOFF` transmits a STOP character to suspend input, and `TCION` transmits a START character to restart input. |
| [tcflow](unix#VALtcflow) [[Unix](unix)] | Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: `TCOOFF` suspends output, `TCOON` restarts output, `TCIOFF` transmits a STOP character to suspend input, and `TCION` transmits a START character to restart input. |
| [tcflush](unixlabels#VALtcflush) [[UnixLabels](unixlabels)] | Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: `TCIFLUSH` flushes data received but not read, `TCOFLUSH` flushes data written but not transmitted, and `TCIOFLUSH` flushes both. |
| [tcflush](unix#VALtcflush) [[Unix](unix)] | Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: `TCIFLUSH` flushes data received but not read, `TCOFLUSH` flushes data written but not transmitted, and `TCIOFLUSH` flushes both. |
| [tcgetattr](unixlabels#VALtcgetattr) [[UnixLabels](unixlabels)] | Return the status of the terminal referred to by the given file descriptor. |
| [tcgetattr](unix#VALtcgetattr) [[Unix](unix)] | Return the status of the terminal referred to by the given file descriptor. |
| [tcsendbreak](unixlabels#VALtcsendbreak) [[UnixLabels](unixlabels)] | Send a break condition on the given file descriptor. |
| [tcsendbreak](unix#VALtcsendbreak) [[Unix](unix)] | Send a break condition on the given file descriptor. |
| [tcsetattr](unixlabels#VALtcsetattr) [[UnixLabels](unixlabels)] | Set the status of the terminal referred to by the given file descriptor. |
| [tcsetattr](unix#VALtcsetattr) [[Unix](unix)] | Set the status of the terminal referred to by the given file descriptor. |
| [temp\_file](filename#VALtemp_file) [[Filename](filename)] | `temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. |
| [time](unixlabels#VALtime) [[UnixLabels](unixlabels)] | Return the current time since 00:00:00 GMT, Jan. |
| [time](unix#VALtime) [[Unix](unix)] | Return the current time since 00:00:00 GMT, Jan. |
| [time](sys#VALtime) [[Sys](sys)] | Return the processor time, in seconds, used by the program since the beginning of execution. |
| [times](unixlabels#VALtimes) [[UnixLabels](unixlabels)] | Return the execution times of the process. |
| [times](unix#VALtimes) [[Unix](unix)] | Return the execution times of the process. |
| [tl](listlabels#VALtl) [[ListLabels](listlabels)] | Return the given list without its first element. |
| [tl](list#VALtl) [[List](list)] | Return the given list without its first element. |
| [to\_buffer](marshal#VALto_buffer) [[Marshal](marshal)] | `Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. |
| [to\_bytes](string#VALto_bytes) [[String](string)] | Return a new byte sequence that contains the same bytes as the given string. |
| [to\_bytes](stringlabels#VALto_bytes) [[StringLabels](stringlabels)] | Return a new byte sequence that contains the same bytes as the given string. |
| [to\_bytes](marshal#VALto_bytes) [[Marshal](marshal)] | `Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. |
| [to\_bytes](buffer#VALto_bytes) [[Buffer](buffer)] | Return a copy of the current contents of the buffer. |
| [to\_channel](marshal#VALto_channel) [[Marshal](marshal)] | `Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. |
| [to\_char](uchar#VALto_char) [[Uchar](uchar)] | `to_char u` is `u` as an OCaml latin1 character. |
| [to\_dispenser](seq#VALto_dispenser) [[Seq](seq)] | `to_dispenser xs` is a fresh dispenser on the sequence `xs`. |
| [to\_float](nativeint#VALto_float) [[Nativeint](nativeint)] | Convert the given native integer to a floating-point number. |
| [to\_float](int64#VALto_float) [[Int64](int64)] | Convert the given 64-bit integer to a floating-point number. |
| [to\_float](int32#VALto_float) [[Int32](int32)] | Convert the given 32-bit integer to a floating-point number. |
| [to\_float](int#VALto_float) [[Int](int)] | `to_float x` is `x` as a floating point number. |
| [to\_float](bool#VALto_float) [[Bool](bool)] | `to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`. |
| [to\_hex](digest#VALto_hex) [[Digest](digest)] | Return the printable hexadecimal representation of the given digest. |
| [to\_int](uchar#VALto_int) [[Uchar](uchar)] | `to_int u` is `u` as an integer. |
| [to\_int](nativeint#VALto_int) [[Nativeint](nativeint)] | Convert the given native integer (type `nativeint`) to an integer (type `int`). |
| [to\_int](int64#VALto_int) [[Int64](int64)] | Convert the given 64-bit integer (type `int64`) to an integer (type `int`). |
| [to\_int](int32#VALto_int) [[Int32](int32)] | Convert the given 32-bit integer (type `int32`) to an integer (type `int`). |
| [to\_int](float#VALto_int) [[Float](float)] | Truncate the given floating-point number to an integer. |
| [to\_int](bool#VALto_int) [[Bool](bool)] | `to_int b` is `0` if `b` is `false` and `1` if `b` is `true`. |
| [to\_int32](nativeint#VALto_int32) [[Nativeint](nativeint)] | Convert the given native integer to a 32-bit integer (type `int32`). |
| [to\_int32](int64#VALto_int32) [[Int64](int64)] | Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). |
| [to\_int64](runtime_events.timestamp#VALto_int64) [[Runtime\_events.Timestamp](runtime_events.timestamp)] | |
| [to\_list](result#VALto_list) [[Result](result)] | `to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise. |
| [to\_list](option#VALto_list) [[Option](option)] | `to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`. |
| [to\_list](float.arraylabels#VALto_list) [[Float.ArrayLabels](float.arraylabels)] | `to_list a` returns the list of all the elements of `a`. |
| [to\_list](float.array#VALto_list) [[Float.Array](float.array)] | `to_list a` returns the list of all the elements of `a`. |
| [to\_list](arraylabels#VALto_list) [[ArrayLabels](arraylabels)] | `to_list a` returns the list of all the elements of `a`. |
| [to\_list](array#VALto_list) [[Array](array)] | `to_list a` returns the list of all the elements of `a`. |
| [to\_nativeint](int64#VALto_nativeint) [[Int64](int64)] | Convert the given 64-bit integer (type `int64`) to a native integer. |
| [to\_option](result#VALto_option) [[Result](result)] | `to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`. |
| [to\_result](option#VALto_result) [[Option](option)] | `to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise. |
| [to\_rev\_seq](set.s#VALto_rev_seq) [[Set.S](set.s)] | Iterate on the whole set, in descending order |
| [to\_rev\_seq](morelabels.set.s#VALto_rev_seq) [[MoreLabels.Set.S](morelabels.set.s)] | Iterate on the whole set, in descending order |
| [to\_rev\_seq](morelabels.map.s#VALto_rev_seq) [[MoreLabels.Map.S](morelabels.map.s)] | Iterate on the whole map, in descending order of keys |
| [to\_rev\_seq](map.s#VALto_rev_seq) [[Map.S](map.s)] | Iterate on the whole map, in descending order of keys |
| [to\_seq](string#VALto_seq) [[String](string)] | `to_seq s` is a sequence made of the string's characters in increasing order. |
| [to\_seq](stringlabels#VALto_seq) [[StringLabels](stringlabels)] | `to_seq s` is a sequence made of the string's characters in increasing order. |
| [to\_seq](stack#VALto_seq) [[Stack](stack)] | Iterate on the stack, top to bottom. |
| [to\_seq](set.s#VALto_seq) [[Set.S](set.s)] | Iterate on the whole set, in ascending order |
| [to\_seq](result#VALto_seq) [[Result](result)] | `to_seq r` is `r` as a sequence. |
| [to\_seq](queue#VALto_seq) [[Queue](queue)] | Iterate on the queue, in front-to-back order. |
| [to\_seq](option#VALto_seq) [[Option](option)] | `to_seq o` is `o` as a sequence. |
| [to\_seq](morelabels.set.s#VALto_seq) [[MoreLabels.Set.S](morelabels.set.s)] | Iterate on the whole set, in ascending order |
| [to\_seq](morelabels.map.s#VALto_seq) [[MoreLabels.Map.S](morelabels.map.s)] | Iterate on the whole map, in ascending order of keys |
| [to\_seq](morelabels.hashtbl.seededs#VALto_seq) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [to\_seq](morelabels.hashtbl.s#VALto_seq) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [to\_seq](morelabels.hashtbl#VALto_seq) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Iterate on the whole table. |
| [to\_seq](map.s#VALto_seq) [[Map.S](map.s)] | Iterate on the whole map, in ascending order of keys |
| [to\_seq](listlabels#VALto_seq) [[ListLabels](listlabels)] | Iterate on the list. |
| [to\_seq](list#VALto_seq) [[List](list)] | Iterate on the list. |
| [to\_seq](hashtbl.seededs#VALto_seq) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [to\_seq](hashtbl.s#VALto_seq) [[Hashtbl.S](hashtbl.s)] | |
| [to\_seq](hashtbl#VALto_seq) [[Hashtbl](hashtbl)] | Iterate on the whole table. |
| [to\_seq](float.arraylabels#VALto_seq) [[Float.ArrayLabels](float.arraylabels)] | Iterate on the floatarray, in increasing order. |
| [to\_seq](float.array#VALto_seq) [[Float.Array](float.array)] | Iterate on the floatarray, in increasing order. |
| [to\_seq](byteslabels#VALto_seq) [[BytesLabels](byteslabels)] | Iterate on the string, in increasing index order. |
| [to\_seq](bytes#VALto_seq) [[Bytes](bytes)] | Iterate on the string, in increasing index order. |
| [to\_seq](buffer#VALto_seq) [[Buffer](buffer)] | Iterate on the buffer, in increasing order. |
| [to\_seq](arraylabels#VALto_seq) [[ArrayLabels](arraylabels)] | Iterate on the array, in increasing order. |
| [to\_seq](array#VALto_seq) [[Array](array)] | Iterate on the array, in increasing order. |
| [to\_seq\_from](set.s#VALto_seq_from) [[Set.S](set.s)] | `to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. |
| [to\_seq\_from](morelabels.set.s#VALto_seq_from) [[MoreLabels.Set.S](morelabels.set.s)] | `to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. |
| [to\_seq\_from](morelabels.map.s#VALto_seq_from) [[MoreLabels.Map.S](morelabels.map.s)] | `to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. |
| [to\_seq\_from](map.s#VALto_seq_from) [[Map.S](map.s)] | `to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. |
| [to\_seq\_keys](morelabels.hashtbl.seededs#VALto_seq_keys) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [to\_seq\_keys](morelabels.hashtbl.s#VALto_seq_keys) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [to\_seq\_keys](morelabels.hashtbl#VALto_seq_keys) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Same as `Seq.map fst (to_seq m)` |
| [to\_seq\_keys](hashtbl.seededs#VALto_seq_keys) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [to\_seq\_keys](hashtbl.s#VALto_seq_keys) [[Hashtbl.S](hashtbl.s)] | |
| [to\_seq\_keys](hashtbl#VALto_seq_keys) [[Hashtbl](hashtbl)] | Same as `Seq.map fst (to_seq m)` |
| [to\_seq\_values](morelabels.hashtbl.seededs#VALto_seq_values) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [to\_seq\_values](morelabels.hashtbl.s#VALto_seq_values) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [to\_seq\_values](morelabels.hashtbl#VALto_seq_values) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | Same as `Seq.map snd (to_seq m)` |
| [to\_seq\_values](hashtbl.seededs#VALto_seq_values) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [to\_seq\_values](hashtbl.s#VALto_seq_values) [[Hashtbl.S](hashtbl.s)] | |
| [to\_seq\_values](hashtbl#VALto_seq_values) [[Hashtbl](hashtbl)] | Same as `Seq.map snd (to_seq m)` |
| [to\_seqi](string#VALto_seqi) [[String](string)] | `to_seqi s` is like [`String.to_seq`](string#VALto_seq) but also tuples the corresponding index. |
| [to\_seqi](stringlabels#VALto_seqi) [[StringLabels](stringlabels)] | `to_seqi s` is like [`StringLabels.to_seq`](stringlabels#VALto_seq) but also tuples the corresponding index. |
| [to\_seqi](float.arraylabels#VALto_seqi) [[Float.ArrayLabels](float.arraylabels)] | Iterate on the floatarray, in increasing order, yielding indices along elements. |
| [to\_seqi](float.array#VALto_seqi) [[Float.Array](float.array)] | Iterate on the floatarray, in increasing order, yielding indices along elements. |
| [to\_seqi](byteslabels#VALto_seqi) [[BytesLabels](byteslabels)] | Iterate on the string, in increasing order, yielding indices along chars |
| [to\_seqi](bytes#VALto_seqi) [[Bytes](bytes)] | Iterate on the string, in increasing order, yielding indices along chars |
| [to\_seqi](buffer#VALto_seqi) [[Buffer](buffer)] | Iterate on the buffer, in increasing order, yielding indices along chars. |
| [to\_seqi](arraylabels#VALto_seqi) [[ArrayLabels](arraylabels)] | Iterate on the array, in increasing order, yielding indices along elements. |
| [to\_seqi](array#VALto_seqi) [[Array](array)] | Iterate on the array, in increasing order, yielding indices along elements. |
| [to\_string](unit#VALto_string) [[Unit](unit)] | `to_string b` is `"()"`. |
| [to\_string](printexc#VALto_string) [[Printexc](printexc)] | `Printexc.to_string e` returns a string representation of the exception `e`. |
| [to\_string](nativeint#VALto_string) [[Nativeint](nativeint)] | Return the string representation of its argument, in decimal. |
| [to\_string](marshal#VALto_string) [[Marshal](marshal)] | Same as `to_bytes` but return the result as a string instead of a byte sequence. |
| [to\_string](int64#VALto_string) [[Int64](int64)] | Return the string representation of its argument, in decimal. |
| [to\_string](int32#VALto_string) [[Int32](int32)] | Return the string representation of its argument, in signed decimal. |
| [to\_string](int#VALto_string) [[Int](int)] | `to_string x` is the written representation of `x` in decimal. |
| [to\_string](float#VALto_string) [[Float](float)] | Return a string representation of a floating-point number. |
| [to\_string](byteslabels#VALto_string) [[BytesLabels](byteslabels)] | Return a new string that contains the same bytes as the given byte sequence. |
| [to\_string](bytes#VALto_string) [[Bytes](bytes)] | Return a new string that contains the same bytes as the given byte sequence. |
| [to\_string](bool#VALto_string) [[Bool](bool)] | `to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`. |
| [to\_string\_default](printexc#VALto_string_default) [[Printexc](printexc)] | `Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers. |
| [top](stack#VALtop) [[Stack](stack)] | `top s` returns the topmost element in stack `s`, or raises [`Stack.Empty`](stack#EXCEPTIONEmpty) if the stack is empty. |
| [top](queue#VALtop) [[Queue](queue)] | `top` is a synonym for `peek`. |
| [top\_opt](stack#VALtop_opt) [[Stack](stack)] | `top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty. |
| [total\_size](marshal#VALtotal_size) [[Marshal](marshal)] | See [`Marshal.header_size`](marshal#VALheader_size). |
| [trans](camlinternalformat#VALtrans) [[CamlinternalFormat](camlinternalformat)] | |
| [transfer](queue#VALtransfer) [[Queue](queue)] | `transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. |
| [transpose](seq#VALtranspose) [[Seq](seq)] | If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`. |
| [trim](string#VALtrim) [[String](string)] | `trim s` is `s` without leading and trailing whitespace. |
| [trim](stringlabels#VALtrim) [[StringLabels](stringlabels)] | `trim s` is `s` without leading and trailing whitespace. |
| [trim](byteslabels#VALtrim) [[BytesLabels](byteslabels)] | Return a copy of the argument, without leading and trailing whitespace. |
| [trim](bytes#VALtrim) [[Bytes](bytes)] | Return a copy of the argument, without leading and trailing whitespace. |
| [trunc](float#VALtrunc) [[Float](float)] | `trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`. |
| [truncate](unixlabels.largefile#VALtruncate) [[UnixLabels.LargeFile](unixlabels.largefile)] | See `truncate`. |
| [truncate](unixlabels#VALtruncate) [[UnixLabels](unixlabels)] | Truncates the named file to the given size. |
| [truncate](unix.largefile#VALtruncate) [[Unix.LargeFile](unix.largefile)] | See `truncate`. |
| [truncate](unix#VALtruncate) [[Unix](unix)] | Truncates the named file to the given size. |
| [truncate](buffer#VALtruncate) [[Buffer](buffer)] | `truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened. |
| [truncate](stdlib#VALtruncate) [[Stdlib](stdlib)] | Same as [`int_of_float`](stdlib#VALint_of_float). |
| [try\_acquire](semaphore.binary#VALtry_acquire) [[Semaphore.Binary](semaphore.binary)] | `try_acquire s` immediately returns `false` if the semaphore `s` has value 0. |
| [try\_acquire](semaphore.counting#VALtry_acquire) [[Semaphore.Counting](semaphore.counting)] | `try_acquire s` immediately returns `false` if the value of semaphore `s` is zero. |
| [try\_lock](mutex#VALtry_lock) [[Mutex](mutex)] | Same as [`Mutex.lock`](mutex#VALlock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. |
| [try\_with](effect.deep#VALtry_with) [[Effect.Deep](effect.deep)] | `try_with f v h` runs the computation `f v` under the handler `h`. |
| [type\_format](camlinternalformat#VALtype_format) [[CamlinternalFormat](camlinternalformat)] | |
| U |
| [umask](unixlabels#VALumask) [[UnixLabels](unixlabels)] | Set the process's file mode creation mask, and return the previous mask. |
| [umask](unix#VALumask) [[Unix](unix)] | Set the process's file mode creation mask, and return the previous mask. |
| [unaligned\_tag](obj#VALunaligned_tag) [[Obj](obj)] | |
| [uncapitalize\_ascii](string#VALuncapitalize_ascii) [[String](string)] | `uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. |
| [uncapitalize\_ascii](stringlabels#VALuncapitalize_ascii) [[StringLabels](stringlabels)] | `uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. |
| [uncapitalize\_ascii](byteslabels#VALuncapitalize_ascii) [[BytesLabels](byteslabels)] | Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. |
| [uncapitalize\_ascii](bytes#VALuncapitalize_ascii) [[Bytes](bytes)] | Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. |
| [uncons](seq#VALuncons) [[Seq](seq)] | If `xs` is empty, then `uncons xs` is `None`. |
| [unescaped](scanf#VALunescaped) [[Scanf](scanf)] | `unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. |
| [unfold](seq#VALunfold) [[Seq](seq)] | `unfold` constructs a sequence out of a step function and an initial state. |
| [union](set.s#VALunion) [[Set.S](set.s)] | Set union. |
| [union](morelabels.set.s#VALunion) [[MoreLabels.Set.S](morelabels.set.s)] | Set union. |
| [union](morelabels.map.s#VALunion) [[MoreLabels.Map.S](morelabels.map.s)] | `union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. |
| [union](map.s#VALunion) [[Map.S](map.s)] | `union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. |
| [unix](sys#VALunix) [[Sys](sys)] | True if `Sys.os_type = "Unix"`. |
| [unlink](unixlabels#VALunlink) [[UnixLabels](unixlabels)] | Removes the named file. |
| [unlink](unix#VALunlink) [[Unix](unix)] | Removes the named file. |
| [unlock](mutex#VALunlock) [[Mutex](mutex)] | Unlock the given mutex. |
| [unsafe\_environment](unixlabels#VALunsafe_environment) [[UnixLabels](unixlabels)] | Return the process environment, as an array of strings with the format ``variable=value''. |
| [unsafe\_environment](unix#VALunsafe_environment) [[Unix](unix)] | Return the process environment, as an array of strings with the format ``variable=value''. |
| [unsafe\_get](bigarray.array3#VALunsafe_get) [[Bigarray.Array3](bigarray.array3)] | Like [`Bigarray.Array3.get`](bigarray.array3#VALget), but bounds checking is not always performed. |
| [unsafe\_get](bigarray.array2#VALunsafe_get) [[Bigarray.Array2](bigarray.array2)] | Like [`Bigarray.Array2.get`](bigarray.array2#VALget), but bounds checking is not always performed. |
| [unsafe\_get](bigarray.array1#VALunsafe_get) [[Bigarray.Array1](bigarray.array1)] | Like [`Bigarray.Array1.get`](bigarray.array1#VALget), but bounds checking is not always performed. |
| [unsafe\_getenv](unixlabels#VALunsafe_getenv) [[UnixLabels](unixlabels)] | Return the value associated to a variable in the process environment. |
| [unsafe\_getenv](unix#VALunsafe_getenv) [[Unix](unix)] | Return the value associated to a variable in the process environment. |
| [unsafe\_of\_string](byteslabels#VALunsafe_of_string) [[BytesLabels](byteslabels)] | Unsafely convert a shared string to a byte sequence that should not be mutated. |
| [unsafe\_of\_string](bytes#VALunsafe_of_string) [[Bytes](bytes)] | Unsafely convert a shared string to a byte sequence that should not be mutated. |
| [unsafe\_set](bigarray.array3#VALunsafe_set) [[Bigarray.Array3](bigarray.array3)] | Like [`Bigarray.Array3.set`](bigarray.array3#VALset), but bounds checking is not always performed. |
| [unsafe\_set](bigarray.array2#VALunsafe_set) [[Bigarray.Array2](bigarray.array2)] | Like [`Bigarray.Array2.set`](bigarray.array2#VALset), but bounds checking is not always performed. |
| [unsafe\_set](bigarray.array1#VALunsafe_set) [[Bigarray.Array1](bigarray.array1)] | Like [`Bigarray.Array1.set`](bigarray.array1#VALset), but bounds checking is not always performed. |
| [unsafe\_to\_string](byteslabels#VALunsafe_to_string) [[BytesLabels](byteslabels)] | Unsafely convert a byte sequence into a string. |
| [unsafe\_to\_string](bytes#VALunsafe_to_string) [[Bytes](bytes)] | Unsafely convert a byte sequence into a string. |
| [unset\_data](obj.ephemeron#VALunset_data) [[Obj.Ephemeron](obj.ephemeron)] | |
| [unset\_key](obj.ephemeron#VALunset_key) [[Obj.Ephemeron](obj.ephemeron)] | |
| [unsigned\_compare](nativeint#VALunsigned_compare) [[Nativeint](nativeint)] | Same as [`Nativeint.compare`](nativeint#VALcompare), except that arguments are interpreted as *unsigned* native integers. |
| [unsigned\_compare](int64#VALunsigned_compare) [[Int64](int64)] | Same as [`Int64.compare`](int64#VALcompare), except that arguments are interpreted as *unsigned* 64-bit integers. |
| [unsigned\_compare](int32#VALunsigned_compare) [[Int32](int32)] | Same as [`Int32.compare`](int32#VALcompare), except that arguments are interpreted as *unsigned* 32-bit integers. |
| [unsigned\_div](nativeint#VALunsigned_div) [[Nativeint](nativeint)] | Same as [`Nativeint.div`](nativeint#VALdiv), except that arguments and result are interpreted as *unsigned* native integers. |
| [unsigned\_div](int64#VALunsigned_div) [[Int64](int64)] | Same as [`Int64.div`](int64#VALdiv), except that arguments and result are interpreted as *unsigned* 64-bit integers. |
| [unsigned\_div](int32#VALunsigned_div) [[Int32](int32)] | Same as [`Int32.div`](int32#VALdiv), except that arguments and result are interpreted as *unsigned* 32-bit integers. |
| [unsigned\_rem](nativeint#VALunsigned_rem) [[Nativeint](nativeint)] | Same as [`Nativeint.rem`](nativeint#VALrem), except that arguments and result are interpreted as *unsigned* native integers. |
| [unsigned\_rem](int64#VALunsigned_rem) [[Int64](int64)] | Same as [`Int64.rem`](int64#VALrem), except that arguments and result are interpreted as *unsigned* 64-bit integers. |
| [unsigned\_rem](int32#VALunsigned_rem) [[Int32](int32)] | Same as [`Int32.rem`](int32#VALrem), except that arguments and result are interpreted as *unsigned* 32-bit integers. |
| [unsigned\_to\_int](nativeint#VALunsigned_to_int) [[Nativeint](nativeint)] | Same as [`Nativeint.to_int`](nativeint#VALto_int), but interprets the argument as an *unsigned* integer. |
| [unsigned\_to\_int](int64#VALunsigned_to_int) [[Int64](int64)] | Same as [`Int64.to_int`](int64#VALto_int), but interprets the argument as an *unsigned* integer. |
| [unsigned\_to\_int](int32#VALunsigned_to_int) [[Int32](int32)] | Same as [`Int32.to_int`](int32#VALto_int), but interprets the argument as an *unsigned* integer. |
| [unzip](seq#VALunzip) [[Seq](seq)] | `unzip` transforms a sequence of pairs into a pair of sequences. |
| [update](morelabels.map.s#VALupdate) [[MoreLabels.Map.S](morelabels.map.s)] | `update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. |
| [update](map.s#VALupdate) [[Map.S](map.s)] | `update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. |
| [update\_geometry](format#VALupdate_geometry) [[Format](format)] | |
| [update\_mod](camlinternalmod#VALupdate_mod) [[CamlinternalMod](camlinternalmod)] | |
| [uppercase\_ascii](string#VALuppercase_ascii) [[String](string)] | `uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. |
| [uppercase\_ascii](stringlabels#VALuppercase_ascii) [[StringLabels](stringlabels)] | `uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. |
| [uppercase\_ascii](char#VALuppercase_ascii) [[Char](char)] | Convert the given character to its equivalent uppercase character, using the US-ASCII character set. |
| [uppercase\_ascii](byteslabels#VALuppercase_ascii) [[BytesLabels](byteslabels)] | Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. |
| [uppercase\_ascii](bytes#VALuppercase_ascii) [[Bytes](bytes)] | Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. |
| [usage](arg#VALusage) [[Arg](arg)] | `Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. |
| [usage\_string](arg#VALusage_string) [[Arg](arg)] | Returns the message that would have been printed by [`Arg.usage`](arg#VALusage), if provided with the same parameters. |
| [use\_printers](printexc#VALuse_printers) [[Printexc](printexc)] | `Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with else as the resulting string otherwise. |
| [utf\_16\_byte\_length](uchar#VALutf_16_byte_length) [[Uchar](uchar)] | `utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. |
| [utf\_8\_byte\_length](uchar#VALutf_8_byte_length) [[Uchar](uchar)] | `utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8. |
| [utf\_decode](uchar#VALutf_decode) [[Uchar](uchar)] | `utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. |
| [utf\_decode\_invalid](uchar#VALutf_decode_invalid) [[Uchar](uchar)] | `utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. |
| [utf\_decode\_is\_valid](uchar#VALutf_decode_is_valid) [[Uchar](uchar)] | `utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode. |
| [utf\_decode\_length](uchar#VALutf_decode_length) [[Uchar](uchar)] | `utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. |
| [utf\_decode\_uchar](uchar#VALutf_decode_uchar) [[Uchar](uchar)] | `utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](uchar#VALrep) otherwise. |
| [utimes](unixlabels#VALutimes) [[UnixLabels](unixlabels)] | Set the last access time (second arg) and last modification time (third arg) for a file. |
| [utimes](unix#VALutimes) [[Unix](unix)] | Set the last access time (second arg) and last modification time (third arg) for a file. |
| V |
| [value](result#VALvalue) [[Result](result)] | `value r ~default` is `v` if `r` is `Ok v` and `default` otherwise. |
| [value](option#VALvalue) [[Option](option)] | `value o ~default` is `v` if `o` is `Some v` and `default` otherwise. |
| W |
| [wait](unixlabels#VALwait) [[UnixLabels](unixlabels)] | Wait until one of the children processes die, and return its pid and termination status. |
| [wait](unix#VALwait) [[Unix](unix)] | Wait until one of the children processes die, and return its pid and termination status. |
| [wait](condition#VALwait) [[Condition](condition)] | The call `wait c m` is permitted only if `m` is the mutex associated with the condition variable `c`, and only if `m` is currently locked. |
| [wait\_pid](thread#VALwait_pid) [[Thread](thread)] | Same function as [`Unix.waitpid`](unix#VALwaitpid).
|
| [wait\_signal](thread#VALwait_signal) [[Thread](thread)] | `wait_signal sigs` suspends the execution of the calling thread until the process receives one of the signals specified in the list `sigs`. |
| [wait\_timed\_read](thread#VALwait_timed_read) [[Thread](thread)] | See [`Thread.wait_timed_write`](thread#VALwait_timed_write).
|
| [wait\_timed\_write](thread#VALwait_timed_write) [[Thread](thread)] | Suspend the execution of the calling thread until at least one character or EOF is available for reading (`wait_timed_read`) or one character can be written without blocking (`wait_timed_write`) on the given Unix file descriptor.
|
| [waitpid](unixlabels#VALwaitpid) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.wait`](unixlabels#VALwait), but waits for the child process whose pid is given. |
| [waitpid](unix#VALwaitpid) [[Unix](unix)] | Same as [`Unix.wait`](unix#VALwait), but waits for the child process whose pid is given. |
| [widen](camlinternaloo#VALwiden) [[CamlinternalOO](camlinternaloo)] | |
| [win32](sys#VALwin32) [[Sys](sys)] | True if `Sys.os_type = "Win32"`. |
| [with\_open\_bin](out_channel#VALwith_open_bin) [[Out\_channel](out_channel)] | `with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f
oc`. |
| [with\_open\_bin](in_channel#VALwith_open_bin) [[In\_channel](in_channel)] | `with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f
ic`. |
| [with\_open\_gen](out_channel#VALwith_open_gen) [[Out\_channel](out_channel)] | Like [`Out\_channel.with_open_bin`](out_channel#VALwith_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`Out\_channel.open_gen`](out_channel#VALopen_gen)). |
| [with\_open\_gen](in_channel#VALwith_open_gen) [[In\_channel](in_channel)] | Like [`In\_channel.with_open_bin`](in_channel#VALwith_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`In\_channel.open_gen`](in_channel#VALopen_gen)). |
| [with\_open\_text](out_channel#VALwith_open_text) [[Out\_channel](out_channel)] | Like [`Out\_channel.with_open_bin`](out_channel#VALwith_open_bin), but the channel is opened in text mode (see [`Out\_channel.open_text`](out_channel#VALopen_text)). |
| [with\_open\_text](in_channel#VALwith_open_text) [[In\_channel](in_channel)] | Like [`In\_channel.with_open_bin`](in_channel#VALwith_open_bin), but the channel is opened in text mode (see [`In\_channel.open_text`](in_channel#VALopen_text)). |
| [with\_positions](lexing#VALwith_positions) [[Lexing](lexing)] | Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`). |
| [with\_tag](obj#VALwith_tag) [[Obj](obj)] | |
| [word\_size](sys#VALword_size) [[Sys](sys)] | Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64. |
| [wrap](event#VALwrap) [[Event](event)] | `wrap ev fn` returns the event that performs the same communications as `ev`, then applies the post-processing function `fn` on the return value. |
| [wrap\_abort](event#VALwrap_abort) [[Event](event)] | `wrap_abort ev fn` returns the event that performs the same communications as `ev`, but if it is not selected the function `fn` is called after the synchronization. |
| [write](unixlabels#VALwrite) [[UnixLabels](unixlabels)] | `write fd ~buf ~pos ~len` writes `len` bytes to descriptor `fd`, taking them from byte sequence `buf`, starting at position `pos` in `buff`. |
| [write](unix#VALwrite) [[Unix](unix)] | `write fd buf pos len` writes `len` bytes to descriptor `fd`, taking them from byte sequence `buf`, starting at position `pos` in `buff`. |
| [write\_arg](arg#VALwrite_arg) [[Arg](arg)] | `Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. |
| [write\_arg0](arg#VALwrite_arg0) [[Arg](arg)] | Identical to [`Arg.write_arg`](arg#VALwrite_arg) but uses the null character for terminator instead of newline. |
| [write\_substring](unixlabels#VALwrite_substring) [[UnixLabels](unixlabels)] | Same as [`UnixLabels.write`](unixlabels#VALwrite), but take the data from a string instead of a byte sequence. |
| [write\_substring](unix#VALwrite_substring) [[Unix](unix)] | Same as [`Unix.write`](unix#VALwrite), but take the data from a string instead of a byte sequence. |
| Y |
| [yield](thread#VALyield) [[Thread](thread)] | Re-schedule the calling thread without suspending it. |
| Z |
| [zero](nativeint#VALzero) [[Nativeint](nativeint)] | The native integer 0. |
| [zero](int64#VALzero) [[Int64](int64)] | The 64-bit integer 0. |
| [zero](int32#VALzero) [[Int32](int32)] | The 32-bit integer 0. |
| [zero](int#VALzero) [[Int](int)] | `zero` is the integer `0`. |
| [zero](float#VALzero) [[Float](float)] | The floating point 0. |
| [zero](complex#VALzero) [[Complex](complex)] | The complex number `0`. |
| [zip](seq#VALzip) [[Seq](seq)] | `zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`. |
| programming_docs |
ocaml Module Bool Module Bool
===========
```
module Bool: sig .. end
```
Boolean values.
* **Since** 4.08
Booleans
--------
```
type t = bool =
```
| | |
| --- | --- |
| `|` | `false` |
| `|` | `true` |
The type of booleans (truth values).
The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types.
```
val not : bool -> bool
```
`not b` is the boolean negation of `b`.
```
val (&&) : bool -> bool -> bool
```
`e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. If `e0` evaluates to `false`, `e1` is not evaluated. Right-associative operator at precedence level 3/11.
```
val (||) : bool -> bool -> bool
```
`e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. If `e0` evaluates to `true`, `e1` is not evaluated. Right-associative operator at precedence level 2/11.
Predicates and comparisons
--------------------------
```
val equal : bool -> bool -> bool
```
`equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`.
```
val compare : bool -> bool -> int
```
`compare b0 b1` is a total order on boolean values. `false` is smaller than `true`.
Converting
----------
```
val to_int : bool -> int
```
`to_int b` is `0` if `b` is `false` and `1` if `b` is `true`.
```
val to_float : bool -> float
```
`to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`.
```
val to_string : bool -> string
```
`to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`.
ocaml Module Buffer Module Buffer
=============
```
module Buffer: sig .. end
```
Extensible buffers.
This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example:
```
let concat_strings ss =
let b = Buffer.create 16 in
List.iter (Buffer.add_string b) ss;
Buffer.contents b
```
* **Alert unsynchronized\_access.** Unsynchronized accesses to buffers are a programming error.
**Unsynchronized accesses**
Unsynchronized accesses to a buffer may lead to an invalid buffer state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
```
type t
```
The abstract type of buffers.
```
val create : int -> t
```
`create n` returns a fresh buffer, initially empty. The `n` parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than `n` characters are stored in the buffer, but shrinks back to `n` characters when `reset` is called. For best performance, `n` should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take `n = 16` for instance. If `n` is not between 1 and [`Sys.max_string_length`](sys#VALmax_string_length), it will be clipped to that interval.
```
val contents : t -> string
```
Return a copy of the current contents of the buffer. The buffer itself is unchanged.
```
val to_bytes : t -> bytes
```
Return a copy of the current contents of the buffer. The buffer itself is unchanged.
* **Since** 4.02
```
val sub : t -> int -> int -> string
```
`Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`.
* **Raises** `Invalid_argument` if `off` and `len` do not designate a valid range of `b`.
```
val blit : t -> int -> bytes -> int -> int -> unit
```
`Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`.
* **Since** 3.11.2
* **Raises** `Invalid_argument` if `srcoff` and `len` do not designate a valid range of `src`, or if `dstoff` and `len` do not designate a valid range of `dst`.
```
val nth : t -> int -> char
```
Get the n-th character of the buffer.
* **Raises** `Invalid_argument` if index out of bounds
```
val length : t -> int
```
Return the number of characters currently contained in the buffer.
```
val clear : t -> unit
```
Empty the buffer.
```
val reset : t -> unit
```
Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](buffer#VALcreate) `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer.
```
val output_buffer : out_channel -> t -> unit
```
`output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`.
```
val truncate : t -> int -> unit
```
`truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened.
* **Since** 4.05.0
* **Raises** `Invalid_argument` if `len < 0` or `len > length b`.
Appending
---------
Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond [`Sys.max_string_length`](sys#VALmax_string_length).
```
val add_char : t -> char -> unit
```
`add_char b c` appends the character `c` at the end of buffer `b`.
```
val add_utf_8_uchar : t -> Uchar.t -> unit
```
`add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`.
* **Since** 4.06.0
```
val add_utf_16le_uchar : t -> Uchar.t -> unit
```
`add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`.
* **Since** 4.06.0
```
val add_utf_16be_uchar : t -> Uchar.t -> unit
```
`add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`.
* **Since** 4.06.0
```
val add_string : t -> string -> unit
```
`add_string b s` appends the string `s` at the end of buffer `b`.
```
val add_bytes : t -> bytes -> unit
```
`add_bytes b s` appends the byte sequence `s` at the end of buffer `b`.
* **Since** 4.02
```
val add_substring : t -> string -> int -> int -> unit
```
`add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`.
* **Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid range of `s`.
```
val add_subbytes : t -> bytes -> int -> int -> unit
```
`add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`.
* **Since** 4.02
* **Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid range of `s`.
```
val add_substitute : t -> (string -> string) -> string -> unit
```
`add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. The substitution process looks for variables into the pattern and substitutes each variable name by its value, as obtained by applying the mapping `f` to the variable name. Inside the string pattern, a variable name immediately follows a non-escaped `$` character and is one of the following:
* a non empty sequence of alphanumeric or `_` characters,
* an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; it then stands for a plain `$`.
* **Raises** `Not_found` if the closing character of a parenthesized variable cannot be found.
```
val add_buffer : t -> t -> unit
```
`add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified.
```
val add_channel : t -> in_channel -> int -> unit
```
`add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`.
* **Raises**
+ `End_of_file` if the channel contains fewer than `n` characters. In this case, the characters are still added to the buffer, so as to avoid loss of data.
+ `Invalid_argument` if `len < 0` or `len > Sys.max_string_length`.
Buffers and Sequences
---------------------
```
val to_seq : t -> char Seq.t
```
Iterate on the buffer, in increasing order.
The behavior is not specified if the buffer is modified during iteration.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
Iterate on the buffer, in increasing order, yielding indices along chars.
The behavior is not specified if the buffer is modified during iteration.
* **Since** 4.07
```
val add_seq : t -> char Seq.t -> unit
```
Add chars to the buffer
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
Create a buffer from the generator
* **Since** 4.07
Binary encoding of integers
---------------------------
The functions in this section append binary encodings of integers to buffers.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. Functions that encode these values truncate their inputs to their least significant bytes.
```
val add_uint8 : t -> int -> unit
```
`add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int8 : t -> int -> unit
```
`add_int8 b i` appends a binary signed 8-bit integer `i` to `b`.
* **Since** 4.08
```
val add_uint16_ne : t -> int -> unit
```
`add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`.
* **Since** 4.08
```
val add_uint16_be : t -> int -> unit
```
`add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`.
* **Since** 4.08
```
val add_uint16_le : t -> int -> unit
```
`add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int16_ne : t -> int -> unit
```
`add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int16_be : t -> int -> unit
```
`add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int16_le : t -> int -> unit
```
`add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int32_ne : t -> int32 -> unit
```
`add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int32_be : t -> int32 -> unit
```
`add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int32_le : t -> int32 -> unit
```
`add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int64_ne : t -> int64 -> unit
```
`add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int64_be : t -> int64 -> unit
```
`add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`.
* **Since** 4.08
```
val add_int64_le : t -> int64 -> unit
```
`add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`.
* **Since** 4.08
ocaml Module ListLabels Module ListLabels
=================
```
module ListLabels: sig .. end
```
List operations.
Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses.
The above considerations can usually be ignored if your lists are not longer than about 10000 elements.
The labeled version of this module can be used as described in the [`StdLabels`](stdlabels) module.
```
type 'a t = 'a list =
```
| | |
| --- | --- |
| `|` | `[]` |
| `|` | `(::) of `'a * 'a list`` |
An alias for the type of lists.
```
val length : 'a list -> int
```
Return the length (number of elements) of the given list.
```
val compare_lengths : 'a list -> 'b list -> int
```
Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list.
* **Since** 4.05.0
```
val compare_length_with : 'a list -> len:int -> int
```
Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list.
* **Since** 4.05.0
```
val cons : 'a -> 'a list -> 'a list
```
`cons x xs` is `x :: xs`
* **Since** 4.05.0
```
val hd : 'a list -> 'a
```
Return the first element of the given list.
* **Raises** `Failure` if the list is empty.
```
val tl : 'a list -> 'a list
```
Return the given list without its first element.
* **Raises** `Failure` if the list is empty.
```
val nth : 'a list -> int -> 'a
```
Return the `n`-th element of the given list. The first element (head of the list) is at position 0.
* **Raises**
+ `Failure` if the list is too short.
+ `Invalid_argument` if `n` is negative.
```
val nth_opt : 'a list -> int -> 'a option
```
Return the `n`-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short.
* **Since** 4.05
* **Raises** `Invalid_argument` if `n` is negative.
```
val rev : 'a list -> 'a list
```
List reversal.
```
val init : len:int -> f:(int -> 'a) -> 'a list
```
`init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right.
* **Since** 4.06.0
* **Raises** `Invalid_argument` if `len < 0`.
```
val append : 'a list -> 'a list -> 'a list
```
Concatenate two lists. Same function as the infix operator `@`. Not tail-recursive (length of the first argument). The `@` operator is not tail-recursive either.
```
val rev_append : 'a list -> 'a list -> 'a list
```
`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`ListLabels.rev`](listlabels#VALrev)`l1) @ l2`, but `rev_append` is tail-recursive and more efficient.
```
val concat : 'a list list -> 'a list
```
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
```
val flatten : 'a list list -> 'a list
```
Same as [`ListLabels.concat`](listlabels#VALconcat). Not tail-recursive (length of the argument + length of the longest sub-list).
Comparison
----------
```
val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool
```
`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`.
Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`ListLabels.compare_lengths`](listlabels#VALcompare_lengths) first.
* **Since** 4.12.0
```
val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int
```
`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`compare`](stdlib#VALcompare):
* `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2`
* the empty list `[]` is strictly smaller than non-empty lists
Note: the `cmp` function will be called even if the lists have different lengths.
* **Since** 4.12.0
Iterators
---------
```
val iter : f:('a -> unit) -> 'a list -> unit
```
`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`.
```
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
```
Same as [`ListLabels.iter`](listlabels#VALiter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
* **Since** 4.00.0
```
val map : f:('a -> 'b) -> 'a list -> 'b list
```
`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. Not tail-recursive.
```
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
```
Same as [`ListLabels.map`](listlabels#VALmap), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. Not tail-recursive.
* **Since** 4.00.0
```
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
```
`rev_map ~f l` gives the same result as [`ListLabels.rev`](listlabels#VALrev)`(`[`ListLabels.map`](listlabels#VALmap)`f l)`, but is tail-recursive and more efficient.
```
val filter_map : f:('a -> 'b option) -> 'a list -> 'b list
```
`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements.
* **Since** 4.08.0
```
val concat_map : f:('a -> 'b list) -> 'a list -> 'b list
```
`concat_map ~f l` gives the same result as [`ListLabels.concat`](listlabels#VALconcat)`(`[`ListLabels.map`](listlabels#VALmap)`f l)`. Tail-recursive.
* **Since** 4.10.0
```
val fold_left_map : f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b list -> 'a * 'c list
```
`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`.
* **Since** 4.11.0
```
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
```
`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`.
```
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
```
`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive.
Iterators on two lists
----------------------
```
val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
```
`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
```
`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
```
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
```
`rev_map2 ~f l1 l2` gives the same result as [`ListLabels.rev`](listlabels#VALrev)`(`[`ListLabels.map2`](listlabels#VALmap2)`f l1 l2)`, but is tail-recursive and more efficient.
```
val fold_left2 : f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
```
`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val fold_right2 : f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
```
`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
List scanning
-------------
```
val for_all : f:('a -> bool) -> 'a list -> bool
```
`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty.
```
val exists : f:('a -> bool) -> 'a list -> bool
```
`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty.
```
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
```
Same as [`ListLabels.for_all`](listlabels#VALfor_all), but for a two-argument predicate.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
```
Same as [`ListLabels.exists`](listlabels#VALexists), but for a two-argument predicate.
* **Raises** `Invalid_argument` if the two lists are determined to have different lengths.
```
val mem : 'a -> set:'a list -> bool
```
`mem a ~set` is true if and only if `a` is equal to an element of `set`.
```
val memq : 'a -> set:'a list -> bool
```
Same as [`ListLabels.mem`](listlabels#VALmem), but uses physical equality instead of structural equality to compare list elements.
List searching
--------------
```
val find : f:('a -> bool) -> 'a list -> 'a
```
`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`.
* **Raises** `Not_found` if there is no value that satisfies `f` in the list `l`.
```
val find_opt : f:('a -> bool) -> 'a list -> 'a option
```
`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`.
* **Since** 4.05
```
val find_map : f:('a -> 'b option) -> 'a list -> 'b option
```
`find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist.
* **Since** 4.10.0
```
val filter : f:('a -> bool) -> 'a list -> 'a list
```
`filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved.
```
val find_all : f:('a -> bool) -> 'a list -> 'a list
```
`find_all` is another name for [`ListLabels.filter`](listlabels#VALfilter).
```
val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list
```
Same as [`ListLabels.filter`](listlabels#VALfilter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.
* **Since** 4.11.0
```
val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
```
`partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved.
```
val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
```
`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`:
* if `f x` is `Left y1`, then `y1` is in `l1`, and
* if `f x` is `Right y2`, then `y2` is in `l2`.
The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`.
In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`.
* **Since** 4.12.0
Association lists
-----------------
```
val assoc : 'a -> ('a * 'b) list -> 'b
```
`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`.
* **Raises** `Not_found` if there is no value associated with `a` in the list `l`.
```
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
```
`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`.
* **Since** 4.05
```
val assq : 'a -> ('a * 'b) list -> 'b
```
Same as [`ListLabels.assoc`](listlabels#VALassoc), but uses physical equality instead of structural equality to compare keys.
```
val assq_opt : 'a -> ('a * 'b) list -> 'b option
```
Same as [`ListLabels.assoc_opt`](listlabels#VALassoc_opt), but uses physical equality instead of structural equality to compare keys.
* **Since** 4.05.0
```
val mem_assoc : 'a -> map:('a * 'b) list -> bool
```
Same as [`ListLabels.assoc`](listlabels#VALassoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key.
```
val mem_assq : 'a -> map:('a * 'b) list -> bool
```
Same as [`ListLabels.mem_assoc`](listlabels#VALmem_assoc), but uses physical equality instead of structural equality to compare keys.
```
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
```
`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive.
```
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
```
Same as [`ListLabels.remove_assoc`](listlabels#VALremove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive.
Lists of pairs
--------------
```
val split : ('a * 'b) list -> 'a list * 'b list
```
Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive.
```
val combine : 'a list -> 'b list -> ('a * 'b) list
```
Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`.
* **Raises** `Invalid_argument` if the two lists have different lengths. Not tail-recursive.
Sorting
-------
```
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`compare`](stdlib#VALcompare) is a suitable comparison function. The resulting list is sorted in increasing order. [`ListLabels.sort`](listlabels#VALsort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
```
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`ListLabels.sort`](listlabels#VALsort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.
```
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`ListLabels.sort`](listlabels#VALsort) or [`ListLabels.stable_sort`](listlabels#VALstable_sort), whichever is faster on typical input.
```
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
```
Same as [`ListLabels.sort`](listlabels#VALsort), but also remove duplicates.
* **Since** 4.03.0
```
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
```
Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments).
Lists and Sequences
-------------------
```
val to_seq : 'a list -> 'a Seq.t
```
Iterate on the list.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a list
```
Create a list from a sequence.
* **Since** 4.07
| programming_docs |
ocaml Module Gc.Memprof Module Gc.Memprof
=================
```
module Memprof: sig .. end
```
`Memprof` is a sampling engine for allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated.
Since blocks are composed of several words, a block can potentially be sampled several times. If a block is sampled several times, then each of the callback is called once for each event of this block: the multiplicity is given in the `n_samples` field of the `allocation` structure.
This engine makes it possible to implement a low-overhead memory profiler as an OCaml library.
Note: this API is EXPERIMENTAL. It may change without prior notice.
```
type allocation_source =
```
| | |
| --- | --- |
| `|` | `Normal` |
| `|` | `Marshal` |
| `|` | `Custom` |
```
type allocation = private {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `n\_samples : `int`;` | `(*` | The number of samples in this block (>= 1). | `*)` |
| | `size : `int`;` | `(*` | The size of the block, in words, excluding the header. | `*)` |
| | `source : `[allocation\_source](gc.memprof#TYPEallocation_source)`;` | `(*` | The type of the allocation. | `*)` |
| | `callstack : `[Printexc.raw\_backtrace](printexc#TYPEraw_backtrace)`;` | `(*` | The callstack for the allocation. | `*)` |
`}` The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation.
```
type ('minor, 'major) tracker = {
```
| | |
| --- | --- |
| | `alloc\_minor : `[allocation](gc.memprof#TYPEallocation) -> 'minor option`;` |
| | `alloc\_major : `[allocation](gc.memprof#TYPEallocation) -> 'major option`;` |
| | `promote : `'minor -> 'major option`;` |
| | `dealloc\_minor : `'minor -> unit`;` |
| | `dealloc\_major : `'major -> unit`;` |
`}` A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks.
When using threads, it is guaranteed that allocation callbacks are always run in the thread where the allocation takes place.
If an allocation-tracking or promotion-tracking function returns `None`, memprof stops tracking the corresponding value.
```
val null_tracker : ('minor, 'major) tracker
```
Default callbacks simply return `None` or `()`
```
val start : sampling_rate:float -> ?callstack_size:int -> ('minor, 'major) tracker -> unit
```
Start the sampling with the given parameters. Fails if sampling is already active.
The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower
The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max_int`.
The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap.
Sampling is temporarily disabled when calling a callback for the current thread. So they do not need to be re-entrant if the program is single-threaded. However, if threads are used, it is possible that a context switch occurs during a callback, in this case the callback functions must be re-entrant.
Note that the callback can be postponed slightly after the actual event. The callstack passed to the callback is always accurate, but the program state may have evolved.
```
val stop : unit -> unit
```
Stop the sampling. Fails if sampling is not active.
This function does not allocate memory.
All the already tracked blocks are discarded. If there are pending postponed callbacks, they may be discarded.
Calling `stop` when a callback is running can lead to callbacks not being called even though some events happened.
ocaml Module Result Module Result
=============
```
module Result: sig .. end
```
Result values.
Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions.
* **Since** 4.08
Results
-------
```
type ('a, 'e) t = ('a, 'e) result =
```
| | |
| --- | --- |
| `|` | `Ok of `'a`` |
| `|` | `Error of `'e`` |
The type for result values. Either a value `Ok v` or an error `Error e`.
```
val ok : 'a -> ('a, 'e) result
```
`ok v` is `Ok v`.
```
val error : 'e -> ('a, 'e) result
```
`error e` is `Error e`.
```
val value : ('a, 'e) result -> default:'a -> 'a
```
`value r ~default` is `v` if `r` is `Ok v` and `default` otherwise.
```
val get_ok : ('a, 'e) result -> 'a
```
`get_ok r` is `v` if `r` is `Ok v` and raise otherwise.
* **Raises** `Invalid_argument` if `r` is `Error _`.
```
val get_error : ('a, 'e) result -> 'e
```
`get_error r` is `e` if `r` is `Error e` and raise otherwise.
* **Raises** `Invalid_argument` if `r` is `Ok _`.
```
val bind : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result
```
`bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`.
```
val join : (('a, 'e) result, 'e) result -> ('a, 'e) result
```
`join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`.
```
val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result
```
`map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`.
```
val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result
```
`map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`.
```
val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c
```
`fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`.
```
val iter : ('a -> unit) -> ('a, 'e) result -> unit
```
`iter f r` is `f v` if `r` is `Ok v` and `()` otherwise.
```
val iter_error : ('e -> unit) -> ('a, 'e) result -> unit
```
`iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise.
Predicates and comparisons
--------------------------
```
val is_ok : ('a, 'e) result -> bool
```
`is_ok r` is `true` if and only if `r` is `Ok _`.
```
val is_error : ('a, 'e) result -> bool
```
`is_error r` is `true` if and only if `r` is `Error _`.
```
val equal : ok:('a -> 'a -> bool) -> error:('e -> 'e -> bool) -> ('a, 'e) result -> ('a, 'e) result -> bool
```
`equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`.
```
val compare : ok:('a -> 'a -> int) -> error:('e -> 'e -> int) -> ('a, 'e) result -> ('a, 'e) result -> int
```
`compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. `Ok _` values are smaller than `Error _` values.
Converting
----------
```
val to_option : ('a, 'e) result -> 'a option
```
`to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`.
```
val to_list : ('a, 'e) result -> 'a list
```
`to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise.
```
val to_seq : ('a, 'e) result -> 'a Seq.t
```
`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence.
ocaml Module Dynlink Module Dynlink
==============
```
module Dynlink: sig .. end
```
Dynamic loading of .cmo, .cma and .cmxs files.
```
val is_native : bool
```
`true` if the program is native, `false` if the program is bytecode.
Dynamic loading of compiled files
---------------------------------
```
val loadfile : string -> unit
```
In bytecode: load the given bytecode object file (`.cmo` file) or bytecode library file (`.cma` file), and link it with the running program. In native code: load the given OCaml plugin file (usually `.cmxs`), and link it with the running program.
All toplevel expressions in the loaded compilation units are evaluated. No facilities are provided to access value names defined by the unit. Therefore, the unit must itself register its entry points with the main program (or a previously-loaded library) e.g. by modifying tables of functions.
An exception will be raised if the given library defines toplevel modules whose names clash with modules existing either in the main program or a shared library previously loaded with `loadfile`. Modules from shared libraries previously loaded with `loadfile_private` are not included in this restriction.
The compilation units loaded by this function are added to the "allowed units" list (see [`Dynlink.set_allowed_units`](dynlink#VALset_allowed_units)).
```
val loadfile_private : string -> unit
```
Same as `loadfile`, except that the compilation units just loaded are hidden (cannot be referenced) from other modules dynamically loaded afterwards.
An exception will be raised if the given library defines toplevel modules whose names clash with modules existing in either the main program or a shared library previously loaded with `loadfile`. Modules from shared libraries previously loaded with `loadfile_private` are not included in this restriction.
An exception will also be raised if the given library defines toplevel modules whose name matches that of an interface depended on by a module existing in either the main program or a shared library previously loaded with `loadfile`. This applies even if such dependency is only a "module alias" dependency (i.e. just on the name rather than the contents of the interface).
The compilation units loaded by this function are not added to the "allowed units" list (see [`Dynlink.set_allowed_units`](dynlink#VALset_allowed_units)) since they cannot be referenced from other compilation units.
```
val adapt_filename : string -> string
```
In bytecode, the identity function. In native code, replace the last extension with `.cmxs`.
Access control
--------------
```
val set_allowed_units : string list -> unit
```
Set the list of compilation units that may be referenced from units that are dynamically loaded in the future to be exactly the given value.
Initially all compilation units composing the program currently running are available for reference from dynamically-linked units. `set_allowed_units` can be used to restrict access to a subset of these units, e.g. to the units that compose the API for dynamically-linked code, and prevent access to all other units, e.g. private, internal modules of the running program.
Note that [`Dynlink.loadfile`](dynlink#VALloadfile) changes the allowed-units list.
```
val allow_only : string list -> unit
```
`allow_only units` sets the list of allowed units to be the intersection of the existing allowed units and the given list of units. As such it can never increase the set of allowed units.
```
val prohibit : string list -> unit
```
`prohibit units` prohibits dynamically-linked units from referencing the units named in list `units` by removing such units from the allowed units list. This can be used to prevent access to selected units, e.g. private, internal modules of the running program.
```
val main_program_units : unit -> string list
```
Return the list of compilation units that form the main program (i.e. are not dynamically linked).
```
val public_dynamically_loaded_units : unit -> string list
```
Return the list of compilation units that have been dynamically loaded via `loadfile` (and not via `loadfile_private`). Note that compilation units loaded dynamically cannot be unloaded.
```
val all_units : unit -> string list
```
Return the list of compilation units that form the main program together with those that have been dynamically loaded via `loadfile` (and not via `loadfile_private`).
```
val allow_unsafe_modules : bool -> unit
```
Govern whether unsafe object files are allowed to be dynamically linked. A compilation unit is 'unsafe' if it contains declarations of external functions, which can break type safety. By default, dynamic linking of unsafe object files is not allowed. In native code, this function does nothing; object files with external functions are always allowed to be dynamically linked.
Error reporting
---------------
```
type linking_error = private
```
| | |
| --- | --- |
| `|` | `Undefined\_global of `string`` |
| `|` | `Unavailable\_primitive of `string`` |
| `|` | `Uninitialized\_global of `string`` |
```
type error = private
```
| | |
| --- | --- |
| `|` | `Not\_a\_bytecode\_file of `string`` |
| `|` | `Inconsistent\_import of `string`` |
| `|` | `Unavailable\_unit of `string`` |
| `|` | `Unsafe\_file` |
| `|` | `Linking\_error of `string * [linking\_error](dynlink#TYPElinking_error)`` |
| `|` | `Corrupted\_interface of `string`` |
| `|` | `Cannot\_open\_dynamic\_library of `exn`` |
| `|` | `Library's\_module\_initializers\_failed of `exn`` |
| `|` | `Inconsistent\_implementation of `string`` |
| `|` | `Module\_already\_loaded of `string`` |
| `|` | `Private\_library\_cannot\_implement\_interface of `string`` |
```
exception Error of error
```
Errors in dynamic linking are reported by raising the `Error` exception with a description of the error. A common case is the dynamic library not being found on the system: this is reported via `Cannot\_open\_dynamic\_library` (the enclosed exception may be platform-specific).
```
val error_message : error -> string
```
Convert an error description to a printable message.
ocaml Module Thread Module Thread
=============
```
module Thread: sig .. end
```
Lightweight threads for Posix `1003.1c` and Win32.
```
type t
```
The type of thread handles.
Thread creation and termination
-------------------------------
```
val create : ('a -> 'b) -> 'a -> t
```
`Thread.create funct arg` creates a new thread of control, in which the function application `funct arg` is executed concurrently with the other threads of the domain. The application of `Thread.create` returns the handle of the newly created thread. The new thread terminates when the application `funct arg` returns, either normally or by raising the [`Thread.Exit`](thread#EXCEPTIONExit) exception or by raising any other uncaught exception. In the last case, the uncaught exception is printed on standard error, but not propagated back to the parent thread. Similarly, the result of the application `funct arg` is discarded and not directly accessible to the parent thread.
See also [`Domain.spawn`](domain#VALspawn) if you want parallel execution instead.
```
val self : unit -> t
```
Return the handle for the thread currently executing.
```
val id : t -> int
```
Return the identifier of the given thread. A thread identifier is an integer that identifies uniquely the thread. It can be used to build data structures indexed by threads.
```
exception Exit
```
Exception raised by user code to initiate termination of the current thread. In a thread created by [`Thread.create`](thread#VALcreate) `funct` `arg`, if the [`Thread.Exit`](thread#EXCEPTIONExit) exception reaches the top of the application `funct arg`, it has the effect of terminating the current thread silently. In other contexts, there is no implicit handling of the [`Thread.Exit`](thread#EXCEPTIONExit) exception.
```
val exit : unit -> unit
```
Deprecated. Use 'raise Thread.Exit' instead. Raise the [`Thread.Exit`](thread#EXCEPTIONExit) exception. In a thread created by [`Thread.create`](thread#VALcreate), this will cause the thread to terminate prematurely, unless the thread function handles the exception itself. [`Fun.protect`](fun#VALprotect) finalizers and catch-all exception handlers will be executed.
To make it clear that an exception is raised and will trigger finalizers and catch-all exception handlers, it is recommended to write `raise Thread.Exit` instead of `Thread.exit ()`.
* **Before 5.0** A different implementation was used, not based on raising an exception, and not running finalizers and catch-all handlers. The previous implementation had a different behavior when called outside of a thread created by `Thread.create`.
Suspending threads
------------------
```
val delay : float -> unit
```
`delay d` suspends the execution of the calling thread for `d` seconds. The other program threads continue to run during this time.
```
val join : t -> unit
```
`join th` suspends the execution of the calling thread until the thread `th` has terminated.
```
val yield : unit -> unit
```
Re-schedule the calling thread without suspending it. This function can be used to give scheduling hints, telling the scheduler that now is a good time to switch to other threads.
Waiting for file descriptors or processes
-----------------------------------------
The functions below are leftovers from an earlier, VM-based threading system. The [`Unix`](unix) module provides equivalent functionality, in a more general and more standard-conformant manner. It is recommended to use [`Unix`](unix) functions directly.
```
val wait_timed_read : Unix.file_descr -> float -> bool
```
Deprecated. Use Unix.select instead. See [`Thread.wait_timed_write`](thread#VALwait_timed_write).
```
val wait_timed_write : Unix.file_descr -> float -> bool
```
Deprecated. Use Unix.select instead. Suspend the execution of the calling thread until at least one character or EOF is available for reading (`wait_timed_read`) or one character can be written without blocking (`wait_timed_write`) on the given Unix file descriptor. Wait for at most the amount of time given as second argument (in seconds). Return `true` if the file descriptor is ready for input/output and `false` if the timeout expired. The same functionality can be achieved with [`Unix.select`](unix#VALselect).
```
val select : Unix.file_descr list -> Unix.file_descr list -> Unix.file_descr list -> float -> Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
```
Deprecated. Use Unix.select instead. Same function as [`Unix.select`](unix#VALselect). Suspend the execution of the calling thread until input/output becomes possible on the given Unix file descriptors. The arguments and results have the same meaning as for [`Unix.select`](unix#VALselect).
```
val wait_pid : int -> int * Unix.process_status
```
Deprecated. Use Unix.waitpid instead. Same function as [`Unix.waitpid`](unix#VALwaitpid). `wait_pid p` suspends the execution of the calling thread until the process specified by the process identifier `p` terminates. Returns the pid of the child caught and its termination status, as per [`Unix.wait`](unix#VALwait).
Management of signals
---------------------
Signal handling follows the POSIX thread model: signals generated by a thread are delivered to that thread; signals generated externally are delivered to one of the threads that does not block it. Each thread possesses a set of blocked signals, which can be modified using [`Thread.sigmask`](thread#VALsigmask). This set is inherited at thread creation time. Per-thread signal masks are supported only by the system thread library under Unix, but not under Win32, nor by the VM thread library.
```
val sigmask : Unix.sigprocmask_command -> int list -> int list
```
`sigmask cmd sigs` changes the set of blocked signals for the calling thread. If `cmd` is `SIG\_SETMASK`, blocked signals are set to those in the list `sigs`. If `cmd` is `SIG\_BLOCK`, the signals in `sigs` are added to the set of blocked signals. If `cmd` is `SIG\_UNBLOCK`, the signals in `sigs` are removed from the set of blocked signals. `sigmask` returns the set of previously blocked signals for the thread.
```
val wait_signal : int list -> int
```
`wait_signal sigs` suspends the execution of the calling thread until the process receives one of the signals specified in the list `sigs`. It then returns the number of the signal received. Signal handlers attached to the signals in `sigs` will not be invoked. The signals `sigs` are expected to be blocked before calling `wait_signal`.
Uncaught exceptions
-------------------
```
val default_uncaught_exception_handler : exn -> unit
```
`Thread.default_uncaught_exception_handler` will print the thread's id, exception and backtrace (if available).
```
val set_uncaught_exception_handler : (exn -> unit) -> unit
```
`Thread.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions.
If the newly set uncaught exception handler raise an exception, [`Thread.default_uncaught_exception_handler`](thread#VALdefault_uncaught_exception_handler) will be called.
| programming_docs |
ocaml Module MoreLabels.Set Module MoreLabels.Set
=====================
```
module Set: sig .. end
```
Sets over ordered types.
This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.
The [`MoreLabels.Set.Make`](morelabels.set.make) functor constructs implementations for any type, given a `compare` function. For instance:
```
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
module PairsSet = Set.Make(IntPairs)
let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
```
This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`.
```
module type OrderedType = sig .. end
```
Input signature of the functor [`MoreLabels.Set.Make`](morelabels.set.make).
```
module type S = sig .. end
```
Output signature of the functor [`MoreLabels.Set.Make`](morelabels.set.make).
```
module Make: functor (Ord : OrderedType) -> S
with type elt = Ord.t
and type t = Set.Make(Ord).t
```
Functor building an implementation of the set structure given a totally ordered type.
ocaml Functor Weak.Make Functor Weak.Make
=================
```
module Make: functor (H : Hashtbl.HashedType) -> S with type data = H.t
```
Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[Hashtbl.HashedType](hashtbl.hashedtype)` |
|
```
type data
```
The type of the elements stored in the table.
```
type t
```
The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`output_value`](stdlib#VALoutput_value) or the functions of the [`Marshal`](marshal) module.
```
val create : int -> t
```
`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed.
```
val clear : t -> unit
```
Remove all elements from the table.
```
val merge : t -> data -> data
```
`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`.
```
val add : t -> data -> unit
```
`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`.
```
val remove : t -> data -> unit
```
`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`.
```
val find : t -> data -> data
```
`find t x` returns an instance of `x` found in `t`.
* **Raises** `Not_found` if there is no such element.
```
val find_opt : t -> data -> data option
```
`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element.
* **Since** 4.05
```
val find_all : t -> data -> data list
```
`find_all t x` returns a list of all the instances of `x` found in `t`.
```
val mem : t -> data -> bool
```
`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise.
```
val iter : (data -> unit) -> t -> unit
```
`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself.
```
val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
```
`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself.
```
val count : t -> int
```
Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements.
```
val stats : t -> int * int * int * int * int * int
```
Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length.
ocaml Module type Hashtbl.SeededS Module type Hashtbl.SeededS
===========================
```
module type SeededS = sig .. end
```
The output signature of the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
* **Since** 4.00.0
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
* **Since** 4.05.0
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val iter : (key -> 'a -> unit) -> 'a t -> unit
```
```
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit
```
* **Since** 4.03.0
```
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
* **Since** 4.07
```
val to_seq_keys : 'a t -> key Seq.t
```
* **Since** 4.07
```
val to_seq_values : 'a t -> 'a Seq.t
```
* **Since** 4.07
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
* **Since** 4.07
ocaml Module StdLabels.String Module StdLabels.String
=======================
```
module String: StringLabels
```
Strings
-------
```
type t = string
```
The type for strings.
```
val make : int -> char -> string
```
`make n c` is a string of length `n` with each index holding the character `c`.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val init : int -> f:(int -> char) -> string
```
`init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order).
* **Since** 4.02.0
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val empty : string
```
The empty string.
* **Since** 4.13.0
```
val of_bytes : bytes -> string
```
Return a new string that contains the same bytes as the given byte sequence.
* **Since** 4.13.0
```
val to_bytes : string -> bytes
```
Return a new byte sequence that contains the same bytes as the given string.
* **Since** 4.13.0
```
val length : string -> int
```
`length s` is the length (number of bytes/characters) of `s`.
```
val get : string -> int -> char
```
`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`.
* **Raises** `Invalid_argument` if `i` not an index of `s`.
Concatenating
-------------
**Note.** The [`(^)`](#) binary operator concatenates two strings.
```
val concat : sep:string -> string list -> string
```
`concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val cat : string -> string -> string
```
`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`).
* **Since** 4.13.0
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
Predicates and comparisons
--------------------------
```
val equal : t -> t -> bool
```
`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal.
* **Since** 4.05.0
```
val compare : t -> t -> int
```
`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`compare`](stdlib#VALcompare) on strings but may be more efficient.
```
val starts_with : prefix:string -> string -> bool
```
`starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`.
* **Since** 4.13.0
```
val ends_with : suffix:string -> string -> bool
```
`ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`.
* **Since** 4.13.0
```
val contains_from : string -> int -> char -> bool
```
`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`.
* **Raises** `Invalid_argument` if `start` is not a valid position in `s`.
```
val rcontains_from : string -> int -> char -> bool
```
`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`.
* **Raises** `Invalid_argument` if `stop < 0` or `stop+1` is not a valid position in `s`.
```
val contains : string -> char -> bool
```
`contains s c` is [`String.contains_from`](string#VALcontains_from)`s 0 c`.
Extracting substrings
---------------------
```
val sub : string -> pos:int -> len:int -> string
```
`sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid substring of `s`.
```
val split_on_char : sep:char -> string -> string list
```
`split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`.
The function's result is specified by the following invariants:
* The list is not empty.
* Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep)
(split_on_char sep s) = s`).
* No string in the result contains the `sep` character.
* **Since** 4.05.0
Transforming
------------
```
val map : f:(char -> char) -> string -> string
```
`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order.
* **Since** 4.00.0
```
val mapi : f:(int -> char -> char) -> string -> string
```
`mapi ~f s` is like [`StringLabels.map`](stringlabels#VALmap) but the index of the character is also passed to `f`.
* **Since** 4.02.0
```
val fold_left : f:('a -> char -> 'a) -> init:'a -> string -> 'a
```
`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`.
* **Since** 4.13.0
```
val fold_right : f:(char -> 'a -> 'a) -> string -> init:'a -> 'a
```
`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`.
* **Since** 4.13.0
```
val for_all : f:(char -> bool) -> string -> bool
```
`for_all p s` checks if all characters in `s` satisfy the predicate `p`.
* **Since** 4.13.0
```
val exists : f:(char -> bool) -> string -> bool
```
`exists p s` checks if at least one character of `s` satisfies the predicate `p`.
* **Since** 4.13.0
```
val trim : string -> string
```
`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`.
* **Since** 4.00.0
```
val escaped : string -> string
```
`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as backslash (0x2F) and double-quote (0x22).
The function [`Scanf.unescaped`](scanf#VALunescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails).
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val uppercase_ascii : string -> string
```
`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val lowercase_ascii : string -> string
```
`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val capitalize_ascii : string -> string
```
`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val uncapitalize_ascii : string -> string
```
`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
Traversing
----------
```
val iter : f:(char -> unit) -> string -> unit
```
`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`.
```
val iteri : f:(int -> char -> unit) -> string -> unit
```
`iteri` is like [`StringLabels.iter`](stringlabels#VALiter), but the function is also given the corresponding character index.
* **Since** 4.00.0
Searching
---------
```
val index_from : string -> int -> char -> int
```
`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`.
* **Raises**
+ `Not_found` if `c` does not occur in `s` after position `i`.
+ `Invalid_argument` if `i` is not a valid position in `s`.
```
val index_from_opt : string -> int -> char -> int option
```
`index_from_opt s i c` is the index of the first occurrence of `c` in `s` after position `i` (if any).
* **Since** 4.05
* **Raises** `Invalid_argument` if `i` is not a valid position in `s`.
```
val rindex_from : string -> int -> char -> int
```
`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`.
* **Raises**
+ `Not_found` if `c` does not occur in `s` before position `i+1`.
+ `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val rindex_from_opt : string -> int -> char -> int option
```
`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any).
* **Since** 4.05
* **Raises** `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val index : string -> char -> int
```
`index s c` is [`String.index_from`](string#VALindex_from)`s 0 c`.
```
val index_opt : string -> char -> int option
```
`index_opt s c` is [`String.index_from_opt`](string#VALindex_from_opt)`s 0 c`.
* **Since** 4.05
```
val rindex : string -> char -> int
```
`rindex s c` is [`String.rindex_from`](string#VALrindex_from)`s (length s - 1) c`.
```
val rindex_opt : string -> char -> int option
```
`rindex_opt s c` is [`String.rindex_from_opt`](string#VALrindex_from_opt)`s (length s - 1) c`.
* **Since** 4.05
Strings and Sequences
---------------------
```
val to_seq : t -> char Seq.t
```
`to_seq s` is a sequence made of the string's characters in increasing order. In `"unsafe-string"` mode, modifications of the string during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
`to_seqi s` is like [`StringLabels.to_seq`](stringlabels#VALto_seq) but also tuples the corresponding index.
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
`of_seq s` is a string made of the sequence's characters.
* **Since** 4.07
UTF decoding and validations
----------------------------
### UTF-8
```
val get_utf_8_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`.
```
val is_valid_utf_8 : t -> bool
```
`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data.
### UTF-16BE
```
val get_utf_16be_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`.
```
val is_valid_utf_16be : t -> bool
```
`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data.
### UTF-16LE
```
val get_utf_16le_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`.
```
val is_valid_utf_16le : t -> bool
```
`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data.
```
val blit : src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from the string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at character number `dst_pos`.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
Binary decoding of integers
---------------------------
The functions in this section binary decode integers from strings.
All following functions raise `Invalid\_argument` if the characters needed at index `i` to decode the integer are not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values.
```
val get_uint8 : string -> int -> int
```
`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int8 : string -> int -> int
```
`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_ne : string -> int -> int
```
`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_be : string -> int -> int
```
`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_uint16_le : string -> int -> int
```
`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_ne : string -> int -> int
```
`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_be : string -> int -> int
```
`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int16_le : string -> int -> int
```
`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int32_ne : string -> int -> int32
```
`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val hash : t -> int
```
An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](hashtbl#VALhash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](hashtbl.make).
* **Since** 5.0.0
```
val seeded_hash : int -> t -> int
```
A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](hashtbl#VALseeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
* **Since** 5.0.0
```
val get_int32_be : string -> int -> int32
```
`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int32_le : string -> int -> int32
```
`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_ne : string -> int -> int64
```
`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_be : string -> int -> int64
```
`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
```
val get_int64_le : string -> int -> int64
```
`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`.
* **Since** 4.13.0
| programming_docs |
ocaml Module Set Module Set
==========
```
module Set: sig .. end
```
Sets over ordered types.
This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.
The [`Set.Make`](set.make) functor constructs implementations for any type, given a `compare` function. For instance:
```
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
module PairsSet = Set.Make(IntPairs)
let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
```
This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`.
```
module type OrderedType = sig .. end
```
Input signature of the functor [`Set.Make`](set.make).
```
module type S = sig .. end
```
Output signature of the functor [`Set.Make`](set.make).
```
module Make: functor (Ord : OrderedType) -> S with type elt = Ord.t
```
Functor building an implementation of the set structure given a totally ordered type.
ocaml Module MoreLabels Module MoreLabels
=================
```
module MoreLabels: sig .. end
```
Extra labeled libraries.
This meta-module provides labelized versions of the [`MoreLabels.Hashtbl`](morelabels.hashtbl), [`MoreLabels.Map`](morelabels.map) and [`MoreLabels.Set`](morelabels.set) modules.
This module is intended to be used through `open MoreLabels` which replaces [`MoreLabels.Hashtbl`](morelabels.hashtbl), [`MoreLabels.Map`](morelabels.map), and [`MoreLabels.Set`](morelabels.set) with their labeled counterparts.
For example:
```
open MoreLabels
Hashtbl.iter ~f:(fun ~key ~data -> g key data) table
```
```
module Hashtbl: sig .. end
```
```
module Map: sig .. end
```
```
module Set: sig .. end
```
ocaml Module StdLabels.Bytes Module StdLabels.Bytes
======================
```
module Bytes: BytesLabels
```
```
val length : bytes -> int
```
Return the length (number of bytes) of the argument.
```
val get : bytes -> int -> char
```
`get s n` returns the byte at index `n` in argument `s`.
* **Raises** `Invalid_argument` if `n` is not a valid index in `s`.
```
val set : bytes -> int -> char -> unit
```
`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`.
* **Raises** `Invalid_argument` if `n` is not a valid index in `s`.
```
val create : int -> bytes
```
`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val make : int -> char -> bytes
```
`make n c` returns a new byte sequence of length `n`, filled with the byte `c`.
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val init : int -> f:(int -> char) -> bytes
```
`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order).
* **Raises** `Invalid_argument` if `n < 0` or `n >`[`Sys.max_string_length`](sys#VALmax_string_length).
```
val empty : bytes
```
A byte sequence of size 0.
```
val copy : bytes -> bytes
```
Return a new byte sequence that contains the same bytes as the argument.
```
val of_string : string -> bytes
```
Return a new byte sequence that contains the same bytes as the given string.
```
val to_string : bytes -> string
```
Return a new string that contains the same bytes as the given byte sequence.
```
val sub : bytes -> pos:int -> len:int -> bytes
```
`sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `s`.
```
val sub_string : bytes -> pos:int -> len:int -> string
```
Same as [`BytesLabels.sub`](byteslabels#VALsub) but return a string instead of a byte sequence.
```
val extend : bytes -> left:int -> right:int -> bytes
```
`extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if the result length is negative or longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val fill : bytes -> pos:int -> len:int -> char -> unit
```
`fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`.
* **Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `s`.
```
val blit : src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from sequence `src`, starting at index `src_pos`, to sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap.
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
```
val blit_string : src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
```
`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid range of `src`, or if `dst_pos` and `len` do not designate a valid range of `dst`.
```
val concat : sep:bytes -> bytes list -> bytes
```
`concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val cat : bytes -> bytes -> bytes
```
`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence.
* **Since** 4.05.0 in BytesLabels
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val iter : f:(char -> unit) -> bytes -> unit
```
`iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s
(length s - 1)); ()`.
```
val iteri : f:(int -> char -> unit) -> bytes -> unit
```
Same as [`BytesLabels.iter`](byteslabels#VALiter), but the function is applied to the index of the byte as first argument and the byte itself as second argument.
```
val map : f:(char -> char) -> bytes -> bytes
```
`map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
```
val mapi : f:(int -> char -> char) -> bytes -> bytes
```
`mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
```
val fold_left : f:('a -> char -> 'a) -> init:'a -> bytes -> 'a
```
`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`.
* **Since** 4.13.0
```
val fold_right : f:(char -> 'a -> 'a) -> bytes -> init:'a -> 'a
```
`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`.
* **Since** 4.13.0
```
val for_all : f:(char -> bool) -> bytes -> bool
```
`for_all p s` checks if all characters in `s` satisfy the predicate `p`.
* **Since** 4.13.0
```
val exists : f:(char -> bool) -> bytes -> bool
```
`exists p s` checks if at least one character of `s` satisfies the predicate `p`.
* **Since** 4.13.0
```
val trim : bytes -> bytes
```
Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`.
```
val escaped : bytes -> bytes
```
Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote.
* **Raises** `Invalid_argument` if the result is longer than [`Sys.max_string_length`](sys#VALmax_string_length) bytes.
```
val index : bytes -> char -> int
```
`index s c` returns the index of the first occurrence of byte `c` in `s`.
* **Raises** `Not_found` if `c` does not occur in `s`.
```
val index_opt : bytes -> char -> int option
```
`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`.
* **Since** 4.05
```
val rindex : bytes -> char -> int
```
`rindex s c` returns the index of the last occurrence of byte `c` in `s`.
* **Raises** `Not_found` if `c` does not occur in `s`.
```
val rindex_opt : bytes -> char -> int option
```
`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`.
* **Since** 4.05
```
val index_from : bytes -> int -> char -> int
```
`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`.
* **Raises**
+ `Invalid_argument` if `i` is not a valid position in `s`.
+ `Not_found` if `c` does not occur in `s` after position `i`.
```
val index_from_opt : bytes -> int -> char -> int option
```
`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`.
* **Since** 4.05
* **Raises** `Invalid_argument` if `i` is not a valid position in `s`.
```
val rindex_from : bytes -> int -> char -> int
```
`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`.
* **Raises**
+ `Invalid_argument` if `i+1` is not a valid position in `s`.
+ `Not_found` if `c` does not occur in `s` before position `i+1`.
```
val rindex_from_opt : bytes -> int -> char -> int option
```
`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`.
* **Since** 4.05
* **Raises** `Invalid_argument` if `i+1` is not a valid position in `s`.
```
val contains : bytes -> char -> bool
```
`contains s c` tests if byte `c` appears in `s`.
```
val contains_from : bytes -> int -> char -> bool
```
`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from
s 0 c`.
* **Raises** `Invalid_argument` if `start` is not a valid position in `s`.
```
val rcontains_from : bytes -> int -> char -> bool
```
`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`.
* **Raises** `Invalid_argument` if `stop < 0` or `stop+1` is not a valid position in `s`.
```
val uppercase_ascii : bytes -> bytes
```
Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val lowercase_ascii : bytes -> bytes
```
Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val capitalize_ascii : bytes -> bytes
```
Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set.
* **Since** 4.05.0
```
val uncapitalize_ascii : bytes -> bytes
```
Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set.
* **Since** 4.05.0
```
type t = bytes
```
An alias for the type of byte sequences.
```
val compare : t -> t -> int
```
The comparison function for byte sequences, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val equal : t -> t -> bool
```
The equality function for byte sequences.
* **Since** 4.05.0
```
val starts_with : prefix:bytes -> bytes -> bool
```
`starts_with``~prefix s` is `true` if and only if `s` starts with `prefix`.
* **Since** 4.13.0
```
val ends_with : suffix:bytes -> bytes -> bool
```
`ends_with``~suffix s` is `true` if and only if `s` ends with `suffix`.
* **Since** 4.13.0
Unsafe conversions (for advanced users)
---------------------------------------
This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings provided by the `-safe-string` option. They are available for expert library authors, but for most purposes you should use the always-correct [`BytesLabels.to_string`](byteslabels#VALto_string) and [`BytesLabels.of_string`](byteslabels#VALof_string) instead.
```
val unsafe_to_string : bytes -> string
```
Unsafely convert a byte sequence into a string.
To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including:
* Unique ownership: the data may be accessed and mutated
* Shared ownership: the data has several owners, that may only access it, not mutate it.
Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again.
`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` -- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string.
There are two valid use-cases that respect this ownership discipline:
1. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed.
```
let string_init len f : string =
let s = Bytes.create len in
for i = 0 to len - 1 do Bytes.set s i (f i) done;
Bytes.unsafe_to_string s
```
This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller.
Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future -- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely.
We have provided the [`String.init`](string#VALinit), [`String.map`](string#VALmap) and [`String.mapi`](string#VALmapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable.
2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended.
```
let bytes_length (s : bytes) =
String.length (Bytes.unsafe_to_string s)
```
In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](string#VALlength) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](string#VALlength) does not capture its argument -- it could escape by a side-channel such as a memoization combinator.
The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](string#VALlength) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership.
```
val unsafe_of_string : string -> bytes
```
Unsafely convert a shared string to a byte sequence that should not be mutated.
The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode.
In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned.
For example, string literals are implicitly shared by the compiler, so you never uniquely own them.
```
let incorrect = Bytes.unsafe_of_string "hello"
let s = Bytes.of_string "hello"
```
The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct.
Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` -- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`.
The only case we have reasonable confidence is safe is if the produced `bytes` is shared -- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](marshal#VALfrom_bytes)) and previously used the `string` type for this purpose.
```
val split_on_char : sep:char -> bytes -> bytes list
```
`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character.
The function's output is specified by the following invariants:
* The list is not empty.
* Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep)
(Bytes.split_on_char sep s) = s`).
* No byte sequence in the result contains the `sep` character.
* **Since** 4.13.0
Iterators
---------
```
val to_seq : t -> char Seq.t
```
Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence.
* **Since** 4.07
```
val to_seqi : t -> (int * char) Seq.t
```
Iterate on the string, in increasing order, yielding indices along chars
* **Since** 4.07
```
val of_seq : char Seq.t -> t
```
Create a string from the generator
* **Since** 4.07
UTF codecs and validations
--------------------------
### UTF-8
```
val get_utf_8_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_8_uchar b i` decodes an UTF-8 character at index `i` in `b`.
```
val set_utf_8_uchar : t -> int -> Uchar.t -> int
```
`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_8 : t -> bool
```
`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data.
### UTF-16BE
```
val get_utf_16be_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16be_uchar b i` decodes an UTF-16BE character at index `i` in `b`.
```
val set_utf_16be_uchar : t -> int -> Uchar.t -> int
```
`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_16be : t -> bool
```
`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data.
### UTF-16LE
```
val get_utf_16le_uchar : t -> int -> Uchar.utf_decode
```
`get_utf_16le_uchar b i` decodes an UTF-16LE character at index `i` in `b`.
```
val set_utf_16le_uchar : t -> int -> Uchar.t -> int
```
`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`.
```
val is_valid_utf_16le : t -> bool
```
`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data.
Binary encoding/decoding of integers
------------------------------------
The functions in this section binary encode and decode integers to and from byte sequences.
All following functions raise `Invalid\_argument` if the space needed at index `i` to decode or encode the integer is not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](sys#VALbig_endian).
32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows:
* Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result.
* Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes.
```
val get_uint8 : bytes -> int -> int
```
`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int8 : bytes -> int -> int
```
`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_ne : bytes -> int -> int
```
`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_be : bytes -> int -> int
```
`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_uint16_le : bytes -> int -> int
```
`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_ne : bytes -> int -> int
```
`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_be : bytes -> int -> int
```
`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int16_le : bytes -> int -> int
```
`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_ne : bytes -> int -> int32
```
`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_be : bytes -> int -> int32
```
`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int32_le : bytes -> int -> int32
```
`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_ne : bytes -> int -> int64
```
`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_be : bytes -> int -> int64
```
`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val get_int64_le : bytes -> int -> int64
```
`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`.
* **Since** 4.08
```
val set_uint8 : bytes -> int -> int -> unit
```
`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int8 : bytes -> int -> int -> unit
```
`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_ne : bytes -> int -> int -> unit
```
`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_be : bytes -> int -> int -> unit
```
`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_uint16_le : bytes -> int -> int -> unit
```
`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_ne : bytes -> int -> int -> unit
```
`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_be : bytes -> int -> int -> unit
```
`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int16_le : bytes -> int -> int -> unit
```
`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_ne : bytes -> int -> int32 -> unit
```
`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_be : bytes -> int -> int32 -> unit
```
`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int32_le : bytes -> int -> int32 -> unit
```
`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_ne : bytes -> int -> int64 -> unit
```
`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_be : bytes -> int -> int64 -> unit
```
`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
```
val set_int64_le : bytes -> int -> int64 -> unit
```
`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`.
* **Since** 4.08
Byte sequences and concurrency safety
-------------------------------------
Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.
### Atomicity
Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning.
For example, consider the following program:
```
let size = 100_000_000
let b = Bytes.make size ' '
let update b f () =
Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b
let d1 = Domain.spawn (update b (fun x -> x + 1))
let d2 = Domain.spawn (update b (fun x -> 2 * x + 1))
let () = Domain.join d1; Domain.join d2
```
the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values.
After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](mutex#TYPEt)).
### Data races
If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location.
### Mixed-size accesses
Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index
```
let b = Bytes.make 10 '\000'
let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' )
```
In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`.
| programming_docs |
ocaml Module Ephemeron.K1 Module Ephemeron.K1
===================
```
module K1: sig .. end
```
Ephemerons with one key.
```
type ('k, 'd) t
```
an ephemeron with one key
```
val make : 'k -> 'd -> ('k, 'd) t
```
`Ephemeron.K1.make k d` creates an ephemeron with key `k` and data `d`.
```
val query : ('k, 'd) t -> 'k -> 'd option
```
`Ephemeron.K1.query eph key` returns `Some x` (where `x` is the ephemeron's data) if `key` is physically equal to `eph`'s key, and `None` if `eph` is empty or `key` is not equal to `eph`'s key.
```
module Make: functor (H : Hashtbl.HashedType) -> Ephemeron.S with type key = H.t
```
Functor building an implementation of a weak hash table
```
module MakeSeeded: functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H.t
```
Functor building an implementation of a weak hash table.
```
module Bucket: sig .. end
```
ocaml Module type MoreLabels.Map.S Module type MoreLabels.Map.S
============================
```
module type S = sig .. end
```
Output signature of the functor [`MoreLabels.Map.Make`](morelabels.map.make).
```
type key
```
The type of the map keys.
```
type +'a t
```
The type of maps from type `key` to type `'a`.
```
val empty : 'a t
```
The empty map.
```
val is_empty : 'a t -> bool
```
Test whether a map is empty or not.
```
val mem : key -> 'a t -> bool
```
`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise.
```
val add : key:key -> data:'a -> 'a t -> 'a t
```
`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears.
* **Before 4.03** Physical equality was not ensured.
```
val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t
```
`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Since** 4.06.0
```
val singleton : key -> 'a -> 'a t
```
`singleton x y` returns the one-element map that contains a binding `y` for `x`.
* **Since** 3.12.0
```
val remove : key -> 'a t -> 'a t
```
`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Before 4.03** Physical equality was not ensured.
```
val merge : f:(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
```
`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`.
* **Since** 3.12.0
```
val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
```
`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where
* `f' _key None None = None`
* `f' _key (Some v) None = Some v`
* `f' _key None (Some v) = Some v`
* `f' key (Some v1) (Some v2) = f key v1 v2`
* **Since** 4.03.0
```
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
```
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
```
val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
```
`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys.
```
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
```
`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
```
`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data.
```
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
```
`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`.
* **Since** 3.12.0
```
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
```
`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`.
* **Since** 3.12.0
```
val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t
```
`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`)
* **Before 4.03** Physical equality was not ensured.
* **Since** 3.12.0
```
val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t
```
`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map:
* if `f k v` is `None` then `k` is not in the result,
* if `f k v` is `Some v'` then the binding `(k, v')` is in the output map.
For example, the following function on maps whose values are lists
```
filter_map
(fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
```
drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty.
* **Since** 4.11.0
```
val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t
```
`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`.
* **Since** 3.12.0
```
val cardinal : 'a t -> int
```
Return the number of bindings of a map.
* **Since** 3.12.0
```
val bindings : 'a t -> (key * 'a) list
```
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`MoreLabels.Map.Make`](morelabels.map.make).
* **Since** 3.12.0
```
val min_binding : 'a t -> key * 'a
```
Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the map is empty.
* **Since** 3.12.0
```
val min_binding_opt : 'a t -> (key * 'a) option
```
Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty.
* **Since** 4.05
```
val max_binding : 'a t -> key * 'a
```
Same as [`MoreLabels.Map.S.min_binding`](morelabels.map.s#VALmin_binding), but returns the binding with the largest key in the given map.
* **Since** 3.12.0
```
val max_binding_opt : 'a t -> (key * 'a) option
```
Same as [`MoreLabels.Map.S.min_binding_opt`](morelabels.map.s#VALmin_binding_opt), but returns the binding with the largest key in the given map.
* **Since** 4.05
```
val choose : 'a t -> key * 'a
```
Return one binding of the given map, or raise `Not\_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 3.12.0
```
val choose_opt : 'a t -> (key * 'a) option
```
Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 4.05
```
val split : key -> 'a t -> 'a t * 'a option * 'a t
```
`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`.
* **Since** 3.12.0
```
val find : key -> 'a t -> 'a
```
`find x m` returns the current value of `x` in `m`, or raises `Not\_found` if no binding for `x` exists.
```
val find_opt : key -> 'a t -> 'a option
```
`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists.
* **Since** 4.05
```
val find_first : f:(key -> bool) -> 'a t -> key * 'a
```
`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not\_found` if `x` is greater than any element of `m`.
* **Since** 4.05
```
val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
```
`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val find_last : f:(key -> bool) -> 'a t -> key * 'a
```
`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
* **Since** 4.05
```
val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
```
`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val map : f:('a -> 'b) -> 'a t -> 'b t
```
`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
```
Same as [`MoreLabels.Map.S.map`](morelabels.map.s#VALmap), but the function receives as arguments both the key and the associated value for each binding of the map.
Maps and Sequences
------------------
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in ascending order of keys
* **Since** 4.07
```
val to_rev_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in descending order of keys
* **Since** 4.12
```
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
```
`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above.
* **Since** 4.07
```
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
```
Add the given bindings to the map, in order.
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
Build a map from the given bindings
* **Since** 4.07
ocaml Module Complex Module Complex
==============
```
module Complex: sig .. end
```
Complex numbers.
This module provides arithmetic operations on complex numbers. Complex numbers are represented by their real and imaginary parts (cartesian representation). Each part is represented by a double-precision floating-point number (type `float`).
```
type t = {
```
| | |
| --- | --- |
| | `re : `float`;` |
| | `im : `float`;` |
`}` The type of complex numbers. `re` is the real part and `im` the imaginary part.
```
val zero : t
```
The complex number `0`.
```
val one : t
```
The complex number `1`.
```
val i : t
```
The complex number `i`.
```
val neg : t -> t
```
Unary negation.
```
val conj : t -> t
```
Conjugate: given the complex `x + i.y`, returns `x - i.y`.
```
val add : t -> t -> t
```
Addition
```
val sub : t -> t -> t
```
Subtraction
```
val mul : t -> t -> t
```
Multiplication
```
val inv : t -> t
```
Multiplicative inverse (`1/z`).
```
val div : t -> t -> t
```
Division
```
val sqrt : t -> t
```
Square root. The result `x + i.y` is such that `x > 0` or `x = 0` and `y >= 0`. This function has a discontinuity along the negative real axis.
```
val norm2 : t -> float
```
Norm squared: given `x + i.y`, returns `x^2 + y^2`.
```
val norm : t -> float
```
Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`.
```
val arg : t -> float
```
Argument. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle ranges from `-pi` to `pi`. This function has a discontinuity along the negative real axis.
```
val polar : float -> float -> t
```
`polar norm arg` returns the complex having norm `norm` and argument `arg`.
```
val exp : t -> t
```
Exponentiation. `exp z` returns `e` to the `z` power.
```
val log : t -> t
```
Natural logarithm (in base `e`).
```
val pow : t -> t -> t
```
Power function. `pow z1 z2` returns `z1` to the `z2` power.
ocaml Module Nativeint Module Nativeint
================
```
module Nativeint: sig .. end
```
Processor-native integers.
This module provides operations on the type `nativeint` of signed 32-bit integers (on 32-bit platforms) or signed 64-bit integers (on 64-bit platforms). This integer type has exactly the same width as that of a pointer type in the C compiler. All arithmetic operations over `nativeint` are taken modulo 232 or 264 depending on the word size of the architecture.
Performance notice: values of type `nativeint` occupy more memory space than values of type `int`, and arithmetic operations on `nativeint` are generally slower than those on `int`. Use `nativeint` only when the application requires the extra bit of precision over the `int` type.
Literals for native integers are suffixed by n:
```
let zero: nativeint = 0n
let one: nativeint = 1n
let m_one: nativeint = -1n
```
```
val zero : nativeint
```
The native integer 0.
```
val one : nativeint
```
The native integer 1.
```
val minus_one : nativeint
```
The native integer -1.
```
val neg : nativeint -> nativeint
```
Unary negation.
```
val add : nativeint -> nativeint -> nativeint
```
Addition.
```
val sub : nativeint -> nativeint -> nativeint
```
Subtraction.
```
val mul : nativeint -> nativeint -> nativeint
```
Multiplication.
```
val div : nativeint -> nativeint -> nativeint
```
Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`(/)`](stdlib#VAL(/)).
* **Raises** `Division_by_zero` if the second argument is zero.
```
val unsigned_div : nativeint -> nativeint -> nativeint
```
Same as [`Nativeint.div`](nativeint#VALdiv), except that arguments and result are interpreted as *unsigned* native integers.
* **Since** 4.08.0
```
val rem : nativeint -> nativeint -> nativeint
```
Integer remainder. If `y` is not zero, the result of `Nativeint.rem x y` satisfies the following properties: `Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y` and `x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y)
(Nativeint.rem x y)`. If `y = 0`, `Nativeint.rem x y` raises `Division\_by\_zero`.
```
val unsigned_rem : nativeint -> nativeint -> nativeint
```
Same as [`Nativeint.rem`](nativeint#VALrem), except that arguments and result are interpreted as *unsigned* native integers.
* **Since** 4.08.0
```
val succ : nativeint -> nativeint
```
Successor. `Nativeint.succ x` is `Nativeint.add x Nativeint.one`.
```
val pred : nativeint -> nativeint
```
Predecessor. `Nativeint.pred x` is `Nativeint.sub x Nativeint.one`.
```
val abs : nativeint -> nativeint
```
`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.
```
val size : int
```
The size in bits of a native integer. This is equal to `32` on a 32-bit platform and to `64` on a 64-bit platform.
```
val max_int : nativeint
```
The greatest representable native integer, either 231 - 1 on a 32-bit platform, or 263 - 1 on a 64-bit platform.
```
val min_int : nativeint
```
The smallest representable native integer, either -231 on a 32-bit platform, or -263 on a 64-bit platform.
```
val logand : nativeint -> nativeint -> nativeint
```
Bitwise logical and.
```
val logor : nativeint -> nativeint -> nativeint
```
Bitwise logical or.
```
val logxor : nativeint -> nativeint -> nativeint
```
Bitwise logical exclusive or.
```
val lognot : nativeint -> nativeint
```
Bitwise logical negation.
```
val shift_left : nativeint -> int -> nativeint
```
`Nativeint.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= bitsize`, where `bitsize` is `32` on a 32-bit platform and `64` on a 64-bit platform.
```
val shift_right : nativeint -> int -> nativeint
```
`Nativeint.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= bitsize`.
```
val shift_right_logical : nativeint -> int -> nativeint
```
`Nativeint.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= bitsize`.
```
val of_int : int -> nativeint
```
Convert the given integer (type `int`) to a native integer (type `nativeint`).
```
val to_int : nativeint -> int
```
Convert the given native integer (type `nativeint`) to an integer (type `int`). The high-order bit is lost during the conversion.
```
val unsigned_to_int : nativeint -> int option
```
Same as [`Nativeint.to_int`](nativeint#VALto_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`.
* **Since** 4.08.0
```
val of_float : float -> nativeint
```
Convert the given floating-point number to a native integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range [[`Nativeint.min_int`](nativeint#VALmin_int), [`Nativeint.max_int`](nativeint#VALmax_int)], no exception is raised, and an unspecified, platform-dependent integer is returned.
```
val to_float : nativeint -> float
```
Convert the given native integer to a floating-point number.
```
val of_int32 : int32 -> nativeint
```
Convert the given 32-bit integer (type `int32`) to a native integer.
```
val to_int32 : nativeint -> int32
```
Convert the given native integer to a 32-bit integer (type `int32`). On 64-bit platforms, the 64-bit native integer is taken modulo 232, i.e. the top 32 bits are lost. On 32-bit platforms, the conversion is exact.
```
val of_string : string -> nativeint
```
Convert the given string to a native integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.
The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Nativeint.max_int+1]`. If the input exceeds [`Nativeint.max_int`](nativeint#VALmax_int) it is converted to the signed integer `Int64.min_int + input - Nativeint.max_int - 1`.
* **Raises** `Failure` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `nativeint`.
```
val of_string_opt : string -> nativeint option
```
Same as `of_string`, but return `None` instead of raising.
* **Since** 4.05
```
val to_string : nativeint -> string
```
Return the string representation of its argument, in decimal.
```
type t = nativeint
```
An alias for the type of native integers.
```
val compare : t -> t -> int
```
The comparison function for native integers, with the same specification as [`compare`](stdlib#VALcompare). Along with the type `t`, this function `compare` allows the module `Nativeint` to be passed as argument to the functors [`Set.Make`](set.make) and [`Map.Make`](map.make).
```
val unsigned_compare : t -> t -> int
```
Same as [`Nativeint.compare`](nativeint#VALcompare), except that arguments are interpreted as *unsigned* native integers.
* **Since** 4.08.0
```
val equal : t -> t -> bool
```
The equal function for native ints.
* **Since** 4.03.0
```
val min : t -> t -> t
```
Return the smaller of the two arguments.
* **Since** 4.13.0
```
val max : t -> t -> t
```
Return the greater of the two arguments.
* **Since** 4.13.0
| programming_docs |
ocaml Module type Map.OrderedType Module type Map.OrderedType
===========================
```
module type OrderedType = sig .. end
```
Input signature of the functor [`Map.Make`](map.make).
```
type t
```
The type of the map keys.
```
val compare : t -> t -> int
```
A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`compare`](stdlib#VALcompare).
ocaml Module UnixLabels Module UnixLabels
=================
```
module UnixLabels: sig .. end
```
Interface to the Unix system.
To use the labeled version of this module, add `module Unix``=``UnixLabels` in your implementation.
Note: all the functions of this module (except [`UnixLabels.error_message`](unixlabels#VALerror_message) and [`UnixLabels.handle_unix_error`](unixlabels#VALhandle_unix_error)) are liable to raise the [`UnixLabels.Unix\_error`](unixlabels#EXCEPTIONUnix_error) exception whenever the underlying system call signals an error.
Error report
------------
```
type error = Unix.error =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `E2BIG` | `(*` | Argument list too long | `*)` |
| `|` | `EACCES` | `(*` | Permission denied | `*)` |
| `|` | `EAGAIN` | `(*` | Resource temporarily unavailable; try again | `*)` |
| `|` | `EBADF` | `(*` | Bad file descriptor | `*)` |
| `|` | `EBUSY` | `(*` | Resource unavailable | `*)` |
| `|` | `ECHILD` | `(*` | No child process | `*)` |
| `|` | `EDEADLK` | `(*` | Resource deadlock would occur | `*)` |
| `|` | `EDOM` | `(*` | Domain error for math functions, etc. | `*)` |
| `|` | `EEXIST` | `(*` | File exists | `*)` |
| `|` | `EFAULT` | `(*` | Bad address | `*)` |
| `|` | `EFBIG` | `(*` | File too large | `*)` |
| `|` | `EINTR` | `(*` | Function interrupted by signal | `*)` |
| `|` | `EINVAL` | `(*` | Invalid argument | `*)` |
| `|` | `EIO` | `(*` | Hardware I/O error | `*)` |
| `|` | `EISDIR` | `(*` | Is a directory | `*)` |
| `|` | `EMFILE` | `(*` | Too many open files by the process | `*)` |
| `|` | `EMLINK` | `(*` | Too many links | `*)` |
| `|` | `ENAMETOOLONG` | `(*` | Filename too long | `*)` |
| `|` | `ENFILE` | `(*` | Too many open files in the system | `*)` |
| `|` | `ENODEV` | `(*` | No such device | `*)` |
| `|` | `ENOENT` | `(*` | No such file or directory | `*)` |
| `|` | `ENOEXEC` | `(*` | Not an executable file | `*)` |
| `|` | `ENOLCK` | `(*` | No locks available | `*)` |
| `|` | `ENOMEM` | `(*` | Not enough memory | `*)` |
| `|` | `ENOSPC` | `(*` | No space left on device | `*)` |
| `|` | `ENOSYS` | `(*` | Function not supported | `*)` |
| `|` | `ENOTDIR` | `(*` | Not a directory | `*)` |
| `|` | `ENOTEMPTY` | `(*` | Directory not empty | `*)` |
| `|` | `ENOTTY` | `(*` | Inappropriate I/O control operation | `*)` |
| `|` | `ENXIO` | `(*` | No such device or address | `*)` |
| `|` | `EPERM` | `(*` | Operation not permitted | `*)` |
| `|` | `EPIPE` | `(*` | Broken pipe | `*)` |
| `|` | `ERANGE` | `(*` | Result too large | `*)` |
| `|` | `EROFS` | `(*` | Read-only file system | `*)` |
| `|` | `ESPIPE` | `(*` | Invalid seek e.g. on a pipe | `*)` |
| `|` | `ESRCH` | `(*` | No such process | `*)` |
| `|` | `EXDEV` | `(*` | Invalid link | `*)` |
| `|` | `EWOULDBLOCK` | `(*` | Operation would block | `*)` |
| `|` | `EINPROGRESS` | `(*` | Operation now in progress | `*)` |
| `|` | `EALREADY` | `(*` | Operation already in progress | `*)` |
| `|` | `ENOTSOCK` | `(*` | Socket operation on non-socket | `*)` |
| `|` | `EDESTADDRREQ` | `(*` | Destination address required | `*)` |
| `|` | `EMSGSIZE` | `(*` | Message too long | `*)` |
| `|` | `EPROTOTYPE` | `(*` | Protocol wrong type for socket | `*)` |
| `|` | `ENOPROTOOPT` | `(*` | Protocol not available | `*)` |
| `|` | `EPROTONOSUPPORT` | `(*` | Protocol not supported | `*)` |
| `|` | `ESOCKTNOSUPPORT` | `(*` | Socket type not supported | `*)` |
| `|` | `EOPNOTSUPP` | `(*` | Operation not supported on socket | `*)` |
| `|` | `EPFNOSUPPORT` | `(*` | Protocol family not supported | `*)` |
| `|` | `EAFNOSUPPORT` | `(*` | Address family not supported by protocol family | `*)` |
| `|` | `EADDRINUSE` | `(*` | Address already in use | `*)` |
| `|` | `EADDRNOTAVAIL` | `(*` | Can't assign requested address | `*)` |
| `|` | `ENETDOWN` | `(*` | Network is down | `*)` |
| `|` | `ENETUNREACH` | `(*` | Network is unreachable | `*)` |
| `|` | `ENETRESET` | `(*` | Network dropped connection on reset | `*)` |
| `|` | `ECONNABORTED` | `(*` | Software caused connection abort | `*)` |
| `|` | `ECONNRESET` | `(*` | Connection reset by peer | `*)` |
| `|` | `ENOBUFS` | `(*` | No buffer space available | `*)` |
| `|` | `EISCONN` | `(*` | Socket is already connected | `*)` |
| `|` | `ENOTCONN` | `(*` | Socket is not connected | `*)` |
| `|` | `ESHUTDOWN` | `(*` | Can't send after socket shutdown | `*)` |
| `|` | `ETOOMANYREFS` | `(*` | Too many references: can't splice | `*)` |
| `|` | `ETIMEDOUT` | `(*` | Connection timed out | `*)` |
| `|` | `ECONNREFUSED` | `(*` | Connection refused | `*)` |
| `|` | `EHOSTDOWN` | `(*` | Host is down | `*)` |
| `|` | `EHOSTUNREACH` | `(*` | No route to host | `*)` |
| `|` | `ELOOP` | `(*` | Too many levels of symbolic links | `*)` |
| `|` | `EOVERFLOW` | `(*` | File size or position not representable | `*)` |
| `|` | `EUNKNOWNERR of `int`` | `(*` | Unknown error | `*)` |
The type of error codes. Errors defined in the POSIX standard and additional errors from UNIX98 and BSD. All other errors are mapped to EUNKNOWNERR.
```
exception Unix_error of error * string * string
```
Raised by the system calls below when an error is encountered. The first component is the error code; the second component is the function name; the third component is the string parameter to the function, if it has one, or the empty string otherwise.
[`UnixLabels.Unix\_error`](unixlabels#EXCEPTIONUnix_error) and [`Unix.Unix\_error`](unix#EXCEPTIONUnix_error) are the same, and catching one will catch the other.
```
val error_message : error -> string
```
Return a string describing the given error code.
```
val handle_unix_error : ('a -> 'b) -> 'a -> 'b
```
`handle_unix_error f x` applies `f` to `x` and returns the result. If the exception [`UnixLabels.Unix\_error`](unixlabels#EXCEPTIONUnix_error) is raised, it prints a message describing the error and exits with code 2.
Access to the process environment
---------------------------------
```
val environment : unit -> string array
```
Return the process environment, as an array of strings with the format ``variable=value''. The returned array is empty if the process has special privileges.
```
val unsafe_environment : unit -> string array
```
Return the process environment, as an array of strings with the format ``variable=value''. Unlike [`UnixLabels.environment`](unixlabels#VALenvironment), this function returns a populated array even if the process has special privileges. See the documentation for [`UnixLabels.unsafe_getenv`](unixlabels#VALunsafe_getenv) for more details.
* **Since** 4.12.0
```
val getenv : string -> string
```
Return the value associated to a variable in the process environment, unless the process has special privileges.
* **Raises** `Not_found` if the variable is unbound or the process has special privileges. This function is identical to [`Sys.getenv`](sys#VALgetenv).
```
val unsafe_getenv : string -> string
```
Return the value associated to a variable in the process environment.
Unlike [`UnixLabels.getenv`](unixlabels#VALgetenv), this function returns the value even if the process has special privileges. It is considered unsafe because the programmer of a setuid or setgid program must be careful to avoid using maliciously crafted environment variables in the search path for executables, the locations for temporary files or logs, and the like.
* **Since** 4.06.0
* **Raises** `Not_found` if the variable is unbound.
```
val putenv : string -> string -> unit
```
`putenv name value` sets the value associated to a variable in the process environment. `name` is the name of the environment variable, and `value` its new associated value.
Process handling
----------------
```
type process_status = Unix.process_status =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `WEXITED of `int`` | `(*` | The process terminated normally by `exit`; the argument is the return code. | `*)` |
| `|` | `WSIGNALED of `int`` | `(*` | The process was killed by a signal; the argument is the signal number. | `*)` |
| `|` | `WSTOPPED of `int`` | `(*` | The process was stopped by a signal; the argument is the signal number. | `*)` |
The termination status of a process. See module [`Sys`](sys) for the definitions of the standard signal numbers. Note that they are not the numbers used by the OS.
```
type wait_flag = Unix.wait_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `WNOHANG` | `(*` | Do not block if no child has died yet, but immediately return with a pid equal to 0. | `*)` |
| `|` | `WUNTRACED` | `(*` | Report also the children that receive stop signals. | `*)` |
Flags for [`UnixLabels.waitpid`](unixlabels#VALwaitpid).
```
val execv : prog:string -> args:string array -> 'a
```
`execv ~prog ~args` execute the program in file `prog`, with the arguments `args`, and the current process environment. These `execv*` functions never return: on success, the current program is replaced by the new one.
* **Raises** `Unix_error` on failure
```
val execve : prog:string -> args:string array -> env:string array -> 'a
```
Same as [`UnixLabels.execv`](unixlabels#VALexecv), except that the third argument provides the environment to the program executed.
```
val execvp : prog:string -> args:string array -> 'a
```
Same as [`UnixLabels.execv`](unixlabels#VALexecv), except that the program is searched in the path.
```
val execvpe : prog:string -> args:string array -> env:string array -> 'a
```
Same as [`UnixLabels.execve`](unixlabels#VALexecve), except that the program is searched in the path.
```
val fork : unit -> int
```
Fork a new process. The returned integer is 0 for the child process, the pid of the child process for the parent process.
* **Raises** `Invalid_argument` on Windows. Use [`UnixLabels.create_process`](unixlabels#VALcreate_process) or threads instead.
```
val wait : unit -> int * process_status
```
Wait until one of the children processes die, and return its pid and termination status.
* **Raises** `Invalid_argument` on Windows. Use [`UnixLabels.waitpid`](unixlabels#VALwaitpid) instead.
```
val waitpid : mode:wait_flag list -> int -> int * process_status
```
Same as [`UnixLabels.wait`](unixlabels#VALwait), but waits for the child process whose pid is given. A pid of `-1` means wait for any child. A pid of `0` means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. The list of options indicates whether `waitpid` should return immediately without waiting, and whether it should report stopped children.
On Windows: can only wait for a given PID, not any child process.
```
val system : string -> process_status
```
Execute the given command, wait until it terminates, and return its termination status. The string is interpreted by the shell `/bin/sh` (or the command interpreter `cmd.exe` on Windows) and therefore can contain redirections, quotes, variables, etc. To properly quote whitespace and shell special characters occurring in file names or command arguments, the use of [`Filename.quote_command`](filename#VALquote_command) is recommended. The result `WEXITED 127` indicates that the shell couldn't be executed.
```
val _exit : int -> 'a
```
Terminate the calling process immediately, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. Unlike [`exit`](stdlib#VALexit), [`Unix._exit`](unix#VAL_exit) performs no finalization whatsoever: functions registered with [`at_exit`](stdlib#VALat_exit) are not called, input/output channels are not flushed, and the C run-time system is not finalized either.
The typical use of [`Unix._exit`](unix#VAL_exit) is after a [`Unix.fork`](unix#VALfork) operation, when the child process runs into a fatal error and must exit. In this case, it is preferable to not perform any finalization action in the child process, as these actions could interfere with similar actions performed by the parent process. For example, output channels should not be flushed by the child process, as the parent process may flush them again later, resulting in duplicate output.
* **Since** 4.12.0
```
val getpid : unit -> int
```
Return the pid of the process.
```
val getppid : unit -> int
```
Return the pid of the parent process.
* **Raises** `Invalid_argument` on Windows (because it is meaningless)
```
val nice : int -> int
```
Change the process priority. The integer argument is added to the ``nice'' value. (Higher values of the ``nice'' value mean lower priorities.) Return the new nice value.
* **Raises** `Invalid_argument` on Windows
Basic file input/output
-----------------------
```
type file_descr = Unix.file_descr
```
The abstract type of file descriptors.
```
val stdin : file_descr
```
File descriptor for standard input.
```
val stdout : file_descr
```
File descriptor for standard output.
```
val stderr : file_descr
```
File descriptor for standard error.
```
type open_flag = Unix.open_flag =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `O\_RDONLY` | `(*` | Open for reading | `*)` |
| `|` | `O\_WRONLY` | `(*` | Open for writing | `*)` |
| `|` | `O\_RDWR` | `(*` | Open for reading and writing | `*)` |
| `|` | `O\_NONBLOCK` | `(*` | Open in non-blocking mode | `*)` |
| `|` | `O\_APPEND` | `(*` | Open for append | `*)` |
| `|` | `O\_CREAT` | `(*` | Create if nonexistent | `*)` |
| `|` | `O\_TRUNC` | `(*` | Truncate to 0 length if existing | `*)` |
| `|` | `O\_EXCL` | `(*` | Fail if existing | `*)` |
| `|` | `O\_NOCTTY` | `(*` | Don't make this dev a controlling tty | `*)` |
| `|` | `O\_DSYNC` | `(*` | Writes complete as `Synchronised I/O data integrity completion' | `*)` |
| `|` | `O\_SYNC` | `(*` | Writes complete as `Synchronised I/O file integrity completion' | `*)` |
| `|` | `O\_RSYNC` | `(*` | Reads complete as writes (depending on O\_SYNC/O\_DSYNC) | `*)` |
| `|` | `O\_SHARE\_DELETE` | `(*` | Windows only: allow the file to be deleted while still open | `*)` |
| `|` | `O\_CLOEXEC` | `(*` | Set the close-on-exec flag on the descriptor returned by [`UnixLabels.openfile`](unixlabels#VALopenfile). See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for more information. | `*)` |
| `|` | `O\_KEEPEXEC` | `(*` | Clear the close-on-exec flag. This is currently the default. | `*)` |
The flags to [`UnixLabels.openfile`](unixlabels#VALopenfile).
```
type file_perm = int
```
The type of file access rights, e.g. `0o640` is read and write for user, read for group, none for others
```
val openfile : string -> mode:open_flag list -> perm:file_perm -> file_descr
```
Open the named file with the given flags. Third argument is the permissions to give to the file if it is created (see [`UnixLabels.umask`](unixlabels#VALumask)). Return a file descriptor on the named file.
```
val close : file_descr -> unit
```
Close a file descriptor.
```
val fsync : file_descr -> unit
```
Flush file buffers to disk.
* **Since** 4.12.0
```
val read : file_descr -> buf:bytes -> pos:int -> len:int -> int
```
`read fd ~buf ~pos ~len` reads `len` bytes from descriptor `fd`, storing them in byte sequence `buf`, starting at position `pos` in `buf`. Return the number of bytes actually read.
```
val write : file_descr -> buf:bytes -> pos:int -> len:int -> int
```
`write fd ~buf ~pos ~len` writes `len` bytes to descriptor `fd`, taking them from byte sequence `buf`, starting at position `pos` in `buff`. Return the number of bytes actually written. `write` repeats the writing operation until all bytes have been written or an error occurs.
```
val single_write : file_descr -> buf:bytes -> pos:int -> len:int -> int
```
Same as [`UnixLabels.write`](unixlabels#VALwrite), but attempts to write only once. Thus, if an error occurs, `single_write` guarantees that no data has been written.
```
val write_substring : file_descr -> buf:string -> pos:int -> len:int -> int
```
Same as [`UnixLabels.write`](unixlabels#VALwrite), but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
```
val single_write_substring : file_descr -> buf:string -> pos:int -> len:int -> int
```
Same as [`UnixLabels.single_write`](unixlabels#VALsingle_write), but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
Interfacing with the standard input/output library
--------------------------------------------------
```
val in_channel_of_descr : file_descr -> in_channel
```
Create an input channel reading from the given descriptor. The channel is initially in binary mode; use `set_binary_mode_in ic false` if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: [`set_binary_mode_in`](stdlib#VALset_binary_mode_in) always fails on channels created with this function.
Beware that input channels are buffered, so more characters may have been read from the descriptor than those accessed using channel functions. Channels also keep a copy of the current position in the file.
Closing the channel `ic` returned by `in_channel_of_descr fd` using `close_in ic` also closes the underlying descriptor `fd`. It is incorrect to close both the channel `ic` and the descriptor `fd`.
If several channels are created on the same descriptor, one of the channels must be closed, but not the others. Consider for example a descriptor `s` connected to a socket and two channels `ic = in_channel_of_descr s` and `oc = out_channel_of_descr s`. The recommended closing protocol is to perform `close_out oc`, which flushes buffered output to the socket then closes the socket. The `ic` channel must not be closed and will be collected by the GC eventually.
```
val out_channel_of_descr : file_descr -> out_channel
```
Create an output channel writing on the given descriptor. The channel is initially in binary mode; use `set_binary_mode_out oc false` if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: [`set_binary_mode_out`](stdlib#VALset_binary_mode_out) always fails on channels created with this function.
Beware that output channels are buffered, so you may have to call [`flush`](stdlib#VALflush) to ensure that all data has been sent to the descriptor. Channels also keep a copy of the current position in the file.
Closing the channel `oc` returned by `out_channel_of_descr fd` using `close_out oc` also closes the underlying descriptor `fd`. It is incorrect to close both the channel `ic` and the descriptor `fd`.
See [`Unix.in_channel_of_descr`](unix#VALin_channel_of_descr) for a discussion of the closing protocol when several channels are created on the same descriptor.
```
val descr_of_in_channel : in_channel -> file_descr
```
Return the descriptor corresponding to an input channel.
```
val descr_of_out_channel : out_channel -> file_descr
```
Return the descriptor corresponding to an output channel.
Seeking and truncating
----------------------
```
type seek_command = Unix.seek_command =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SEEK\_SET` | `(*` | indicates positions relative to the beginning of the file | `*)` |
| `|` | `SEEK\_CUR` | `(*` | indicates positions relative to the current position | `*)` |
| `|` | `SEEK\_END` | `(*` | indicates positions relative to the end of the file | `*)` |
Positioning modes for [`UnixLabels.lseek`](unixlabels#VALlseek).
```
val lseek : file_descr -> int -> mode:seek_command -> int
```
Set the current position for a file descriptor, and return the resulting offset (from the beginning of the file).
```
val truncate : string -> len:int -> unit
```
Truncates the named file to the given size.
```
val ftruncate : file_descr -> len:int -> unit
```
Truncates the file corresponding to the given descriptor to the given size.
File status
-----------
```
type file_kind = Unix.file_kind =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `S\_REG` | `(*` | Regular file | `*)` |
| `|` | `S\_DIR` | `(*` | Directory | `*)` |
| `|` | `S\_CHR` | `(*` | Character device | `*)` |
| `|` | `S\_BLK` | `(*` | Block device | `*)` |
| `|` | `S\_LNK` | `(*` | Symbolic link | `*)` |
| `|` | `S\_FIFO` | `(*` | Named pipe | `*)` |
| `|` | `S\_SOCK` | `(*` | Socket | `*)` |
```
type stats = Unix.stats = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `st\_dev : `int`;` | `(*` | Device number | `*)` |
| | `st\_ino : `int`;` | `(*` | Inode number | `*)` |
| | `st\_kind : `[file\_kind](unixlabels#TYPEfile_kind)`;` | `(*` | Kind of the file | `*)` |
| | `st\_perm : `[file\_perm](unixlabels#TYPEfile_perm)`;` | `(*` | Access rights | `*)` |
| | `st\_nlink : `int`;` | `(*` | Number of links | `*)` |
| | `st\_uid : `int`;` | `(*` | User id of the owner | `*)` |
| | `st\_gid : `int`;` | `(*` | Group ID of the file's group | `*)` |
| | `st\_rdev : `int`;` | `(*` | Device ID (if special file) | `*)` |
| | `st\_size : `int`;` | `(*` | Size in bytes | `*)` |
| | `st\_atime : `float`;` | `(*` | Last access time | `*)` |
| | `st\_mtime : `float`;` | `(*` | Last modification time | `*)` |
| | `st\_ctime : `float`;` | `(*` | Last status change time | `*)` |
`}` The information returned by the [`UnixLabels.stat`](unixlabels#VALstat) calls.
```
val stat : string -> stats
```
Return the information for the named file.
```
val lstat : string -> stats
```
Same as [`UnixLabels.stat`](unixlabels#VALstat), but in case the file is a symbolic link, return the information for the link itself.
```
val fstat : file_descr -> stats
```
Return the information for the file associated with the given descriptor.
```
val isatty : file_descr -> bool
```
Return `true` if the given file descriptor refers to a terminal or console window, `false` otherwise.
File operations on large files
------------------------------
```
module LargeFile: sig .. end
```
File operations on large files.
Mapping files into memory
-------------------------
```
val map_file : file_descr -> ?pos:int64 -> kind:('a, 'b) Bigarray.kind -> layout:'c Bigarray.layout -> shared:bool -> dims:int array -> ('a, 'b, 'c) Bigarray.Genarray.t
```
Memory mapping of a file as a Bigarray. `map_file fd ~kind ~layout ~shared ~dims` returns a Bigarray of kind `kind`, layout `layout`, and dimensions as specified in `dims`. The data contained in this Bigarray are the contents of the file referred to by the file descriptor `fd` (as opened previously with [`UnixLabels.openfile`](unixlabels#VALopenfile), for example). The optional `pos` parameter is the byte offset in the file of the data being mapped; it defaults to 0 (map from the beginning of the file).
If `shared` is `true`, all modifications performed on the array are reflected in the file. This requires that `fd` be opened with write permissions. If `shared` is `false`, modifications performed on the array are done in memory only, using copy-on-write of the modified pages; the underlying file is not affected.
[`UnixLabels.map_file`](unixlabels#VALmap_file) is much more efficient than reading the whole file in a Bigarray, modifying that Bigarray, and writing it afterwards.
To adjust automatically the dimensions of the Bigarray to the actual size of the file, the major dimension (that is, the first dimension for an array with C layout, and the last dimension for an array with Fortran layout) can be given as `-1`. [`UnixLabels.map_file`](unixlabels#VALmap_file) then determines the major dimension from the size of the file. The file must contain an integral number of sub-arrays as determined by the non-major dimensions, otherwise `Failure` is raised.
If all dimensions of the Bigarray are given, the file size is matched against the size of the Bigarray. If the file is larger than the Bigarray, only the initial portion of the file is mapped to the Bigarray. If the file is smaller than the big array, the file is automatically grown to the size of the Bigarray. This requires write permissions on `fd`.
Array accesses are bounds-checked, but the bounds are determined by the initial call to `map_file`. Therefore, you should make sure no other process modifies the mapped file while you're accessing it, or a SIGBUS signal may be raised. This happens, for instance, if the file is shrunk.
`Invalid\_argument` or `Failure` may be raised in cases where argument validation fails.
* **Since** 4.06.0
Operations on file names
------------------------
```
val unlink : string -> unit
```
Removes the named file.
If the named file is a directory, raises:
* `EPERM` on POSIX compliant system
* `EISDIR` on Linux >= 2.1.132
* `EACCESS` on Windows
```
val rename : src:string -> dst:string -> unit
```
`rename ~src ~dst` changes the name of a file from `src` to `dst`, moving it between directories if needed. If `dst` already exists, its contents will be replaced with those of `src`. Depending on the operating system, the metadata (permissions, owner, etc) of `dst` can either be preserved or be replaced by those of `src`.
```
val link : ?follow:bool -> src:string -> dst:string -> unit
```
`link ?follow ~src ~dst` creates a hard link named `dst` to the file named `src`.
* **Raises**
+ `ENOSYS` On *Unix* if `~follow:_` is requested, but linkat is unavailable.
+ `ENOSYS` On *Windows* if `~follow:false` is requested.
`follow` : indicates whether a `src` symlink is followed or a hardlink to `src` itself will be created. On *Unix* systems this is done using the `linkat(2)` function. If `?follow` is not provided, then the `link(2)` function is used whose behaviour is OS-dependent, but more widely available.
```
val realpath : string -> string
```
`realpath p` is an absolute pathname for `p` obtained by resolving all extra `/` characters, relative path segments and symbolic links.
* **Since** 4.13.0
File permissions and ownership
------------------------------
```
type access_permission = Unix.access_permission =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `R\_OK` | `(*` | Read permission | `*)` |
| `|` | `W\_OK` | `(*` | Write permission | `*)` |
| `|` | `X\_OK` | `(*` | Execution permission | `*)` |
| `|` | `F\_OK` | `(*` | File exists | `*)` |
Flags for the [`UnixLabels.access`](unixlabels#VALaccess) call.
```
val chmod : string -> perm:file_perm -> unit
```
Change the permissions of the named file.
```
val fchmod : file_descr -> perm:file_perm -> unit
```
Change the permissions of an opened file.
* **Raises** `Invalid_argument` on Windows
```
val chown : string -> uid:int -> gid:int -> unit
```
Change the owner uid and owner gid of the named file.
* **Raises** `Invalid_argument` on Windows
```
val fchown : file_descr -> uid:int -> gid:int -> unit
```
Change the owner uid and owner gid of an opened file.
* **Raises** `Invalid_argument` on Windows
```
val umask : int -> int
```
Set the process's file mode creation mask, and return the previous mask.
* **Raises** `Invalid_argument` on Windows
```
val access : string -> perm:access_permission list -> unit
```
Check that the process has the given permissions over the named file.
On Windows: execute permission `X\_OK` cannot be tested, just tests for read permission instead.
* **Raises** `Unix_error` otherwise.
Operations on file descriptors
------------------------------
```
val dup : ?cloexec:bool -> file_descr -> file_descr
```
Return a new file descriptor referencing the same file as the given descriptor. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val dup2 : ?cloexec:bool -> src:file_descr -> dst:file_descr -> unit
```
`dup2 ~src ~dst` duplicates `src` to `dst`, closing `dst` if already opened. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val set_nonblock : file_descr -> unit
```
Set the ``non-blocking'' flag on the given descriptor. When the non-blocking flag is set, reading on a descriptor on which there is temporarily no data available raises the `EAGAIN` or `EWOULDBLOCK` error instead of blocking; writing on a descriptor on which there is temporarily no room for writing also raises `EAGAIN` or `EWOULDBLOCK`.
```
val clear_nonblock : file_descr -> unit
```
Clear the ``non-blocking'' flag on the given descriptor. See [`UnixLabels.set_nonblock`](unixlabels#VALset_nonblock).
```
val set_close_on_exec : file_descr -> unit
```
Set the ``close-on-exec'' flag on the given descriptor. A descriptor with the close-on-exec flag is automatically closed when the current process starts another program with one of the `exec`, `create_process` and `open_process` functions.
It is often a security hole to leak file descriptors opened on, say, a private file to an external program: the program, then, gets access to the private file and can do bad things with it. Hence, it is highly recommended to set all file descriptors ``close-on-exec'', except in the very few cases where a file descriptor actually needs to be transmitted to another program.
The best way to set a file descriptor ``close-on-exec'' is to create it in this state. To this end, the `openfile` function has `O\_CLOEXEC` and `O\_KEEPEXEC` flags to enforce ``close-on-exec'' mode or ``keep-on-exec'' mode, respectively. All other operations in the Unix module that create file descriptors have an optional argument `?cloexec:bool` to indicate whether the file descriptor should be created in ``close-on-exec'' mode (by writing `~cloexec:true`) or in ``keep-on-exec'' mode (by writing `~cloexec:false`). For historical reasons, the default file descriptor creation mode is ``keep-on-exec'', if no `cloexec` optional argument is given. This is not a safe default, hence it is highly recommended to pass explicit `cloexec` arguments to operations that create file descriptors.
The `cloexec` optional arguments and the `O\_KEEPEXEC` flag were introduced in OCaml 4.05. Earlier, the common practice was to create file descriptors in the default, ``keep-on-exec'' mode, then call `set_close_on_exec` on those freshly-created file descriptors. This is not as safe as creating the file descriptor in ``close-on-exec'' mode because, in multithreaded programs, a window of vulnerability exists between the time when the file descriptor is created and the time `set_close_on_exec` completes. If another thread spawns another program during this window, the descriptor will leak, as it is still in the ``keep-on-exec'' mode.
Regarding the atomicity guarantees given by `~cloexec:true` or by the use of the `O\_CLOEXEC` flag: on all platforms it is guaranteed that a concurrently-executing Caml thread cannot leak the descriptor by starting a new process. On Linux, this guarantee extends to concurrently-executing C threads. As of Feb 2017, other operating systems lack the necessary system calls and still expose a window of vulnerability during which a C thread can see the newly-created file descriptor in ``keep-on-exec'' mode.
```
val clear_close_on_exec : file_descr -> unit
```
Clear the ``close-on-exec'' flag on the given descriptor. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec).
Directories
-----------
```
val mkdir : string -> perm:file_perm -> unit
```
Create a directory with the given permissions (see [`UnixLabels.umask`](unixlabels#VALumask)).
```
val rmdir : string -> unit
```
Remove an empty directory.
```
val chdir : string -> unit
```
Change the process working directory.
```
val getcwd : unit -> string
```
Return the name of the current working directory.
```
val chroot : string -> unit
```
Change the process root directory.
* **Raises** `Invalid_argument` on Windows
```
type dir_handle = Unix.dir_handle
```
The type of descriptors over opened directories.
```
val opendir : string -> dir_handle
```
Open a descriptor on a directory
```
val readdir : dir_handle -> string
```
Return the next entry in a directory.
* **Raises** `End_of_file` when the end of the directory has been reached.
```
val rewinddir : dir_handle -> unit
```
Reposition the descriptor to the beginning of the directory
```
val closedir : dir_handle -> unit
```
Close a directory descriptor.
Pipes and redirections
----------------------
```
val pipe : ?cloexec:bool -> unit -> file_descr * file_descr
```
Create a pipe. The first component of the result is opened for reading, that's the exit to the pipe. The second component is opened for writing, that's the entrance to the pipe. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val mkfifo : string -> perm:file_perm -> unit
```
Create a named pipe with the given permissions (see [`UnixLabels.umask`](unixlabels#VALumask)).
* **Raises** `Invalid_argument` on Windows
High-level process and redirection management
---------------------------------------------
```
val create_process : prog:string -> args:string array -> stdin:file_descr -> stdout:file_descr -> stderr:file_descr -> int
```
`create_process ~prog ~args ~stdin ~stdout ~stderr` forks a new process that executes the program in file `prog`, with arguments `args`. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The standard input and outputs of the new process are connected to the descriptors `stdin`, `stdout` and `stderr`. Passing e.g. [`Unix.stdout`](unix#VALstdout) for `stdout` prevents the redirection and causes the new process to have the same standard output as the current process. The executable file `prog` is searched in the path. The new process has the same environment as the current process.
```
val create_process_env : prog:string -> args:string array -> env:string array -> stdin:file_descr -> stdout:file_descr -> stderr:file_descr -> int
```
`create_process_env ~prog ~args ~env ~stdin ~stdout ~stderr` works as [`UnixLabels.create_process`](unixlabels#VALcreate_process), except that the extra argument `env` specifies the environment passed to the program.
```
val open_process_in : string -> in_channel
```
High-level pipe and process management. This function runs the given command in parallel with the program. The standard output of the command is redirected to a pipe, which can be read via the returned input channel. The command is interpreted by the shell `/bin/sh` (or `cmd.exe` on Windows), cf. [`UnixLabels.system`](unixlabels#VALsystem). The [`Filename.quote_command`](filename#VALquote_command) function can be used to quote the command and its arguments as appropriate for the shell being used. If the command does not need to be run through the shell, [`UnixLabels.open_process_args_in`](unixlabels#VALopen_process_args_in) can be used as a more robust and more efficient alternative to [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in).
```
val open_process_out : string -> out_channel
```
Same as [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in), but redirect the standard input of the command to a pipe. Data written to the returned output channel is sent to the standard input of the command. Warning: writes on output channels are buffered, hence be careful to call [`flush`](stdlib#VALflush) at the right times to ensure correct synchronization. If the command does not need to be run through the shell, [`UnixLabels.open_process_args_out`](unixlabels#VALopen_process_args_out) can be used instead of [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out).
```
val open_process : string -> in_channel * out_channel
```
Same as [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out), but redirects both the standard input and standard output of the command to pipes connected to the two returned channels. The input channel is connected to the output of the command, and the output channel to the input of the command. If the command does not need to be run through the shell, [`UnixLabels.open_process_args`](unixlabels#VALopen_process_args) can be used instead of [`UnixLabels.open_process`](unixlabels#VALopen_process).
```
val open_process_full : string -> env:string array -> in_channel * out_channel * in_channel
```
Similar to [`UnixLabels.open_process`](unixlabels#VALopen_process), but the second argument specifies the environment passed to the command. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the command. If the command does not need to be run through the shell, [`UnixLabels.open_process_args_full`](unixlabels#VALopen_process_args_full) can be used instead of [`UnixLabels.open_process_full`](unixlabels#VALopen_process_full).
```
val open_process_args_in : string -> string array -> in_channel
```
`open_process_args_in prog args` runs the program `prog` with arguments `args`. The new process executes concurrently with the current process. The standard output of the new process is redirected to a pipe, which can be read via the returned input channel.
The executable file `prog` is searched in the path. This behaviour changed in 4.12; previously `prog` was looked up only in the current directory.
The new process has the same environment as the current process.
* **Since** 4.08.0
```
val open_process_args_out : string -> string array -> out_channel
```
Same as [`UnixLabels.open_process_args_in`](unixlabels#VALopen_process_args_in), but redirect the standard input of the new process to a pipe. Data written to the returned output channel is sent to the standard input of the program. Warning: writes on output channels are buffered, hence be careful to call [`flush`](stdlib#VALflush) at the right times to ensure correct synchronization.
* **Since** 4.08.0
```
val open_process_args : string -> string array -> in_channel * out_channel
```
Same as [`UnixLabels.open_process_args_out`](unixlabels#VALopen_process_args_out), but redirects both the standard input and standard output of the new process to pipes connected to the two returned channels. The input channel is connected to the output of the program, and the output channel to the input of the program.
* **Since** 4.08.0
```
val open_process_args_full : string -> string array -> string array -> in_channel * out_channel * in_channel
```
Similar to [`UnixLabels.open_process_args`](unixlabels#VALopen_process_args), but the third argument specifies the environment passed to the new process. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the program.
* **Since** 4.08.0
```
val process_in_pid : in_channel -> int
```
Return the pid of a process opened via [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in) or [`UnixLabels.open_process_args_in`](unixlabels#VALopen_process_args_in).
* **Since** 4.12.0
```
val process_out_pid : out_channel -> int
```
Return the pid of a process opened via [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out) or [`UnixLabels.open_process_args_out`](unixlabels#VALopen_process_args_out).
* **Since** 4.12.0
```
val process_pid : in_channel * out_channel -> int
```
Return the pid of a process opened via [`UnixLabels.open_process`](unixlabels#VALopen_process) or [`UnixLabels.open_process_args`](unixlabels#VALopen_process_args).
* **Since** 4.12.0
```
val process_full_pid : in_channel * out_channel * in_channel -> int
```
Return the pid of a process opened via [`UnixLabels.open_process_full`](unixlabels#VALopen_process_full) or [`UnixLabels.open_process_args_full`](unixlabels#VALopen_process_args_full).
* **Since** 4.12.0
```
val close_process_in : in_channel -> process_status
```
Close channels opened by [`UnixLabels.open_process_in`](unixlabels#VALopen_process_in), wait for the associated command to terminate, and return its termination status.
```
val close_process_out : out_channel -> process_status
```
Close channels opened by [`UnixLabels.open_process_out`](unixlabels#VALopen_process_out), wait for the associated command to terminate, and return its termination status.
```
val close_process : in_channel * out_channel -> process_status
```
Close channels opened by [`UnixLabels.open_process`](unixlabels#VALopen_process), wait for the associated command to terminate, and return its termination status.
```
val close_process_full : in_channel * out_channel * in_channel -> process_status
```
Close channels opened by [`UnixLabels.open_process_full`](unixlabels#VALopen_process_full), wait for the associated command to terminate, and return its termination status.
Symbolic links
--------------
```
val symlink : ?to_dir:bool -> src:string -> dst:string -> unit
```
`symlink ?to_dir ~src ~dst` creates the file `dst` as a symbolic link to the file `src`. On Windows, `~to_dir` indicates if the symbolic link points to a directory or a file; if omitted, `symlink` examines `src` using `stat` and picks appropriately, if `src` does not exist then `false` is assumed (for this reason, it is recommended that the `~to_dir` parameter be specified in new code). On Unix, `~to_dir` is ignored.
Windows symbolic links are available in Windows Vista onwards. There are some important differences between Windows symlinks and their POSIX counterparts.
Windows symbolic links come in two flavours: directory and regular, which designate whether the symbolic link points to a directory or a file. The type must be correct - a directory symlink which actually points to a file cannot be selected with chdir and a file symlink which actually points to a directory cannot be read or written (note that Cygwin's emulation layer ignores this distinction).
When symbolic links are created to existing targets, this distinction doesn't matter and `symlink` will automatically create the correct kind of symbolic link. The distinction matters when a symbolic link is created to a non-existent target.
The other caveat is that by default symbolic links are a privileged operation. Administrators will always need to be running elevated (or with UAC disabled) and by default normal user accounts need to be granted the SeCreateSymbolicLinkPrivilege via Local Security Policy (secpol.msc) or via Active Directory.
[`UnixLabels.has_symlink`](unixlabels#VALhas_symlink) can be used to check that a process is able to create symbolic links.
```
val has_symlink : unit -> bool
```
Returns `true` if the user is able to create symbolic links. On Windows, this indicates that the user not only has the SeCreateSymbolicLinkPrivilege but is also running elevated, if necessary. On other platforms, this is simply indicates that the symlink system call is available.
* **Since** 4.03.0
```
val readlink : string -> string
```
Read the contents of a symbolic link.
Polling
-------
```
val select : read:file_descr list -> write:file_descr list -> except:file_descr list -> timeout:float -> file_descr list * file_descr list * file_descr list
```
Wait until some input/output operations become possible on some channels. The three list arguments are, respectively, a set of descriptors to check for reading (first argument), for writing (second argument), or for exceptional conditions (third argument). The fourth argument is the maximal timeout, in seconds; a negative fourth argument means no timeout (unbounded wait). The result is composed of three sets of descriptors: those ready for reading (first component), ready for writing (second component), and over which an exceptional condition is pending (third component).
Locking
-------
```
type lock_command = Unix.lock_command =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `F\_ULOCK` | `(*` | Unlock a region | `*)` |
| `|` | `F\_LOCK` | `(*` | Lock a region for writing, and block if already locked | `*)` |
| `|` | `F\_TLOCK` | `(*` | Lock a region for writing, or fail if already locked | `*)` |
| `|` | `F\_TEST` | `(*` | Test a region for other process locks | `*)` |
| `|` | `F\_RLOCK` | `(*` | Lock a region for reading, and block if already locked | `*)` |
| `|` | `F\_TRLOCK` | `(*` | Lock a region for reading, or fail if already locked | `*)` |
Commands for [`UnixLabels.lockf`](unixlabels#VALlockf).
```
val lockf : file_descr -> mode:lock_command -> len:int -> unit
```
`lockf fd ~mode ~len` puts a lock on a region of the file opened as `fd`. The region starts at the current read/write position for `fd` (as set by [`UnixLabels.lseek`](unixlabels#VALlseek)), and extends `len` bytes forward if `len` is positive, `len` bytes backwards if `len` is negative, or to the end of the file if `len` is zero. A write lock prevents any other process from acquiring a read or write lock on the region. A read lock prevents any other process from acquiring a write lock on the region, but lets other processes acquire read locks on it.
The `F\_LOCK` and `F\_TLOCK` commands attempts to put a write lock on the specified region. The `F\_RLOCK` and `F\_TRLOCK` commands attempts to put a read lock on the specified region. If one or several locks put by another process prevent the current process from acquiring the lock, `F\_LOCK` and `F\_RLOCK` block until these locks are removed, while `F\_TLOCK` and `F\_TRLOCK` fail immediately with an exception. The `F\_ULOCK` removes whatever locks the current process has on the specified region. Finally, the `F\_TEST` command tests whether a write lock can be acquired on the specified region, without actually putting a lock. It returns immediately if successful, or fails otherwise.
What happens when a process tries to lock a region of a file that is already locked by the same process depends on the OS. On POSIX-compliant systems, the second lock operation succeeds and may "promote" the older lock from read lock to write lock. On Windows, the second lock operation will block or fail.
Signals
-------
Note: installation of signal handlers is performed via the functions [`Sys.signal`](sys#VALsignal) and [`Sys.set_signal`](sys#VALset_signal).
```
val kill : pid:int -> signal:int -> unit
```
`kill ~pid ~signal` sends signal number `signal` to the process with id `pid`.
On Windows: only the [`Sys.sigkill`](sys#VALsigkill) signal is emulated.
```
type sigprocmask_command = Unix.sigprocmask_command =
```
| | |
| --- | --- |
| `|` | `SIG\_SETMASK` |
| `|` | `SIG\_BLOCK` |
| `|` | `SIG\_UNBLOCK` |
```
val sigprocmask : mode:sigprocmask_command -> int list -> int list
```
`sigprocmask ~mode sigs` changes the set of blocked signals. If `mode` is `SIG\_SETMASK`, blocked signals are set to those in the list `sigs`. If `mode` is `SIG\_BLOCK`, the signals in `sigs` are added to the set of blocked signals. If `mode` is `SIG\_UNBLOCK`, the signals in `sigs` are removed from the set of blocked signals. `sigprocmask` returns the set of previously blocked signals.
When the systhreads version of the `Thread` module is loaded, this function redirects to `Thread.sigmask`. I.e., `sigprocmask` only changes the mask of the current thread.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
```
val sigpending : unit -> int list
```
Return the set of blocked signals that are currently pending.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
```
val sigsuspend : int list -> unit
```
`sigsuspend sigs` atomically sets the blocked signals to `sigs` and waits for a non-ignored, non-blocked signal to be delivered. On return, the blocked signals are reset to their initial value.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
```
val pause : unit -> unit
```
Wait until a non-ignored, non-blocked signal is delivered.
* **Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)
Time functions
--------------
```
type process_times = Unix.process_times = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `tms\_utime : `float`;` | `(*` | User time for the process | `*)` |
| | `tms\_stime : `float`;` | `(*` | System time for the process | `*)` |
| | `tms\_cutime : `float`;` | `(*` | User time for the children processes | `*)` |
| | `tms\_cstime : `float`;` | `(*` | System time for the children processes | `*)` |
`}` The execution times (CPU times) of a process.
```
type tm = Unix.tm = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `tm\_sec : `int`;` | `(*` | Seconds 0..60 | `*)` |
| | `tm\_min : `int`;` | `(*` | Minutes 0..59 | `*)` |
| | `tm\_hour : `int`;` | `(*` | Hours 0..23 | `*)` |
| | `tm\_mday : `int`;` | `(*` | Day of month 1..31 | `*)` |
| | `tm\_mon : `int`;` | `(*` | Month of year 0..11 | `*)` |
| | `tm\_year : `int`;` | `(*` | Year - 1900 | `*)` |
| | `tm\_wday : `int`;` | `(*` | Day of week (Sunday is 0) | `*)` |
| | `tm\_yday : `int`;` | `(*` | Day of year 0..365 | `*)` |
| | `tm\_isdst : `bool`;` | `(*` | Daylight time savings in effect | `*)` |
`}` The type representing wallclock time and calendar date.
```
val time : unit -> float
```
Return the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds.
```
val gettimeofday : unit -> float
```
Same as [`UnixLabels.time`](unixlabels#VALtime), but with resolution better than 1 second.
```
val gmtime : float -> tm
```
Convert a time in seconds, as returned by [`UnixLabels.time`](unixlabels#VALtime), into a date and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. To perform the inverse conversion, set the TZ environment variable to "UTC", use [`UnixLabels.mktime`](unixlabels#VALmktime), and then restore the original value of TZ.
```
val localtime : float -> tm
```
Convert a time in seconds, as returned by [`UnixLabels.time`](unixlabels#VALtime), into a date and a time. Assumes the local time zone. The function performing the inverse conversion is [`UnixLabels.mktime`](unixlabels#VALmktime).
```
val mktime : tm -> float * tm
```
Convert a date and time, specified by the `tm` argument, into a time in seconds, as returned by [`UnixLabels.time`](unixlabels#VALtime). The `tm_isdst`, `tm_wday` and `tm_yday` fields of `tm` are ignored. Also return a normalized copy of the given `tm` record, with the `tm_wday`, `tm_yday`, and `tm_isdst` fields recomputed from the other fields, and the other fields normalized (so that, e.g., 40 October is changed into 9 November). The `tm` argument is interpreted in the local time zone.
```
val alarm : int -> int
```
Schedule a `SIGALRM` signal after the given number of seconds.
* **Raises** `Invalid_argument` on Windows
```
val sleep : int -> unit
```
Stop execution for the given number of seconds.
```
val sleepf : float -> unit
```
Stop execution for the given number of seconds. Like `sleep`, but fractions of seconds are supported.
* **Since** 4.12.0
```
val times : unit -> process_times
```
Return the execution times of the process.
On Windows: partially implemented, will not report timings for child processes.
```
val utimes : string -> access:float -> modif:float -> unit
```
Set the last access time (second arg) and last modification time (third arg) for a file. Times are expressed in seconds from 00:00:00 GMT, Jan. 1, 1970. If both times are `0.0`, the access and last modification times are both set to the current time.
```
type interval_timer = Unix.interval_timer =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `ITIMER\_REAL` | `(*` | decrements in real time, and sends the signal `SIGALRM` when expired. | `*)` |
| `|` | `ITIMER\_VIRTUAL` | `(*` | decrements in process virtual time, and sends `SIGVTALRM` when expired. | `*)` |
| `|` | `ITIMER\_PROF` | `(*` | (for profiling) decrements both when the process is running and when the system is running on behalf of the process; it sends `SIGPROF` when expired. | `*)` |
The three kinds of interval timers.
```
type interval_timer_status = Unix.interval_timer_status = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `it\_interval : `float`;` | `(*` | Period | `*)` |
| | `it\_value : `float`;` | `(*` | Current value of the timer | `*)` |
`}` The type describing the status of an interval timer
```
val getitimer : interval_timer -> interval_timer_status
```
Return the current status of the given interval timer.
* **Raises** `Invalid_argument` on Windows
```
val setitimer : interval_timer -> interval_timer_status -> interval_timer_status
```
`setitimer t s` sets the interval timer `t` and returns its previous status. The `s` argument is interpreted as follows: `s.it_value`, if nonzero, is the time to the next timer expiration; `s.it_interval`, if nonzero, specifies a value to be used in reloading `it_value` when the timer expires. Setting `s.it_value` to zero disables the timer. Setting `s.it_interval` to zero causes the timer to be disabled after its next expiration.
* **Raises** `Invalid_argument` on Windows
User id, group id
-----------------
```
val getuid : unit -> int
```
Return the user id of the user executing the process.
On Windows: always returns `1`.
```
val geteuid : unit -> int
```
Return the effective user id under which the process runs.
On Windows: always returns `1`.
```
val setuid : int -> unit
```
Set the real user id and effective user id for the process.
* **Raises** `Invalid_argument` on Windows
```
val getgid : unit -> int
```
Return the group id of the user executing the process.
On Windows: always returns `1`.
```
val getegid : unit -> int
```
Return the effective group id under which the process runs.
On Windows: always returns `1`.
```
val setgid : int -> unit
```
Set the real group id and effective group id for the process.
* **Raises** `Invalid_argument` on Windows
```
val getgroups : unit -> int array
```
Return the list of groups to which the user executing the process belongs.
On Windows: always returns `[|1|]`.
```
val setgroups : int array -> unit
```
`setgroups groups` sets the supplementary group IDs for the calling process. Appropriate privileges are required.
* **Raises** `Invalid_argument` on Windows
```
val initgroups : string -> int -> unit
```
`initgroups user group` initializes the group access list by reading the group database /etc/group and using all groups of which `user` is a member. The additional group `group` is also added to the list.
* **Raises** `Invalid_argument` on Windows
```
type passwd_entry = Unix.passwd_entry = {
```
| | |
| --- | --- |
| | `pw\_name : `string`;` |
| | `pw\_passwd : `string`;` |
| | `pw\_uid : `int`;` |
| | `pw\_gid : `int`;` |
| | `pw\_gecos : `string`;` |
| | `pw\_dir : `string`;` |
| | `pw\_shell : `string`;` |
`}` Structure of entries in the `passwd` database.
```
type group_entry = Unix.group_entry = {
```
| | |
| --- | --- |
| | `gr\_name : `string`;` |
| | `gr\_passwd : `string`;` |
| | `gr\_gid : `int`;` |
| | `gr\_mem : `string array`;` |
`}` Structure of entries in the `groups` database.
```
val getlogin : unit -> string
```
Return the login name of the user executing the process.
```
val getpwnam : string -> passwd_entry
```
Find an entry in `passwd` with the given name.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
```
val getgrnam : string -> group_entry
```
Find an entry in `group` with the given name.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
```
val getpwuid : int -> passwd_entry
```
Find an entry in `passwd` with the given user id.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
```
val getgrgid : int -> group_entry
```
Find an entry in `group` with the given group id.
* **Raises** `Not_found` if no such entry exists, or always on Windows.
Internet addresses
------------------
```
type inet_addr = Unix.inet_addr
```
The abstract type of Internet addresses.
```
val inet_addr_of_string : string -> inet_addr
```
Conversion from the printable representation of an Internet address to its internal representation. The argument string consists of 4 numbers separated by periods (`XXX.YYY.ZZZ.TTT`) for IPv4 addresses, and up to 8 numbers separated by colons for IPv6 addresses.
* **Raises** `Failure` when given a string that does not match these formats.
```
val string_of_inet_addr : inet_addr -> string
```
Return the printable representation of the given Internet address. See [`UnixLabels.inet_addr_of_string`](unixlabels#VALinet_addr_of_string) for a description of the printable representation.
```
val inet_addr_any : inet_addr
```
A special IPv4 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses.
```
val inet_addr_loopback : inet_addr
```
A special IPv4 address representing the host machine (`127.0.0.1`).
```
val inet6_addr_any : inet_addr
```
A special IPv6 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses.
```
val inet6_addr_loopback : inet_addr
```
A special IPv6 address representing the host machine (`::1`).
```
val is_inet6_addr : inet_addr -> bool
```
Whether the given `inet_addr` is an IPv6 address.
* **Since** 4.12.0
Sockets
-------
```
type socket_domain = Unix.socket_domain =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `PF\_UNIX` | `(*` | Unix domain | `*)` |
| `|` | `PF\_INET` | `(*` | Internet domain (IPv4) | `*)` |
| `|` | `PF\_INET6` | `(*` | Internet domain (IPv6) | `*)` |
The type of socket domains. Not all platforms support IPv6 sockets (type `PF\_INET6`).
On Windows: `PF\_UNIX` supported since 4.14.0 on Windows 10 1803 and later.
```
type socket_type = Unix.socket_type =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SOCK\_STREAM` | `(*` | Stream socket | `*)` |
| `|` | `SOCK\_DGRAM` | `(*` | Datagram socket | `*)` |
| `|` | `SOCK\_RAW` | `(*` | Raw socket | `*)` |
| `|` | `SOCK\_SEQPACKET` | `(*` | Sequenced packets socket | `*)` |
The type of socket kinds, specifying the semantics of communications. `SOCK\_SEQPACKET` is included for completeness, but is rarely supported by the OS, and needs system calls that are not available in this library.
```
type sockaddr = Unix.sockaddr =
```
| | |
| --- | --- |
| `|` | `ADDR\_UNIX of `string`` |
| `|` | `ADDR\_INET of `[inet\_addr](unixlabels#TYPEinet_addr) * int`` |
The type of socket addresses. `ADDR\_UNIX name` is a socket address in the Unix domain; `name` is a file name in the file system. `ADDR\_INET(addr,port)` is a socket address in the Internet domain; `addr` is the Internet address of the machine, and `port` is the port number.
```
val socket : ?cloexec:bool -> domain:socket_domain -> kind:socket_type -> protocol:int -> file_descr
```
Create a new socket in the given domain, and with the given kind. The third argument is the protocol type; 0 selects the default protocol for that kind of sockets. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val domain_of_sockaddr : sockaddr -> socket_domain
```
Return the socket domain adequate for the given socket address.
```
val socketpair : ?cloexec:bool -> domain:socket_domain -> kind:socket_type -> protocol:int -> file_descr * file_descr
```
Create a pair of unnamed sockets, connected together. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val accept : ?cloexec:bool -> file_descr -> file_descr * sockaddr
```
Accept connections on the given socket. The returned descriptor is a socket connected to the client; the returned address is the address of the connecting client. See [`UnixLabels.set_close_on_exec`](unixlabels#VALset_close_on_exec) for documentation on the `cloexec` optional argument.
```
val bind : file_descr -> addr:sockaddr -> unit
```
Bind a socket to an address.
```
val connect : file_descr -> addr:sockaddr -> unit
```
Connect a socket to an address.
```
val listen : file_descr -> max:int -> unit
```
Set up a socket for receiving connection requests. The integer argument is the maximal number of pending requests.
```
type shutdown_command = Unix.shutdown_command =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SHUTDOWN\_RECEIVE` | `(*` | Close for receiving | `*)` |
| `|` | `SHUTDOWN\_SEND` | `(*` | Close for sending | `*)` |
| `|` | `SHUTDOWN\_ALL` | `(*` | Close both | `*)` |
The type of commands for `shutdown`.
```
val shutdown : file_descr -> mode:shutdown_command -> unit
```
Shutdown a socket connection. `SHUTDOWN\_SEND` as second argument causes reads on the other end of the connection to return an end-of-file condition. `SHUTDOWN\_RECEIVE` causes writes on the other end of the connection to return a closed pipe condition (`SIGPIPE` signal).
```
val getsockname : file_descr -> sockaddr
```
Return the address of the given socket.
```
val getpeername : file_descr -> sockaddr
```
Return the address of the host connected to the given socket.
```
type msg_flag = Unix.msg_flag =
```
| | |
| --- | --- |
| `|` | `MSG\_OOB` |
| `|` | `MSG\_DONTROUTE` |
| `|` | `MSG\_PEEK` |
The flags for [`UnixLabels.recv`](unixlabels#VALrecv), [`UnixLabels.recvfrom`](unixlabels#VALrecvfrom), [`UnixLabels.send`](unixlabels#VALsend) and [`UnixLabels.sendto`](unixlabels#VALsendto).
```
val recv : file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list -> int
```
Receive data from a connected socket.
```
val recvfrom : file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list -> int * sockaddr
```
Receive data from an unconnected socket.
```
val send : file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list -> int
```
Send data over a connected socket.
```
val send_substring : file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> int
```
Same as `send`, but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
```
val sendto : file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list -> addr:sockaddr -> int
```
Send data over an unconnected socket.
```
val sendto_substring : file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> sockaddr -> int
```
Same as `sendto`, but take the data from a string instead of a byte sequence.
* **Since** 4.02.0
Socket options
--------------
```
type socket_bool_option = Unix.socket_bool_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_DEBUG` | `(*` | Record debugging information | `*)` |
| `|` | `SO\_BROADCAST` | `(*` | Permit sending of broadcast messages | `*)` |
| `|` | `SO\_REUSEADDR` | `(*` | Allow reuse of local addresses for bind | `*)` |
| `|` | `SO\_KEEPALIVE` | `(*` | Keep connection active | `*)` |
| `|` | `SO\_DONTROUTE` | `(*` | Bypass the standard routing algorithms | `*)` |
| `|` | `SO\_OOBINLINE` | `(*` | Leave out-of-band data in line | `*)` |
| `|` | `SO\_ACCEPTCONN` | `(*` | Report whether socket listening is enabled | `*)` |
| `|` | `TCP\_NODELAY` | `(*` | Control the Nagle algorithm for TCP sockets | `*)` |
| `|` | `IPV6\_ONLY` | `(*` | Forbid binding an IPv6 socket to an IPv4 address | `*)` |
| `|` | `SO\_REUSEPORT` | `(*` | Allow reuse of address and port bindings | `*)` |
The socket options that can be consulted with [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) and modified with [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt). These options have a boolean (`true`/`false`) value.
```
type socket_int_option = Unix.socket_int_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_SNDBUF` | `(*` | Size of send buffer | `*)` |
| `|` | `SO\_RCVBUF` | `(*` | Size of received buffer | `*)` |
| `|` | `SO\_ERROR` | `(*` | Deprecated. Use Unix.getsockopt\_error instead. Deprecated. Use [`UnixLabels.getsockopt_error`](unixlabels#VALgetsockopt_error) instead. | `*)` |
| `|` | `SO\_TYPE` | `(*` | Report the socket type | `*)` |
| `|` | `SO\_RCVLOWAT` | `(*` | Minimum number of bytes to process for input operations | `*)` |
| `|` | `SO\_SNDLOWAT` | `(*` | Minimum number of bytes to process for output operations | `*)` |
The socket options that can be consulted with [`UnixLabels.getsockopt_int`](unixlabels#VALgetsockopt_int) and modified with [`UnixLabels.setsockopt_int`](unixlabels#VALsetsockopt_int). These options have an integer value.
```
type socket_optint_option = Unix.socket_optint_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_LINGER` | `(*` | Whether to linger on closed connections that have data present, and for how long (in seconds) | `*)` |
The socket options that can be consulted with [`UnixLabels.getsockopt_optint`](unixlabels#VALgetsockopt_optint) and modified with [`UnixLabels.setsockopt_optint`](unixlabels#VALsetsockopt_optint). These options have a value of type `int option`, with `None` meaning ``disabled''.
```
type socket_float_option = Unix.socket_float_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `SO\_RCVTIMEO` | `(*` | Timeout for input operations | `*)` |
| `|` | `SO\_SNDTIMEO` | `(*` | Timeout for output operations | `*)` |
The socket options that can be consulted with [`UnixLabels.getsockopt_float`](unixlabels#VALgetsockopt_float) and modified with [`UnixLabels.setsockopt_float`](unixlabels#VALsetsockopt_float). These options have a floating-point value representing a time in seconds. The value 0 means infinite timeout.
```
val getsockopt : file_descr -> socket_bool_option -> bool
```
Return the current status of a boolean-valued option in the given socket.
```
val setsockopt : file_descr -> socket_bool_option -> bool -> unit
```
Set or clear a boolean-valued option in the given socket.
```
val getsockopt_int : file_descr -> socket_int_option -> int
```
Same as [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) for an integer-valued socket option.
```
val setsockopt_int : file_descr -> socket_int_option -> int -> unit
```
Same as [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt) for an integer-valued socket option.
```
val getsockopt_optint : file_descr -> socket_optint_option -> int option
```
Same as [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) for a socket option whose value is an `int option`.
```
val setsockopt_optint : file_descr -> socket_optint_option -> int option -> unit
```
Same as [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt) for a socket option whose value is an `int option`.
```
val getsockopt_float : file_descr -> socket_float_option -> float
```
Same as [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) for a socket option whose value is a floating-point number.
```
val setsockopt_float : file_descr -> socket_float_option -> float -> unit
```
Same as [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt) for a socket option whose value is a floating-point number.
```
val getsockopt_error : file_descr -> error option
```
Return the error condition associated with the given socket, and clear it.
High-level network connection functions
---------------------------------------
```
val open_connection : sockaddr -> in_channel * out_channel
```
Connect to a server at the given address. Return a pair of buffered channels connected to the server. Remember to call [`flush`](stdlib#VALflush) on the output channel at the right times to ensure correct synchronization.
The two channels returned by `open_connection` share a descriptor to a socket. Therefore, when the connection is over, you should call [`close_out`](stdlib#VALclose_out) on the output channel, which will also close the underlying socket. Do not call [`close_in`](stdlib#VALclose_in) on the input channel; it will be collected by the GC eventually.
```
val shutdown_connection : in_channel -> unit
```
``Shut down'' a connection established with [`UnixLabels.open_connection`](unixlabels#VALopen_connection); that is, transmit an end-of-file condition to the server reading on the other side of the connection. This does not close the socket and the channels used by the connection. See [`Unix.open_connection`](unix#VALopen_connection) for how to close them once the connection is over.
```
val establish_server : (in_channel -> out_channel -> unit) -> addr:sockaddr -> unit
```
Establish a server on the given address. The function given as first argument is called for each connection with two buffered channels connected to the client. A new process is created for each connection. The function [`UnixLabels.establish_server`](unixlabels#VALestablish_server) never returns normally.
The two channels given to the function share a descriptor to a socket. The function does not need to close the channels, since this occurs automatically when the function returns. If the function prefers explicit closing, it should close the output channel using [`close_out`](stdlib#VALclose_out) and leave the input channel unclosed, for reasons explained in [`Unix.in_channel_of_descr`](unix#VALin_channel_of_descr).
* **Raises** `Invalid_argument` on Windows. Use threads instead.
Host and protocol databases
---------------------------
```
type host_entry = Unix.host_entry = {
```
| | |
| --- | --- |
| | `h\_name : `string`;` |
| | `h\_aliases : `string array`;` |
| | `h\_addrtype : `[socket\_domain](unixlabels#TYPEsocket_domain)`;` |
| | `h\_addr\_list : `[inet\_addr](unixlabels#TYPEinet_addr) array`;` |
`}` Structure of entries in the `hosts` database.
```
type protocol_entry = Unix.protocol_entry = {
```
| | |
| --- | --- |
| | `p\_name : `string`;` |
| | `p\_aliases : `string array`;` |
| | `p\_proto : `int`;` |
`}` Structure of entries in the `protocols` database.
```
type service_entry = Unix.service_entry = {
```
| | |
| --- | --- |
| | `s\_name : `string`;` |
| | `s\_aliases : `string array`;` |
| | `s\_port : `int`;` |
| | `s\_proto : `string`;` |
`}` Structure of entries in the `services` database.
```
val gethostname : unit -> string
```
Return the name of the local host.
```
val gethostbyname : string -> host_entry
```
Find an entry in `hosts` with the given name.
* **Raises** `Not_found` if no such entry exists.
```
val gethostbyaddr : inet_addr -> host_entry
```
Find an entry in `hosts` with the given address.
* **Raises** `Not_found` if no such entry exists.
```
val getprotobyname : string -> protocol_entry
```
Find an entry in `protocols` with the given name.
* **Raises** `Not_found` if no such entry exists.
```
val getprotobynumber : int -> protocol_entry
```
Find an entry in `protocols` with the given protocol number.
* **Raises** `Not_found` if no such entry exists.
```
val getservbyname : string -> protocol:string -> service_entry
```
Find an entry in `services` with the given name.
* **Raises** `Not_found` if no such entry exists.
```
val getservbyport : int -> protocol:string -> service_entry
```
Find an entry in `services` with the given service number.
* **Raises** `Not_found` if no such entry exists.
```
type addr_info = Unix.addr_info = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `ai\_family : `[socket\_domain](unixlabels#TYPEsocket_domain)`;` | `(*` | Socket domain | `*)` |
| | `ai\_socktype : `[socket\_type](unixlabels#TYPEsocket_type)`;` | `(*` | Socket type | `*)` |
| | `ai\_protocol : `int`;` | `(*` | Socket protocol number | `*)` |
| | `ai\_addr : `[sockaddr](unixlabels#TYPEsockaddr)`;` | `(*` | Address | `*)` |
| | `ai\_canonname : `string`;` | `(*` | Canonical host name | `*)` |
`}` Address information returned by [`UnixLabels.getaddrinfo`](unixlabels#VALgetaddrinfo).
```
type getaddrinfo_option = Unix.getaddrinfo_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `AI\_FAMILY of `[socket\_domain](unixlabels#TYPEsocket_domain)`` | `(*` | Impose the given socket domain | `*)` |
| `|` | `AI\_SOCKTYPE of `[socket\_type](unixlabels#TYPEsocket_type)`` | `(*` | Impose the given socket type | `*)` |
| `|` | `AI\_PROTOCOL of `int`` | `(*` | Impose the given protocol | `*)` |
| `|` | `AI\_NUMERICHOST` | `(*` | Do not call name resolver, expect numeric IP address | `*)` |
| `|` | `AI\_CANONNAME` | `(*` | Fill the `ai_canonname` field of the result | `*)` |
| `|` | `AI\_PASSIVE` | `(*` | Set address to ``any'' address for use with [`UnixLabels.bind`](unixlabels#VALbind) | `*)` |
Options to [`UnixLabels.getaddrinfo`](unixlabels#VALgetaddrinfo).
```
val getaddrinfo : string -> string -> getaddrinfo_option list -> addr_info list
```
`getaddrinfo host service opts` returns a list of [`UnixLabels.addr_info`](unixlabels#TYPEaddr_info) records describing socket parameters and addresses suitable for communicating with the given host and service. The empty list is returned if the host or service names are unknown, or the constraints expressed in `opts` cannot be satisfied.
`host` is either a host name or the string representation of an IP address. `host` can be given as the empty string; in this case, the ``any'' address or the ``loopback'' address are used, depending whether `opts` contains `AI\_PASSIVE`. `service` is either a service name or the string representation of a port number. `service` can be given as the empty string; in this case, the port field of the returned addresses is set to 0. `opts` is a possibly empty list of options that allows the caller to force a particular socket domain (e.g. IPv6 only or IPv4 only) or a particular socket type (e.g. TCP only or UDP only).
```
type name_info = Unix.name_info = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `ni\_hostname : `string`;` | `(*` | Name or IP address of host | `*)` |
| | `ni\_service : `string`;` | `(*` | Name of service or port number | `*)` |
`}` Host and service information returned by [`UnixLabels.getnameinfo`](unixlabels#VALgetnameinfo).
```
type getnameinfo_option = Unix.getnameinfo_option =
```
| | | | | |
| --- | --- | --- | --- | --- |
| `|` | `NI\_NOFQDN` | `(*` | Do not qualify local host names | `*)` |
| `|` | `NI\_NUMERICHOST` | `(*` | Always return host as IP address | `*)` |
| `|` | `NI\_NAMEREQD` | `(*` | Fail if host name cannot be determined | `*)` |
| `|` | `NI\_NUMERICSERV` | `(*` | Always return service as port number | `*)` |
| `|` | `NI\_DGRAM` | `(*` | Consider the service as UDP-based instead of the default TCP | `*)` |
Options to [`UnixLabels.getnameinfo`](unixlabels#VALgetnameinfo).
```
val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
```
`getnameinfo addr opts` returns the host name and service name corresponding to the socket address `addr`. `opts` is a possibly empty list of options that governs how these names are obtained.
* **Raises** `Not_found` if an error occurs.
Terminal interface
------------------
The following functions implement the POSIX standard terminal interface. They provide control over asynchronous communication ports and pseudo-terminals. Refer to the `termios` man page for a complete description.
```
type terminal_io = Unix.terminal_io = {
```
| | | | | |
| --- | --- | --- | --- | --- |
| | `mutable c\_ignbrk : `bool`;` | `(*` | Ignore the break condition. | `*)` |
| | `mutable c\_brkint : `bool`;` | `(*` | Signal interrupt on break condition. | `*)` |
| | `mutable c\_ignpar : `bool`;` | `(*` | Ignore characters with parity errors. | `*)` |
| | `mutable c\_parmrk : `bool`;` | `(*` | Mark parity errors. | `*)` |
| | `mutable c\_inpck : `bool`;` | `(*` | Enable parity check on input. | `*)` |
| | `mutable c\_istrip : `bool`;` | `(*` | Strip 8th bit on input characters. | `*)` |
| | `mutable c\_inlcr : `bool`;` | `(*` | Map NL to CR on input. | `*)` |
| | `mutable c\_igncr : `bool`;` | `(*` | Ignore CR on input. | `*)` |
| | `mutable c\_icrnl : `bool`;` | `(*` | Map CR to NL on input. | `*)` |
| | `mutable c\_ixon : `bool`;` | `(*` | Recognize XON/XOFF characters on input. | `*)` |
| | `mutable c\_ixoff : `bool`;` | `(*` | Emit XON/XOFF chars to control input flow. | `*)` |
| | `mutable c\_opost : `bool`;` | `(*` | Enable output processing. | `*)` |
| | `mutable c\_obaud : `int`;` | `(*` | Output baud rate (0 means close connection). | `*)` |
| | `mutable c\_ibaud : `int`;` | `(*` | Input baud rate. | `*)` |
| | `mutable c\_csize : `int`;` | `(*` | Number of bits per character (5-8). | `*)` |
| | `mutable c\_cstopb : `int`;` | `(*` | Number of stop bits (1-2). | `*)` |
| | `mutable c\_cread : `bool`;` | `(*` | Reception is enabled. | `*)` |
| | `mutable c\_parenb : `bool`;` | `(*` | Enable parity generation and detection. | `*)` |
| | `mutable c\_parodd : `bool`;` | `(*` | Specify odd parity instead of even. | `*)` |
| | `mutable c\_hupcl : `bool`;` | `(*` | Hang up on last close. | `*)` |
| | `mutable c\_clocal : `bool`;` | `(*` | Ignore modem status lines. | `*)` |
| | `mutable c\_isig : `bool`;` | `(*` | Generate signal on INTR, QUIT, SUSP. | `*)` |
| | `mutable c\_icanon : `bool`;` | `(*` | Enable canonical processing (line buffering and editing) | `*)` |
| | `mutable c\_noflsh : `bool`;` | `(*` | Disable flush after INTR, QUIT, SUSP. | `*)` |
| | `mutable c\_echo : `bool`;` | `(*` | Echo input characters. | `*)` |
| | `mutable c\_echoe : `bool`;` | `(*` | Echo ERASE (to erase previous character). | `*)` |
| | `mutable c\_echok : `bool`;` | `(*` | Echo KILL (to erase the current line). | `*)` |
| | `mutable c\_echonl : `bool`;` | `(*` | Echo NL even if c\_echo is not set. | `*)` |
| | `mutable c\_vintr : `char`;` | `(*` | Interrupt character (usually ctrl-C). | `*)` |
| | `mutable c\_vquit : `char`;` | `(*` | Quit character (usually ctrl-\). | `*)` |
| | `mutable c\_verase : `char`;` | `(*` | Erase character (usually DEL or ctrl-H). | `*)` |
| | `mutable c\_vkill : `char`;` | `(*` | Kill line character (usually ctrl-U). | `*)` |
| | `mutable c\_veof : `char`;` | `(*` | End-of-file character (usually ctrl-D). | `*)` |
| | `mutable c\_veol : `char`;` | `(*` | Alternate end-of-line char. (usually none). | `*)` |
| | `mutable c\_vmin : `int`;` | `(*` | Minimum number of characters to read before the read request is satisfied. | `*)` |
| | `mutable c\_vtime : `int`;` | `(*` | Maximum read wait (in 0.1s units). | `*)` |
| | `mutable c\_vstart : `char`;` | `(*` | Start character (usually ctrl-Q). | `*)` |
| | `mutable c\_vstop : `char`;` | `(*` | Stop character (usually ctrl-S). | `*)` |
`}`
```
val tcgetattr : file_descr -> terminal_io
```
Return the status of the terminal referred to by the given file descriptor.
* **Raises** `Invalid_argument` on Windows
```
type setattr_when = Unix.setattr_when =
```
| | |
| --- | --- |
| `|` | `TCSANOW` |
| `|` | `TCSADRAIN` |
| `|` | `TCSAFLUSH` |
```
val tcsetattr : file_descr -> mode:setattr_when -> terminal_io -> unit
```
Set the status of the terminal referred to by the given file descriptor. The second argument indicates when the status change takes place: immediately (`TCSANOW`), when all pending output has been transmitted (`TCSADRAIN`), or after flushing all input that has been received but not read (`TCSAFLUSH`). `TCSADRAIN` is recommended when changing the output parameters; `TCSAFLUSH`, when changing the input parameters.
* **Raises** `Invalid_argument` on Windows
```
val tcsendbreak : file_descr -> duration:int -> unit
```
Send a break condition on the given file descriptor. The second argument is the duration of the break, in 0.1s units; 0 means standard duration (0.25s).
* **Raises** `Invalid_argument` on Windows
```
val tcdrain : file_descr -> unit
```
Waits until all output written on the given file descriptor has been transmitted.
* **Raises** `Invalid_argument` on Windows
```
type flush_queue = Unix.flush_queue =
```
| | |
| --- | --- |
| `|` | `TCIFLUSH` |
| `|` | `TCOFLUSH` |
| `|` | `TCIOFLUSH` |
```
val tcflush : file_descr -> mode:flush_queue -> unit
```
Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: `TCIFLUSH` flushes data received but not read, `TCOFLUSH` flushes data written but not transmitted, and `TCIOFLUSH` flushes both.
* **Raises** `Invalid_argument` on Windows
```
type flow_action = Unix.flow_action =
```
| | |
| --- | --- |
| `|` | `TCOOFF` |
| `|` | `TCOON` |
| `|` | `TCIOFF` |
| `|` | `TCION` |
```
val tcflow : file_descr -> mode:flow_action -> unit
```
Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: `TCOOFF` suspends output, `TCOON` restarts output, `TCIOFF` transmits a STOP character to suspend input, and `TCION` transmits a START character to restart input.
* **Raises** `Invalid_argument` on Windows
```
val setsid : unit -> int
```
Put the calling process in a new session and detach it from its controlling terminal.
* **Raises** `Invalid_argument` on Windows
| programming_docs |
ocaml Functor Ephemeron.K1.MakeSeeded Functor Ephemeron.K1.MakeSeeded
===============================
```
module MakeSeeded: functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H.t
```
Functor building an implementation of a weak hash table. The seed is similar to the one of [`Hashtbl.MakeSeeded`](hashtbl.makeseeded).
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `H` | : | `[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)` |
|
```
type key
```
```
type 'a t
```
```
val create : ?random:bool -> int -> 'a t
```
```
val clear : 'a t -> unit
```
```
val reset : 'a t -> unit
```
```
val copy : 'a t -> 'a t
```
```
val add : 'a t -> key -> 'a -> unit
```
```
val remove : 'a t -> key -> unit
```
```
val find : 'a t -> key -> 'a
```
```
val find_opt : 'a t -> key -> 'a option
```
```
val find_all : 'a t -> key -> 'a list
```
```
val replace : 'a t -> key -> 'a -> unit
```
```
val mem : 'a t -> key -> bool
```
```
val length : 'a t -> int
```
```
val stats : 'a t -> Hashtbl.statistics
```
```
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
```
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
```
val clean : 'a t -> unit
```
remove all dead bindings. Done automatically during automatic resizing.
```
val stats_alive : 'a t -> Hashtbl.statistics
```
same as [`Hashtbl.SeededS.stats`](hashtbl.seededs#VALstats) but only count the alive bindings
ocaml Module Printf Module Printf
=============
```
module Printf: sig .. end
```
Formatted output functions.
```
val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a
```
`fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`.
The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments.
Conversion specifications have the following form:
`% [flags] [width] [.precision] type`
In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters.
The types and their meanings are:
* `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability.
* `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability.
* `x`: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag `#` adds a `0x` prefix to non zero values.
* `X`: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag `#` adds a `0X` prefix to non zero values.
* `o`: convert an integer argument to unsigned octal. The flag `#` adds a `0` prefix to non zero values.
* `s`: insert a string argument.
* `S`: convert a string argument to OCaml syntax (double quotes, escapes).
* `c`: insert a character argument.
* `C`: convert a character argument to OCaml syntax (single quotes, escapes).
* `f`: convert a floating-point argument to decimal notation, in the style `dddd.ddd`.
* `F`: convert a floating-point argument to OCaml syntax (`dddd.` or `dddd.ddd` or `d.ddd e+-dd`). Converts to hexadecimal with the `#` flag (see `h`).
* `e` or `E`: convert a floating-point argument to decimal notation, in the style `d.ddd e+-dd` (mantissa and exponent).
* `g` or `G`: convert a floating-point argument to decimal notation, in style `f` or `e`, `E` (whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining.
* `h` or `H`: convert a floating-point argument to hexadecimal notation, in the style `0xh.hhhh p+-dd` (hexadecimal mantissa, exponent in decimal and denotes a power of 2).
* `B`: convert a boolean argument to the string `true` or `false`
* `b`: convert a boolean argument (deprecated; do not use in new programs).
* `ld`, `li`, `lu`, `lx`, `lX`, `lo`: convert an `int32` argument to the format specified by the second letter (decimal, hexadecimal, etc).
* `nd`, `ni`, `nu`, `nx`, `nX`, `no`: convert a `nativeint` argument to the format specified by the second letter.
* `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: convert an `int64` argument to the format specified by the second letter.
* `a`: user-defined printer. Take two arguments and apply the first one to `outchan` (the current output channel) and to the second argument. The first argument must therefore have type `out_channel -> 'b -> unit` and the second `'b`. The output produced by the function is inserted in the output of `fprintf` at the current point.
* `t`: same as `%a`, but take only one argument (with type `out_channel -> unit`) and apply it to `outchan`.
* `{ fmt %}`: convert a format string argument to its type digest. The argument must have the same type as the internal format string `fmt`.
* `( fmt %)`: format string substitution. Take a format string argument and substitute it to the internal format string `fmt` to print following arguments. The argument must have the same type as the internal format string `fmt`.
* `!`: take no argument and flush the output.
* `%`: take no argument and output one `%` character.
* `@`: take no argument and output one `@` character.
* `,`: take no argument and output nothing: a no-op delimiter for conversion specifications.
The optional `flags` are:
* `-`: left-justify the output (default is right justification).
* `0`: for numerical conversions, pad with zeroes instead of spaces.
* `+`: for signed numerical conversions, prefix number with a `+` sign if positive.
* space: for signed numerical conversions, prefix number with a space if positive.
* `#`: request an alternate formatting style for the integer types and the floating-point type `F`.
The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters.
The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits.
The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float.
```
val printf : ('a, out_channel, unit) format -> 'a
```
Same as [`Printf.fprintf`](printf#VALfprintf), but output on `stdout`.
```
val eprintf : ('a, out_channel, unit) format -> 'a
```
Same as [`Printf.fprintf`](printf#VALfprintf), but output on `stderr`.
```
val sprintf : ('a, unit, string) format -> 'a
```
Same as [`Printf.fprintf`](printf#VALfprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments.
```
val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a
```
Same as [`Printf.fprintf`](printf#VALfprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](buffer)).
```
val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a
```
Same as [`Printf.fprintf`](printf#VALfprintf), but does not print anything. Useful to ignore some material when conditionally printing.
* **Since** 3.10.0
```
val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a
```
Same as [`Printf.bprintf`](printf#VALbprintf), but does not print anything. Useful to ignore some material when conditionally printing.
* **Since** 4.11.0
Formatted output functions with continuations.
```
val kfprintf : (out_channel -> 'd) -> out_channel -> ('a, out_channel, unit, 'd) format4 -> 'a
```
Same as `fprintf`, but instead of returning immediately, passes the out channel to its first argument at the end of printing.
* **Since** 3.09.0
```
val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a
```
Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.
* **Since** 4.01.0
```
val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a
```
Same as `sprintf` above, but instead of returning the string, passes it to the first argument.
* **Since** 3.09.0
```
val kbprintf : (Buffer.t -> 'd) -> Buffer.t -> ('a, Buffer.t, unit, 'd) format4 -> 'a
```
Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing.
* **Since** 3.10.0
```
val ikbprintf : (Buffer.t -> 'd) -> Buffer.t -> ('a, Buffer.t, unit, 'd) format4 -> 'a
```
Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.
* **Since** 4.11.0
Deprecated
```
val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a
```
Deprecated. Use Printf.ksprintf instead. A deprecated synonym for `ksprintf`.
ocaml Module Ephemeron.Kn.Bucket Module Ephemeron.Kn.Bucket
==========================
```
module Bucket: sig .. end
```
```
type ('k, 'd) t
```
A bucket is a mutable "list" of ephemerons.
```
val make : unit -> ('k, 'd) t
```
Create a new bucket.
```
val add : ('k, 'd) t -> 'k array -> 'd -> unit
```
Add an ephemeron to the bucket.
```
val remove : ('k, 'd) t -> 'k array -> unit
```
`remove b k` removes from `b` the most-recently added ephemeron with keys `k`, or does nothing if there is no such ephemeron.
```
val find : ('k, 'd) t -> 'k array -> 'd option
```
Returns the data of the most-recently added ephemeron with the given keys, or `None` if there is no such ephemeron.
```
val length : ('k, 'd) t -> int
```
Returns an upper bound on the length of the bucket.
```
val clear : ('k, 'd) t -> unit
```
Remove all ephemerons from the bucket.
ocaml Module Filename Module Filename
===============
```
module Filename: sig .. end
```
Operations on file names.
```
val current_dir_name : string
```
The conventional name for the current directory (e.g. `.` in Unix).
```
val parent_dir_name : string
```
The conventional name for the parent of the current directory (e.g. `..` in Unix).
```
val dir_sep : string
```
The directory separator (e.g. `/` in Unix).
* **Since** 3.11.2
```
val concat : string -> string -> string
```
`concat dir file` returns a file name that designates file `file` in directory `dir`.
```
val is_relative : string -> bool
```
Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`).
```
val is_implicit : string -> bool
```
Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory.
```
val check_suffix : string -> string -> bool
```
`check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
```
val chop_suffix : string -> string -> string
```
`chop_suffix name suff` removes the suffix `suff` from the filename `name`.
* **Raises** `Invalid_argument` if `name` does not end with the suffix `suff`.
```
val chop_suffix_opt : suffix:string -> string -> string option
```
`chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix.
Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.
* **Since** 4.08
```
val extension : string -> string
```
`extension name` is the shortest suffix `ext` of `name0` where:
* `name0` is the longest suffix of `name` that does not contain a directory separator;
* `ext` starts with a period;
* `ext` is preceded by at least one non-period character in `name0`.
If such a suffix does not exist, `extension name` is the empty string.
* **Since** 4.04
```
val remove_extension : string -> string
```
Return the given file name without its extension, as defined in [`Filename.extension`](filename#VALextension). If the extension is empty, the function returns the given file name.
The following invariant holds for any file name `s`:
`remove_extension s ^ extension s = s`
* **Since** 4.04
```
val chop_extension : string -> string
```
Same as [`Filename.remove_extension`](filename#VALremove_extension), but raise `Invalid\_argument` if the given name has an empty extension.
```
val basename : string -> string
```
Split a file name into directory name / base file name. If `name` is a valid file name, then `concat (dirname name) (basename name)` returns a file name which is equivalent to `name`. Moreover, after setting the current directory to `dirname name` (with [`Sys.chdir`](sys#VALchdir)), references to `basename name` (which is a relative file name) designate the same file as `name` before the call to [`Sys.chdir`](sys#VALchdir).
This function conforms to the specification of POSIX.1-2008 for the `basename` utility.
```
val dirname : string -> string
```
See [`Filename.basename`](filename#VALbasename). This function conforms to the specification of POSIX.1-2008 for the `dirname` utility.
```
val null : string
```
`null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. It represents a file on the OS that discards all writes and returns end of file on reads.
* **Since** 4.10.0
```
val temp_file : ?temp_dir:string -> string -> string -> string
```
`temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](filename#VALget_temp_dir_name). The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called.
* **Before 3.11.2** no ?temp\_dir optional argument
* **Raises** `Sys_error` if the file could not be created.
```
val open_temp_file : ?mode:open_flag list -> ?perms:int -> ?temp_dir:string -> string -> string -> string * out_channel
```
Same as [`Filename.temp_file`](filename#VALtemp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open\_append`, `Open\_binary`, and `Open\_text`. The default is `[Open\_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`).
* **Before 4.03.0** no ?perms optional argument
* **Before 3.11.2** no ?temp\_dir optional argument
* **Raises** `Sys_error` if the file could not be opened.
```
val get_temp_dir_name : unit -> string
```
The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the `TEMP` environment variable, or "." if the variable is not set. The temporary directory can be changed with [`Filename.set_temp_dir_name`](filename#VALset_temp_dir_name).
* **Since** 4.00.0
```
val set_temp_dir_name : string -> unit
```
Change the temporary directory returned by [`Filename.get_temp_dir_name`](filename#VALget_temp_dir_name) and used by [`Filename.temp_file`](filename#VALtemp_file) and [`Filename.open_temp_file`](filename#VALopen_temp_file). The temporary directory is a domain-local value which is inherited by child domains.
* **Since** 4.00.0
```
val quote : string -> string
```
Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions.
```
val quote_command : string -> ?stdin:string -> ?stdout:string -> ?stderr:string -> string list -> string
```
`quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](sys#VALcommand), [`Unix.system`](unix#VALsystem), and the [`Unix.open_process`](unix#VALopen_process) functions.
The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty.
The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`.
Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using [`Filename.quote`](filename#VALquote), then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by [`Sys.command`](sys#VALcommand).
* **Since** 4.10.0
* **Raises** `Failure` if the command cannot be escaped on the current platform.
ocaml Index of types Index of types
==============
| |
| --- |
| A |
| [acc](camlinternalformat#TYPEacc) [[CamlinternalFormat](camlinternalformat)] | |
| [acc\_formatting\_gen](camlinternalformat#TYPEacc_formatting_gen) [[CamlinternalFormat](camlinternalformat)] | |
| [access\_permission](unixlabels#TYPEaccess_permission) [[UnixLabels](unixlabels)] | Flags for the [`UnixLabels.access`](unixlabels#VALaccess) call. |
| [access\_permission](unix#TYPEaccess_permission) [[Unix](unix)] | Flags for the [`Unix.access`](unix#VALaccess) call. |
| [addr\_info](unixlabels#TYPEaddr_info) [[UnixLabels](unixlabels)] | Address information returned by [`UnixLabels.getaddrinfo`](unixlabels#VALgetaddrinfo). |
| [addr\_info](unix#TYPEaddr_info) [[Unix](unix)] | Address information returned by [`Unix.getaddrinfo`](unix#VALgetaddrinfo). |
| [alarm](gc#TYPEalarm) [[Gc](gc)] | An alarm is a piece of data that calls a user function at the end of each major GC cycle. |
| [allocation](gc.memprof#TYPEallocation) [[Gc.Memprof](gc.memprof)] | The type of metadata associated with allocations. |
| [allocation\_source](gc.memprof#TYPEallocation_source) [[Gc.Memprof](gc.memprof)] | |
| [anon\_fun](arg#TYPEanon_fun) [[Arg](arg)] | |
| B |
| [backend\_type](sys#TYPEbackend_type) [[Sys](sys)] | Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript. |
| [backtrace\_slot](printexc#TYPEbacktrace_slot) [[Printexc](printexc)] | The abstract type `backtrace_slot` represents a single slot of a backtrace. |
| [block\_type](camlinternalformatbasics#TYPEblock_type) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| C |
| [c\_layout](bigarray#TYPEc_layout) [[Bigarray](bigarray)] | See [`Bigarray.fortran_layout`](bigarray#TYPEfortran_layout). |
| [channel](event#TYPEchannel) [[Event](event)] | The type of communication channels carrying values of type `'a`. |
| [char\_set](camlinternalformatbasics#TYPEchar_set) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [closure](camlinternaloo#TYPEclosure) [[CamlinternalOO](camlinternaloo)] | |
| [complex32\_elt](bigarray#TYPEcomplex32_elt) [[Bigarray](bigarray)] | |
| [complex64\_elt](bigarray#TYPEcomplex64_elt) [[Bigarray](bigarray)] | |
| [continuation](effect.shallow#TYPEcontinuation) [[Effect.Shallow](effect.shallow)] | `('a,'b) continuation` is a delimited continuation that expects a `'a` value and returns a `'b` value. |
| [continuation](effect.deep#TYPEcontinuation) [[Effect.Deep](effect.deep)] | `('a,'b) continuation` is a delimited continuation that expects a `'a` value and returns a `'b` value. |
| [control](gc#TYPEcontrol) [[Gc](gc)] | The GC parameters are given as a `control` record. |
| [counter](camlinternalformatbasics#TYPEcounter) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [cursor](runtime_events#TYPEcursor) [[Runtime\_events](runtime_events)] | Type of the cursor used when consuming |
| [custom\_arity](camlinternalformatbasics#TYPEcustom_arity) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| D |
| [data](weak.s#TYPEdata) [[Weak.S](weak.s)] | The type of the elements stored in the table. |
| [dir\_handle](unixlabels#TYPEdir_handle) [[UnixLabels](unixlabels)] | The type of descriptors over opened directories. |
| [dir\_handle](unix#TYPEdir_handle) [[Unix](unix)] | The type of descriptors over opened directories. |
| [doc](arg#TYPEdoc) [[Arg](arg)] | |
| E |
| [effect\_handler](effect.deep#TYPEeffect_handler) [[Effect.Deep](effect.deep)] | `'a effect_handler` is a deep handler with an identity value handler `fun x -> x` and an exception handler that raises any exception `fun e -> raise e`. |
| [elt](set.s#TYPEelt) [[Set.S](set.s)] | The type of the set elements. |
| [elt](morelabels.set.s#TYPEelt) [[MoreLabels.Set.S](morelabels.set.s)] | The type of the set elements. |
| [error](unixlabels#TYPEerror) [[UnixLabels](unixlabels)] | The type of error codes. |
| [error](unix#TYPEerror) [[Unix](unix)] | The type of error codes. |
| [error](dynlink#TYPEerror) [[Dynlink](dynlink)] | |
| [event](event#TYPEevent) [[Event](event)] | The type of communication events returning a result of type `'a`. |
| [extern\_flags](marshal#TYPEextern_flags) [[Marshal](marshal)] | The flags to the `Marshal.to_*` functions below. |
| [extra\_info](sys#TYPEextra_info) [[Sys](sys)] | |
| [extra\_prefix](sys#TYPEextra_prefix) [[Sys](sys)] | |
| F |
| [file\_descr](unixlabels#TYPEfile_descr) [[UnixLabels](unixlabels)] | The abstract type of file descriptors. |
| [file\_descr](unix#TYPEfile_descr) [[Unix](unix)] | The abstract type of file descriptors. |
| [file\_kind](unixlabels#TYPEfile_kind) [[UnixLabels](unixlabels)] | |
| [file\_kind](unix#TYPEfile_kind) [[Unix](unix)] | |
| [file\_name](scanf.scanning#TYPEfile_name) [[Scanf.Scanning](scanf.scanning)] | A convenient alias to designate a file name. |
| [file\_perm](unixlabels#TYPEfile_perm) [[UnixLabels](unixlabels)] | The type of file access rights, e.g. |
| [file\_perm](unix#TYPEfile_perm) [[Unix](unix)] | The type of file access rights, e.g. |
| [float32\_elt](bigarray#TYPEfloat32_elt) [[Bigarray](bigarray)] | |
| [float64\_elt](bigarray#TYPEfloat64_elt) [[Bigarray](bigarray)] | |
| [float\_conv](camlinternalformatbasics#TYPEfloat_conv) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [float\_flag\_conv](camlinternalformatbasics#TYPEfloat_flag_conv) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [float\_kind\_conv](camlinternalformatbasics#TYPEfloat_kind_conv) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [flow\_action](unixlabels#TYPEflow_action) [[UnixLabels](unixlabels)] | |
| [flow\_action](unix#TYPEflow_action) [[Unix](unix)] | |
| [flush\_queue](unixlabels#TYPEflush_queue) [[UnixLabels](unixlabels)] | |
| [flush\_queue](unix#TYPEflush_queue) [[Unix](unix)] | |
| [fmt](camlinternalformatbasics#TYPEfmt) [[CamlinternalFormatBasics](camlinternalformatbasics)] | List of format elements. |
| [fmt\_ebb](camlinternalformat#TYPEfmt_ebb) [[CamlinternalFormat](camlinternalformat)] | |
| [fmtty](camlinternalformatbasics#TYPEfmtty) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [fmtty\_rel](camlinternalformatbasics#TYPEfmtty_rel) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [format](stdlib#TYPEformat) [[Stdlib](stdlib)] | |
| [format4](stdlib#TYPEformat4) [[Stdlib](stdlib)] | |
| [format6](stdlib#TYPEformat6) [[Stdlib](stdlib)] | |
| [format6](camlinternalformatbasics#TYPEformat6) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [formatter](format#TYPEformatter) [[Format](format)] | Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. |
| [formatter\_out\_functions](format#TYPEformatter_out_functions) [[Format](format)] | The set of output functions specific to a formatter: the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`., the `out_flush` function flushes the pretty-printer output device., `out_newline` is called to open a new line when the pretty-printer splits the line., the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output., the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. By default: fields `out_string` and `out_flush` are output device specific; (e.g. [`output_string`](stdlib#VALoutput_string) and [`flush`](stdlib#VALflush) for a [`out_channel`](stdlib#TYPEout_channel) device, or `Buffer.add_substring` and [`ignore`](stdlib#VALignore) for a `Buffer.t` output device),, field `out_newline` is equivalent to `out_string "\n" 0 1`;, fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`. |
| [formatter\_stag\_functions](format#TYPEformatter_stag_functions) [[Format](format)] | The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. |
| [formatting\_gen](camlinternalformatbasics#TYPEformatting_gen) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [formatting\_lit](camlinternalformatbasics#TYPEformatting_lit) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [fortran\_layout](bigarray#TYPEfortran_layout) [[Bigarray](bigarray)] | To facilitate interoperability with existing C and Fortran code, this library supports two different memory layouts for Bigarrays, one compatible with the C conventions, the other compatible with the Fortran conventions. |
| [fpclass](float#TYPEfpclass) [[Float](float)] | The five classes of floating-point numbers, as determined by the [`Float.classify_float`](float#VALclassify_float) function. |
| [fpclass](stdlib#TYPEfpclass) [[Stdlib](stdlib)] | The five classes of floating-point numbers, as determined by the [`classify_float`](stdlib#VALclassify_float) function. |
| G |
| [geometry](format#TYPEgeometry) [[Format](format)] | |
| [getaddrinfo\_option](unixlabels#TYPEgetaddrinfo_option) [[UnixLabels](unixlabels)] | Options to [`UnixLabels.getaddrinfo`](unixlabels#VALgetaddrinfo). |
| [getaddrinfo\_option](unix#TYPEgetaddrinfo_option) [[Unix](unix)] | Options to [`Unix.getaddrinfo`](unix#VALgetaddrinfo). |
| [getnameinfo\_option](unixlabels#TYPEgetnameinfo_option) [[UnixLabels](unixlabels)] | Options to [`UnixLabels.getnameinfo`](unixlabels#VALgetnameinfo). |
| [getnameinfo\_option](unix#TYPEgetnameinfo_option) [[Unix](unix)] | Options to [`Unix.getnameinfo`](unix#VALgetnameinfo). |
| [group\_entry](unixlabels#TYPEgroup_entry) [[UnixLabels](unixlabels)] | Structure of entries in the `groups` database. |
| [group\_entry](unix#TYPEgroup_entry) [[Unix](unix)] | Structure of entries in the `groups` database. |
| H |
| [handler](effect.shallow#TYPEhandler) [[Effect.Shallow](effect.shallow)] | `('a,'b) handler` is a handler record with three fields -- `retc` is the value handler, `exnc` handles exceptions, and `effc` handles the effects performed by the computation enclosed by the handler. |
| [handler](effect.deep#TYPEhandler) [[Effect.Deep](effect.deep)] | `('a,'b) handler` is a handler record with three fields -- `retc` is the value handler, `exnc` handles exceptions, and `effc` handles the effects performed by the computation enclosed by the handler. |
| [heter\_list](camlinternalformat#TYPEheter_list) [[CamlinternalFormat](camlinternalformat)] | |
| [host\_entry](unixlabels#TYPEhost_entry) [[UnixLabels](unixlabels)] | Structure of entries in the `hosts` database. |
| [host\_entry](unix#TYPEhost_entry) [[Unix](unix)] | Structure of entries in the `hosts` database. |
| I |
| [id](domain#TYPEid) [[Domain](domain)] | Domains have unique integer identifiers |
| [ignored](camlinternalformatbasics#TYPEignored) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [impl](camlinternaloo#TYPEimpl) [[CamlinternalOO](camlinternaloo)] | |
| [in\_channel](scanf.scanning#TYPEin_channel) [[Scanf.Scanning](scanf.scanning)] | The notion of input channel for the [`Scanf`](scanf) module: those channels provide all the machinery necessary to read from any source of characters, including a [`in_channel`](stdlib#TYPEin_channel) value. |
| [in\_channel](stdlib#TYPEin_channel) [[Stdlib](stdlib)] | The type of input channel. |
| [inet\_addr](unixlabels#TYPEinet_addr) [[UnixLabels](unixlabels)] | The abstract type of Internet addresses. |
| [inet\_addr](unix#TYPEinet_addr) [[Unix](unix)] | The abstract type of Internet addresses. |
| [info](obj.closure#TYPEinfo) [[Obj.Closure](obj.closure)] | |
| [init\_table](camlinternaloo#TYPEinit_table) [[CamlinternalOO](camlinternaloo)] | |
| [int16\_signed\_elt](bigarray#TYPEint16_signed_elt) [[Bigarray](bigarray)] | |
| [int16\_unsigned\_elt](bigarray#TYPEint16_unsigned_elt) [[Bigarray](bigarray)] | |
| [int32\_elt](bigarray#TYPEint32_elt) [[Bigarray](bigarray)] | |
| [int64\_elt](bigarray#TYPEint64_elt) [[Bigarray](bigarray)] | |
| [int8\_signed\_elt](bigarray#TYPEint8_signed_elt) [[Bigarray](bigarray)] | |
| [int8\_unsigned\_elt](bigarray#TYPEint8_unsigned_elt) [[Bigarray](bigarray)] | |
| [int\_conv](camlinternalformatbasics#TYPEint_conv) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [int\_elt](bigarray#TYPEint_elt) [[Bigarray](bigarray)] | |
| [interval\_timer](unixlabels#TYPEinterval_timer) [[UnixLabels](unixlabels)] | The three kinds of interval timers. |
| [interval\_timer](unix#TYPEinterval_timer) [[Unix](unix)] | The three kinds of interval timers. |
| [interval\_timer\_status](unixlabels#TYPEinterval_timer_status) [[UnixLabels](unixlabels)] | The type describing the status of an interval timer |
| [interval\_timer\_status](unix#TYPEinterval_timer_status) [[Unix](unix)] | The type describing the status of an interval timer |
| K |
| [key](morelabels.map.s#TYPEkey) [[MoreLabels.Map.S](morelabels.map.s)] | The type of the map keys. |
| [key](morelabels.hashtbl.seededs#TYPEkey) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [key](morelabels.hashtbl.s#TYPEkey) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [key](map.s#TYPEkey) [[Map.S](map.s)] | The type of the map keys. |
| [key](hashtbl.seededs#TYPEkey) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [key](hashtbl.s#TYPEkey) [[Hashtbl.S](hashtbl.s)] | |
| [key](ephemeron.seededs#TYPEkey) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [key](ephemeron.s#TYPEkey) [[Ephemeron.S](ephemeron.s)] | |
| [key](domain.dls#TYPEkey) [[Domain.DLS](domain.dls)] | Type of a DLS key |
| [key](arg#TYPEkey) [[Arg](arg)] | |
| [kind](bigarray#TYPEkind) [[Bigarray](bigarray)] | To each element kind is associated an OCaml type, which is the type of OCaml values that can be stored in the Bigarray or read back from it. |
| L |
| [label](camlinternaloo#TYPElabel) [[CamlinternalOO](camlinternaloo)] | |
| [layout](bigarray#TYPElayout) [[Bigarray](bigarray)] | |
| [lexbuf](lexing#TYPElexbuf) [[Lexing](lexing)] | The type of lexer buffers. |
| [lifecycle](runtime_events#TYPElifecycle) [[Runtime\_events](runtime_events)] | Lifecycle events for the ring itself |
| [linking\_error](dynlink#TYPElinking_error) [[Dynlink](dynlink)] | |
| [location](printexc#TYPElocation) [[Printexc](printexc)] | The type of location information found in backtraces. |
| [lock\_command](unixlabels#TYPElock_command) [[UnixLabels](unixlabels)] | Commands for [`UnixLabels.lockf`](unixlabels#VALlockf). |
| [lock\_command](unix#TYPElock_command) [[Unix](unix)] | Commands for [`Unix.lockf`](unix#VALlockf). |
| M |
| [meth](camlinternaloo#TYPEmeth) [[CamlinternalOO](camlinternaloo)] | |
| [msg\_flag](unixlabels#TYPEmsg_flag) [[UnixLabels](unixlabels)] | The flags for [`UnixLabels.recv`](unixlabels#VALrecv), [`UnixLabels.recvfrom`](unixlabels#VALrecvfrom), [`UnixLabels.send`](unixlabels#VALsend) and [`UnixLabels.sendto`](unixlabels#VALsendto). |
| [msg\_flag](unix#TYPEmsg_flag) [[Unix](unix)] | The flags for [`Unix.recv`](unix#VALrecv), [`Unix.recvfrom`](unix#VALrecvfrom), [`Unix.send`](unix#VALsend) and [`Unix.sendto`](unix#VALsendto). |
| [mutable\_char\_set](camlinternalformat#TYPEmutable_char_set) [[CamlinternalFormat](camlinternalformat)] | |
| N |
| [name\_info](unixlabels#TYPEname_info) [[UnixLabels](unixlabels)] | Host and service information returned by [`UnixLabels.getnameinfo`](unixlabels#VALgetnameinfo). |
| [name\_info](unix#TYPEname_info) [[Unix](unix)] | Host and service information returned by [`Unix.getnameinfo`](unix#VALgetnameinfo). |
| [nativeint\_elt](bigarray#TYPEnativeint_elt) [[Bigarray](bigarray)] | |
| [node](seq#TYPEnode) [[Seq](seq)] | A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence. |
| O |
| [obj](camlinternaloo#TYPEobj) [[CamlinternalOO](camlinternaloo)] | |
| [obj\_t](obj.ephemeron#TYPEobj_t) [[Obj.Ephemeron](obj.ephemeron)] | alias for [`Obj.t`](obj#TYPEt) |
| [ocaml\_release\_info](sys#TYPEocaml_release_info) [[Sys](sys)] | |
| [open\_flag](unixlabels#TYPEopen_flag) [[UnixLabels](unixlabels)] | The flags to [`UnixLabels.openfile`](unixlabels#VALopenfile). |
| [open\_flag](unix#TYPEopen_flag) [[Unix](unix)] | The flags to [`Unix.openfile`](unix#VALopenfile). |
| [open\_flag](out_channel#TYPEopen_flag) [[Out\_channel](out_channel)] | Opening modes for [`Out\_channel.open_gen`](out_channel#VALopen_gen). |
| [open\_flag](in_channel#TYPEopen_flag) [[In\_channel](in_channel)] | Opening modes for [`In\_channel.open_gen`](in_channel#VALopen_gen). |
| [open\_flag](stdlib#TYPEopen_flag) [[Stdlib](stdlib)] | Opening modes for [`open_out_gen`](stdlib#VALopen_out_gen) and [`open_in_gen`](stdlib#VALopen_in_gen). |
| [out\_channel](stdlib#TYPEout_channel) [[Stdlib](stdlib)] | The type of output channel. |
| P |
| [pad\_option](camlinternalformatbasics#TYPEpad_option) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [padding](camlinternalformatbasics#TYPEpadding) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [padty](camlinternalformatbasics#TYPEpadty) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [param\_format\_ebb](camlinternalformat#TYPEparam_format_ebb) [[CamlinternalFormat](camlinternalformat)] | |
| [params](camlinternaloo#TYPEparams) [[CamlinternalOO](camlinternaloo)] | |
| [passwd\_entry](unixlabels#TYPEpasswd_entry) [[UnixLabels](unixlabels)] | Structure of entries in the `passwd` database. |
| [passwd\_entry](unix#TYPEpasswd_entry) [[Unix](unix)] | Structure of entries in the `passwd` database. |
| [position](lexing#TYPEposition) [[Lexing](lexing)] | A value of type `position` describes a point in a source file. |
| [prec\_option](camlinternalformatbasics#TYPEprec_option) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [precision](camlinternalformatbasics#TYPEprecision) [[CamlinternalFormatBasics](camlinternalformatbasics)] | |
| [process\_status](unixlabels#TYPEprocess_status) [[UnixLabels](unixlabels)] | The termination status of a process. |
| [process\_status](unix#TYPEprocess_status) [[Unix](unix)] | The termination status of a process. |
| [process\_times](unixlabels#TYPEprocess_times) [[UnixLabels](unixlabels)] | The execution times (CPU times) of a process. |
| [process\_times](unix#TYPEprocess_times) [[Unix](unix)] | The execution times (CPU times) of a process. |
| [protocol\_entry](unixlabels#TYPEprotocol_entry) [[UnixLabels](unixlabels)] | Structure of entries in the `protocols` database. |
| [protocol\_entry](unix#TYPEprotocol_entry) [[Unix](unix)] | Structure of entries in the `protocols` database. |
| R |
| [raw\_backtrace](printexc#TYPEraw_backtrace) [[Printexc](printexc)] | The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below. |
| [raw\_backtrace\_entry](printexc#TYPEraw_backtrace_entry) [[Printexc](printexc)] | A `raw_backtrace_entry` is an element of a `raw_backtrace`. |
| [raw\_backtrace\_slot](printexc#TYPEraw_backtrace_slot) [[Printexc](printexc)] | This type is used to iterate over the slots of a `raw_backtrace`. |
| [raw\_data](obj#TYPEraw_data) [[Obj](obj)] | |
| [ref](stdlib#TYPEref) [[Stdlib](stdlib)] | The type of references (mutable indirection cells) containing a value of type `'a`. |
| [regexp](str#TYPEregexp) [[Str](str)] | The type of compiled regular expressions. |
| [repr](sys.immediate64.make#TYPErepr) [[Sys.Immediate64.Make](sys.immediate64.make)] | |
| [result](stdlib#TYPEresult) [[Stdlib](stdlib)] | |
| [runtime\_counter](runtime_events#TYPEruntime_counter) [[Runtime\_events](runtime_events)] | The type for counter events emitted by the runtime |
| [runtime\_phase](runtime_events#TYPEruntime_phase) [[Runtime\_events](runtime_events)] | The type for span events emitted by the runtime |
| S |
| [scanbuf](scanf.scanning#TYPEscanbuf) [[Scanf.Scanning](scanf.scanning)] | The type of scanning buffers. |
| [scanner](scanf#TYPEscanner) [[Scanf](scanf)] | The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan
ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanf.Scanning.in_channel`](scanf.scanning#TYPEin_channel) formatted input channel `ic`. |
| [scanner\_opt](scanf#TYPEscanner_opt) [[Scanf](scanf)] | |
| [seek\_command](unixlabels#TYPEseek_command) [[UnixLabels](unixlabels)] | Positioning modes for [`UnixLabels.lseek`](unixlabels#VALlseek). |
| [seek\_command](unix#TYPEseek_command) [[Unix](unix)] | Positioning modes for [`Unix.lseek`](unix#VALlseek). |
| [service\_entry](unixlabels#TYPEservice_entry) [[UnixLabels](unixlabels)] | Structure of entries in the `services` database. |
| [service\_entry](unix#TYPEservice_entry) [[Unix](unix)] | Structure of entries in the `services` database. |
| [setattr\_when](unixlabels#TYPEsetattr_when) [[UnixLabels](unixlabels)] | |
| [setattr\_when](unix#TYPEsetattr_when) [[Unix](unix)] | |
| [shape](camlinternalmod#TYPEshape) [[CamlinternalMod](camlinternalmod)] | |
| [shutdown\_command](unixlabels#TYPEshutdown_command) [[UnixLabels](unixlabels)] | The type of commands for `shutdown`. |
| [shutdown\_command](unix#TYPEshutdown_command) [[Unix](unix)] | The type of commands for `shutdown`. |
| [signal\_behavior](sys#TYPEsignal_behavior) [[Sys](sys)] | What to do when receiving a signal: `Signal\_default`: take the default behavior (usually: abort the program), `Signal\_ignore`: ignore the signal, `Signal\_handle f`: call function `f`, giving it the signal number as argument. |
| [sigprocmask\_command](unixlabels#TYPEsigprocmask_command) [[UnixLabels](unixlabels)] | |
| [sigprocmask\_command](unix#TYPEsigprocmask_command) [[Unix](unix)] | |
| [sockaddr](unixlabels#TYPEsockaddr) [[UnixLabels](unixlabels)] | The type of socket addresses. |
| [sockaddr](unix#TYPEsockaddr) [[Unix](unix)] | The type of socket addresses. |
| [socket\_bool\_option](unixlabels#TYPEsocket_bool_option) [[UnixLabels](unixlabels)] | The socket options that can be consulted with [`UnixLabels.getsockopt`](unixlabels#VALgetsockopt) and modified with [`UnixLabels.setsockopt`](unixlabels#VALsetsockopt). |
| [socket\_bool\_option](unix#TYPEsocket_bool_option) [[Unix](unix)] | The socket options that can be consulted with [`Unix.getsockopt`](unix#VALgetsockopt) and modified with [`Unix.setsockopt`](unix#VALsetsockopt). |
| [socket\_domain](unixlabels#TYPEsocket_domain) [[UnixLabels](unixlabels)] | The type of socket domains. |
| [socket\_domain](unix#TYPEsocket_domain) [[Unix](unix)] | The type of socket domains. |
| [socket\_float\_option](unixlabels#TYPEsocket_float_option) [[UnixLabels](unixlabels)] | The socket options that can be consulted with [`UnixLabels.getsockopt_float`](unixlabels#VALgetsockopt_float) and modified with [`UnixLabels.setsockopt_float`](unixlabels#VALsetsockopt_float). |
| [socket\_float\_option](unix#TYPEsocket_float_option) [[Unix](unix)] | The socket options that can be consulted with [`Unix.getsockopt_float`](unix#VALgetsockopt_float) and modified with [`Unix.setsockopt_float`](unix#VALsetsockopt_float). |
| [socket\_int\_option](unixlabels#TYPEsocket_int_option) [[UnixLabels](unixlabels)] | The socket options that can be consulted with [`UnixLabels.getsockopt_int`](unixlabels#VALgetsockopt_int) and modified with [`UnixLabels.setsockopt_int`](unixlabels#VALsetsockopt_int). |
| [socket\_int\_option](unix#TYPEsocket_int_option) [[Unix](unix)] | The socket options that can be consulted with [`Unix.getsockopt_int`](unix#VALgetsockopt_int) and modified with [`Unix.setsockopt_int`](unix#VALsetsockopt_int). |
| [socket\_optint\_option](unixlabels#TYPEsocket_optint_option) [[UnixLabels](unixlabels)] | The socket options that can be consulted with [`UnixLabels.getsockopt_optint`](unixlabels#VALgetsockopt_optint) and modified with [`UnixLabels.setsockopt_optint`](unixlabels#VALsetsockopt_optint). |
| [socket\_optint\_option](unix#TYPEsocket_optint_option) [[Unix](unix)] | The socket options that can be consulted with [`Unix.getsockopt_optint`](unix#VALgetsockopt_optint) and modified with [`Unix.setsockopt_optint`](unix#VALsetsockopt_optint). |
| [socket\_type](unixlabels#TYPEsocket_type) [[UnixLabels](unixlabels)] | The type of socket kinds, specifying the semantics of communications. |
| [socket\_type](unix#TYPEsocket_type) [[Unix](unix)] | The type of socket kinds, specifying the semantics of communications. |
| [spec](arg#TYPEspec) [[Arg](arg)] | The concrete type describing the behavior associated with a keyword. |
| [split\_result](str#TYPEsplit_result) [[Str](str)] | |
| [stag](format#TYPEstag) [[Format](format)] | *Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities. |
| [stat](gc#TYPEstat) [[Gc](gc)] | The memory management counters are returned in a `stat` record. |
| [statistics](morelabels.hashtbl#TYPEstatistics) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | |
| [statistics](hashtbl#TYPEstatistics) [[Hashtbl](hashtbl)] | |
| [stats](unixlabels.largefile#TYPEstats) [[UnixLabels.LargeFile](unixlabels.largefile)] | |
| [stats](unixlabels#TYPEstats) [[UnixLabels](unixlabels)] | The information returned by the [`UnixLabels.stat`](unixlabels#VALstat) calls. |
| [stats](unix.largefile#TYPEstats) [[Unix.LargeFile](unix.largefile)] | |
| [stats](unix#TYPEstats) [[Unix](unix)] | The information returned by the [`Unix.stat`](unix#VALstat) calls. |
| [stats](camlinternaloo#TYPEstats) [[CamlinternalOO](camlinternaloo)] | |
| [symbolic\_output\_buffer](format#TYPEsymbolic_output_buffer) [[Format](format)] | The output buffer of a symbolic pretty-printer. |
| [symbolic\_output\_item](format#TYPEsymbolic_output_item) [[Format](format)] | Items produced by symbolic pretty-printers |
| T |
| [t](runtime_events.callbacks#TYPEt) [[Runtime\_events.Callbacks](runtime_events.callbacks)] | Type of callbacks |
| [t](runtime_events.timestamp#TYPEt) [[Runtime\_events.Timestamp](runtime_events.timestamp)] | Type for the int64 timestamp to allow for future changes |
| [t](thread#TYPEt) [[Thread](thread)] | The type of thread handles. |
| [t](camlinternaloo#TYPEt) [[CamlinternalOO](camlinternaloo)] | |
| [t](camlinternallazy#TYPEt) [[CamlinternalLazy](camlinternallazy)] | |
| [t](weak.s#TYPEt) [[Weak.S](weak.s)] | The type of tables that contain elements of type `data`. |
| [t](weak#TYPEt) [[Weak](weak)] | The type of arrays of weak pointers (weak arrays). |
| [t](unit#TYPEt) [[Unit](unit)] | The unit type. |
| [t](uchar#TYPEt) [[Uchar](uchar)] | The type for Unicode characters. |
| [t](sys.immediate64.immediate#TYPEt) [[Sys.Immediate64.Immediate](sys.immediate64.immediate)] | |
| [t](sys.immediate64.non_immediate#TYPEt) [[Sys.Immediate64.Non\_immediate](sys.immediate64.non_immediate)] | |
| [t](sys.immediate64.make#TYPEt) [[Sys.Immediate64.Make](sys.immediate64.make)] | |
| [t](string#TYPEt) [[String](string)] | The type for strings. |
| [t](stringlabels#TYPEt) [[StringLabels](stringlabels)] | The type for strings. |
| [t](stack#TYPEt) [[Stack](stack)] | The type of stacks containing elements of type `'a`. |
| [t](set.orderedtype#TYPEt) [[Set.OrderedType](set.orderedtype)] | The type of the set elements. |
| [t](set.s#TYPEt) [[Set.S](set.s)] | The type of sets. |
| [t](seq#TYPEt) [[Seq](seq)] | A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. |
| [t](semaphore.binary#TYPEt) [[Semaphore.Binary](semaphore.binary)] | The type of binary semaphores. |
| [t](semaphore.counting#TYPEt) [[Semaphore.Counting](semaphore.counting)] | The type of counting semaphores. |
| [t](result#TYPEt) [[Result](result)] | The type for result values. |
| [t](random.state#TYPEt) [[Random.State](random.state)] | The type of PRNG states. |
| [t](queue#TYPEt) [[Queue](queue)] | The type of queues containing elements of type `'a`. |
| [t](printexc.slot#TYPEt) [[Printexc.Slot](printexc.slot)] | |
| [t](printexc#TYPEt) [[Printexc](printexc)] | The type of exception values. |
| [t](out_channel#TYPEt) [[Out\_channel](out_channel)] | The type of output channel. |
| [t](option#TYPEt) [[Option](option)] | The type for option values. |
| [t](obj.ephemeron#TYPEt) [[Obj.Ephemeron](obj.ephemeron)] | an ephemeron cf [`Obj.Ephemeron`](obj.ephemeron) |
| [t](obj.extension_constructor#TYPEt) [[Obj.Extension\_constructor](obj.extension_constructor)] | |
| [t](obj#TYPEt) [[Obj](obj)] | |
| [t](nativeint#TYPEt) [[Nativeint](nativeint)] | An alias for the type of native integers. |
| [t](mutex#TYPEt) [[Mutex](mutex)] | The type of mutexes. |
| [t](morelabels.set.orderedtype#TYPEt) [[MoreLabels.Set.OrderedType](morelabels.set.orderedtype)] | The type of the set elements. |
| [t](morelabels.set.s#TYPEt) [[MoreLabels.Set.S](morelabels.set.s)] | The type of sets. |
| [t](morelabels.map.orderedtype#TYPEt) [[MoreLabels.Map.OrderedType](morelabels.map.orderedtype)] | The type of the map keys. |
| [t](morelabels.map.s#TYPEt) [[MoreLabels.Map.S](morelabels.map.s)] | The type of maps from type `key` to type `'a`. |
| [t](morelabels.hashtbl.seededhashedtype#TYPEt) [[MoreLabels.Hashtbl.SeededHashedType](morelabels.hashtbl.seededhashedtype)] | The type of the hashtable keys. |
| [t](morelabels.hashtbl.hashedtype#TYPEt) [[MoreLabels.Hashtbl.HashedType](morelabels.hashtbl.hashedtype)] | The type of the hashtable keys. |
| [t](morelabels.hashtbl.seededs#TYPEt) [[MoreLabels.Hashtbl.SeededS](morelabels.hashtbl.seededs)] | |
| [t](morelabels.hashtbl.s#TYPEt) [[MoreLabels.Hashtbl.S](morelabels.hashtbl.s)] | |
| [t](morelabels.hashtbl#TYPEt) [[MoreLabels.Hashtbl](morelabels.hashtbl)] | The type of hash tables from type `'a` to type `'b`. |
| [t](map.orderedtype#TYPEt) [[Map.OrderedType](map.orderedtype)] | The type of the map keys. |
| [t](map.s#TYPEt) [[Map.S](map.s)] | The type of maps from type `key` to type `'a`. |
| [t](listlabels#TYPEt) [[ListLabels](listlabels)] | An alias for the type of lists. |
| [t](list#TYPEt) [[List](list)] | An alias for the type of lists. |
| [t](lazy#TYPEt) [[Lazy](lazy)] | A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. |
| [t](int64#TYPEt) [[Int64](int64)] | An alias for the type of 64-bit integers. |
| [t](int32#TYPEt) [[Int32](int32)] | An alias for the type of 32-bit integers. |
| [t](int#TYPEt) [[Int](int)] | The type for integer values. |
| [t](in_channel#TYPEt) [[In\_channel](in_channel)] | The type of input channel. |
| [t](hashtbl.seededhashedtype#TYPEt) [[Hashtbl.SeededHashedType](hashtbl.seededhashedtype)] | The type of the hashtable keys. |
| [t](hashtbl.hashedtype#TYPEt) [[Hashtbl.HashedType](hashtbl.hashedtype)] | The type of the hashtable keys. |
| [t](hashtbl.seededs#TYPEt) [[Hashtbl.SeededS](hashtbl.seededs)] | |
| [t](hashtbl.s#TYPEt) [[Hashtbl.S](hashtbl.s)] | |
| [t](hashtbl#TYPEt) [[Hashtbl](hashtbl)] | The type of hash tables from type `'a` to type `'b`. |
| [t](float.arraylabels#TYPEt) [[Float.ArrayLabels](float.arraylabels)] | The type of float arrays with packed representation. |
| [t](float.array#TYPEt) [[Float.Array](float.array)] | The type of float arrays with packed representation. |
| [t](float#TYPEt) [[Float](float)] | An alias for the type of floating-point numbers. |
| [t](ephemeron.kn.bucket#TYPEt) [[Ephemeron.Kn.Bucket](ephemeron.kn.bucket)] | A bucket is a mutable "list" of ephemerons. |
| [t](ephemeron.kn#TYPEt) [[Ephemeron.Kn](ephemeron.kn)] | an ephemeron with an arbitrary number of keys of the same type |
| [t](ephemeron.k2.bucket#TYPEt) [[Ephemeron.K2.Bucket](ephemeron.k2.bucket)] | A bucket is a mutable "list" of ephemerons. |
| [t](ephemeron.k2#TYPEt) [[Ephemeron.K2](ephemeron.k2)] | an ephemeron with two keys |
| [t](ephemeron.k1.bucket#TYPEt) [[Ephemeron.K1.Bucket](ephemeron.k1.bucket)] | A bucket is a mutable "list" of ephemerons. |
| [t](ephemeron.seededs#TYPEt) [[Ephemeron.SeededS](ephemeron.seededs)] | |
| [t](ephemeron.s#TYPEt) [[Ephemeron.S](ephemeron.s)] | |
| [t](ephemeron.k1#TYPEt) [[Ephemeron.K1](ephemeron.k1)] | an ephemeron with one key |
| [t](either#TYPEt) [[Either](either)] | A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b` |
| [t](effect#TYPEt) [[Effect](effect)] | The type of effects. |
| [t](domain#TYPEt) [[Domain](domain)] | A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception |
| [t](digest#TYPEt) [[Digest](digest)] | The type of digests: 16-character strings. |
| [t](condition#TYPEt) [[Condition](condition)] | The type of condition variables. |
| [t](complex#TYPEt) [[Complex](complex)] | The type of complex numbers. |
| [t](char#TYPEt) [[Char](char)] | An alias for the type of characters. |
| [t](byteslabels#TYPEt) [[BytesLabels](byteslabels)] | An alias for the type of byte sequences. |
| [t](bytes#TYPEt) [[Bytes](bytes)] | An alias for the type of byte sequences. |
| [t](buffer#TYPEt) [[Buffer](buffer)] | The abstract type of buffers. |
| [t](bool#TYPEt) [[Bool](bool)] | The type of booleans (truth values). |
| [t](bigarray.array3#TYPEt) [[Bigarray.Array3](bigarray.array3)] | The type of three-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`. |
| [t](bigarray.array2#TYPEt) [[Bigarray.Array2](bigarray.array2)] | The type of two-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`. |
| [t](bigarray.array1#TYPEt) [[Bigarray.Array1](bigarray.array1)] | The type of one-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`. |
| [t](bigarray.array0#TYPEt) [[Bigarray.Array0](bigarray.array0)] | The type of zero-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`. |
| [t](bigarray.genarray#TYPEt) [[Bigarray.Genarray](bigarray.genarray)] | The type `Genarray.t` is the type of Bigarrays with variable numbers of dimensions. |
| [t](atomic#TYPEt) [[Atomic](atomic)] | An atomic (mutable) reference to a value of type `'a`. |
| [t](arraylabels#TYPEt) [[ArrayLabels](arraylabels)] | An alias for the type of arrays. |
| [t](array#TYPEt) [[Array](array)] | An alias for the type of arrays. |
| [table](camlinternaloo#TYPEtable) [[CamlinternalOO](camlinternaloo)] | |
| [tables](camlinternaloo#TYPEtables) [[CamlinternalOO](camlinternaloo)] | |
| [tag](camlinternaloo#TYPEtag) [[CamlinternalOO](camlinternaloo)] | |
| [tag](format#TYPEtag) [[Format](format)] | |
| [terminal\_io](unixlabels#TYPEterminal_io) [[UnixLabels](unixlabels)] | |
| [terminal\_io](unix#TYPEterminal_io) [[Unix](unix)] | |
| [tm](unixlabels#TYPEtm) [[UnixLabels](unixlabels)] | The type representing wallclock time and calendar date. |
| [tm](unix#TYPEtm) [[Unix](unix)] | The type representing wallclock time and calendar date. |
| [tracker](gc.memprof#TYPEtracker) [[Gc.Memprof](gc.memprof)] | A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks. |
| U |
| [usage\_msg](arg#TYPEusage_msg) [[Arg](arg)] | |
| [utf\_decode](uchar#TYPEutf_decode) [[Uchar](uchar)] | The type for UTF decode results. |
| W |
| [wait\_flag](unixlabels#TYPEwait_flag) [[UnixLabels](unixlabels)] | Flags for [`UnixLabels.waitpid`](unixlabels#VALwaitpid). |
| [wait\_flag](unix#TYPEwait_flag) [[Unix](unix)] | Flags for [`Unix.waitpid`](unix#VALwaitpid). |
| programming_docs |
ocaml Functor Map.Make Functor Map.Make
================
```
module Make: functor (Ord : OrderedType) -> S with type key = Ord.t
```
Functor building an implementation of the map structure given a totally ordered type.
| | | | | |
| --- | --- | --- | --- | --- |
| **Parameters:** |
| | | |
| --- | --- | --- |
| `Ord` | : | `[OrderedType](map.orderedtype)` |
|
```
type key
```
The type of the map keys.
```
type +'a t
```
The type of maps from type `key` to type `'a`.
```
val empty : 'a t
```
The empty map.
```
val is_empty : 'a t -> bool
```
Test whether a map is empty or not.
```
val mem : key -> 'a t -> bool
```
`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise.
```
val add : key -> 'a -> 'a t -> 'a t
```
`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears.
* **Before 4.03** Physical equality was not ensured.
```
val update : key -> ('a option -> 'a option) -> 'a t -> 'a t
```
`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Since** 4.06.0
```
val singleton : key -> 'a -> 'a t
```
`singleton x y` returns the one-element map that contains a binding `y` for `x`.
* **Since** 3.12.0
```
val remove : key -> 'a t -> 'a t
```
`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`).
* **Before 4.03** Physical equality was not ensured.
```
val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
```
`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`.
* **Since** 3.12.0
```
val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
```
`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where
* `f' _key None None = None`
* `f' _key (Some v) None = Some v`
* `f' _key None (Some v) = Some v`
* `f' key (Some v1) (Some v2) = f key v1 v2`
* **Since** 4.03.0
```
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
```
Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.
```
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
```
`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys.
```
val iter : (key -> 'a -> unit) -> 'a t -> unit
```
`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
```
`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data.
```
val for_all : (key -> 'a -> bool) -> 'a t -> bool
```
`for_all f m` checks if all the bindings of the map satisfy the predicate `f`.
* **Since** 3.12.0
```
val exists : (key -> 'a -> bool) -> 'a t -> bool
```
`exists f m` checks if at least one binding of the map satisfies the predicate `f`.
* **Since** 3.12.0
```
val filter : (key -> 'a -> bool) -> 'a t -> 'a t
```
`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`)
* **Before 4.03** Physical equality was not ensured.
* **Since** 3.12.0
```
val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t
```
`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map:
* if `f k v` is `None` then `k` is not in the result,
* if `f k v` is `Some v'` then the binding `(k, v')` is in the output map.
For example, the following function on maps whose values are lists
```
filter_map
(fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
```
drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty.
* **Since** 4.11.0
```
val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
```
`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`.
* **Since** 3.12.0
```
val cardinal : 'a t -> int
```
Return the number of bindings of a map.
* **Since** 3.12.0
```
val bindings : 'a t -> (key * 'a) list
```
Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](map.make).
* **Since** 3.12.0
```
val min_binding : 'a t -> key * 'a
```
Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not\_found` if the map is empty.
* **Since** 3.12.0
```
val min_binding_opt : 'a t -> (key * 'a) option
```
Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty.
* **Since** 4.05
```
val max_binding : 'a t -> key * 'a
```
Same as [`Map.S.min_binding`](map.s#VALmin_binding), but returns the binding with the largest key in the given map.
* **Since** 3.12.0
```
val max_binding_opt : 'a t -> (key * 'a) option
```
Same as [`Map.S.min_binding_opt`](map.s#VALmin_binding_opt), but returns the binding with the largest key in the given map.
* **Since** 4.05
```
val choose : 'a t -> key * 'a
```
Return one binding of the given map, or raise `Not\_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 3.12.0
```
val choose_opt : 'a t -> (key * 'a) option
```
Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.
* **Since** 4.05
```
val split : key -> 'a t -> 'a t * 'a option * 'a t
```
`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`.
* **Since** 3.12.0
```
val find : key -> 'a t -> 'a
```
`find x m` returns the current value of `x` in `m`, or raises `Not\_found` if no binding for `x` exists.
```
val find_opt : key -> 'a t -> 'a option
```
`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists.
* **Since** 4.05
```
val find_first : (key -> bool) -> 'a t -> key * 'a
```
`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not\_found` if `x` is greater than any element of `m`.
* **Since** 4.05
```
val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option
```
`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val find_last : (key -> bool) -> 'a t -> key * 'a
```
`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not\_found` if no such key exists.
* **Since** 4.05
```
val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option
```
`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists.
* **Since** 4.05
```
val map : ('a -> 'b) -> 'a t -> 'b t
```
`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.
```
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
```
Same as [`Map.S.map`](map.s#VALmap), but the function receives as arguments both the key and the associated value for each binding of the map.
Maps and Sequences
------------------
```
val to_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in ascending order of keys
* **Since** 4.07
```
val to_rev_seq : 'a t -> (key * 'a) Seq.t
```
Iterate on the whole map, in descending order of keys
* **Since** 4.12
```
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
```
`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above.
* **Since** 4.07
```
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
```
Add the given bindings to the map, in order.
* **Since** 4.07
```
val of_seq : (key * 'a) Seq.t -> 'a t
```
Build a map from the given bindings
* **Since** 4.07
ocaml Module Domain Module Domain
=============
```
module Domain: sig .. end
```
* **Alert unstable.** The Domain interface may change in incompatible ways in the future.
Domains.
See 'Parallel programming' chapter in the manual.
```
type 'a t
```
A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception
```
val spawn : (unit -> 'a) -> 'a t
```
`spawn f` creates a new domain that runs in parallel with the current domain.
```
val join : 'a t -> 'a
```
`join d` blocks until domain `d` runs to completion. If `d` results in a value, then that is returned by `join d`. If `d` raises an uncaught exception, then that is re-raised by `join d`.
```
type id = private int
```
Domains have unique integer identifiers
```
val get_id : 'a t -> id
```
`get_id d` returns the identifier of the domain `d`
```
val self : unit -> id
```
`self ()` is the identifier of the currently running domain
```
val before_first_spawn : (unit -> unit) -> unit
```
`before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. The functions registered with `before_first_spawn` are called on the main (initial) domain. The functions registered with `before_first_spawn` are called in 'first in, first out' order: the oldest function added with `before_first_spawn` is called first.
* **Raises** `Invalid_argument` if the program has already spawned a domain.
```
val at_exit : (unit -> unit) -> unit
```
`at_exit f` registers `f` to be called when the current domain exits. Note that `at_exit` callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. An example:
```
let temp_file_key = Domain.DLS.new_key (fun _ ->
let tmp = snd (Filename.open_temp_file "" "") in
Domain.at_exit (fun () -> close_out_noerr tmp);
tmp)
```
The snippet above creates a key that when retrieved for the first time will open a temporary file and register an `at_exit` callback to close it, thus guaranteeing the descriptor is not leaked in case the current domain exits.
```
val cpu_relax : unit -> unit
```
If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures
```
val is_main_domain : unit -> bool
```
`is_main_domain ()` returns true if called from the initial domain.
```
val recommended_domain_count : unit -> int
```
The recommended maximum number of domains which should be running simultaneously (including domains already running).
The value returned is at least `1`.
```
module DLS: sig .. end
```
ocaml Module Sys Module Sys
==========
```
module Sys: sig .. end
```
System interface.
Every function in this module raises `Sys\_error` with an informative message when the underlying system call signal an error.
```
val argv : string array
```
The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program.
```
val executable_name : string
```
The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable.
```
val file_exists : string -> bool
```
Test if a file with the given name exists.
```
val is_directory : string -> bool
```
Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file.
* **Since** 3.10.0
* **Raises** `Sys_error` if no file exists with the given name.
```
val remove : string -> unit
```
Remove the given file name from the file system.
```
val rename : string -> string -> unit
```
Rename a file. `rename oldpath newpath` renames the file called `oldpath`, giving it `newpath` as its new name, moving it between directories if needed. If `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`.
* **Since** 4.06 concerning the "replace existing file" behavior
```
val getenv : string -> string
```
Return the value associated to a variable in the process environment.
* **Raises** `Not_found` if the variable is unbound.
```
val getenv_opt : string -> string option
```
Return the value associated to a variable in the process environment or `None` if the variable is unbound.
* **Since** 4.05
```
val command : string -> int
```
Execute the given shell command and return its exit code.
The argument of [`Sys.command`](sys#VALcommand) is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell.
Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The [`Filename.quote_command`](filename#VALquote_command) performs the appropriate quoting given a command name, a list of arguments, and optional file redirections.
```
val time : unit -> float
```
Return the processor time, in seconds, used by the program since the beginning of execution.
```
val chdir : string -> unit
```
Change the current working directory of the process.
```
val mkdir : string -> int -> unit
```
Create a directory with the given permissions.
* **Since** 4.12.0
```
val rmdir : string -> unit
```
Remove an empty directory.
* **Since** 4.12.0
```
val getcwd : unit -> string
```
Return the current working directory of the process.
```
val readdir : string -> string array
```
Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
```
val interactive : bool ref
```
This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`.
* **Alert unsynchronized\_access.** The interactive status is a mutable global state.
```
val os_type : string
```
Operating system currently executing the OCaml program. One of
* `"Unix"` (for all Unix versions, including Linux and Mac OS X),
* `"Win32"` (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
* `"Cygwin"` (for MS-Windows, OCaml compiled with Cygwin).
```
type backend_type =
```
| | |
| --- | --- |
| `|` | `Native` |
| `|` | `Bytecode` |
| `|` | `Other of `string`` |
Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript.
* **Since** 4.04.0
```
val backend_type : backend_type
```
Backend type currently executing the OCaml program.
* **Since** 4.04.0
```
val unix : bool
```
True if `Sys.os_type = "Unix"`.
* **Since** 4.01.0
```
val win32 : bool
```
True if `Sys.os_type = "Win32"`.
* **Since** 4.01.0
```
val cygwin : bool
```
True if `Sys.os_type = "Cygwin"`.
* **Since** 4.01.0
```
val word_size : int
```
Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64.
```
val int_size : int
```
Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript.
* **Since** 4.03.0
```
val big_endian : bool
```
Whether the machine currently executing the Caml program is big-endian.
* **Since** 4.00.0
```
val max_string_length : int
```
Maximum length of strings and byte sequences.
```
val max_array_length : int
```
Maximum length of a normal array (i.e. any array whose elements are not of type `float`). The maximum length of a `float array` is `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`.
```
val max_floatarray_length : int
```
Maximum length of a floatarray. This is also the maximum length of a `float array` when OCaml is configured with `--enable-flat-float-array`.
```
val runtime_variant : unit -> string
```
Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation.
* **Since** 4.03.0
```
val runtime_parameters : unit -> string
```
Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable.
* **Since** 4.03.0
Signal handling
---------------
```
type signal_behavior =
```
| | |
| --- | --- |
| `|` | `Signal\_default` |
| `|` | `Signal\_ignore` |
| `|` | `Signal\_handle of `(int -> unit)`` |
What to do when receiving a signal:
* `Signal\_default`: take the default behavior (usually: abort the program)
* `Signal\_ignore`: ignore the signal
* `Signal\_handle f`: call function `f`, giving it the signal number as argument.
```
val signal : int -> signal_behavior -> signal_behavior
```
Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid\_argument` exception is raised.
```
val set_signal : int -> signal_behavior -> unit
```
Same as [`Sys.signal`](sys#VALsignal) but return value is ignored.
### Signal numbers for the standard POSIX signals.
```
val sigabrt : int
```
Abnormal termination
```
val sigalrm : int
```
Timeout
```
val sigfpe : int
```
Arithmetic exception
```
val sighup : int
```
Hangup on controlling terminal
```
val sigill : int
```
Invalid hardware instruction
```
val sigint : int
```
Interactive interrupt (ctrl-C)
```
val sigkill : int
```
Termination (cannot be ignored)
```
val sigpipe : int
```
Broken pipe
```
val sigquit : int
```
Interactive termination
```
val sigsegv : int
```
Invalid memory reference
```
val sigterm : int
```
Termination
```
val sigusr1 : int
```
Application-defined signal 1
```
val sigusr2 : int
```
Application-defined signal 2
```
val sigchld : int
```
Child process terminated
```
val sigcont : int
```
Continue
```
val sigstop : int
```
Stop
```
val sigtstp : int
```
Interactive stop
```
val sigttin : int
```
Terminal read from background process
```
val sigttou : int
```
Terminal write from background process
```
val sigvtalrm : int
```
Timeout in virtual time
```
val sigprof : int
```
Profiling interrupt
```
val sigbus : int
```
Bus error
* **Since** 4.03
```
val sigpoll : int
```
Pollable event
* **Since** 4.03
```
val sigsys : int
```
Bad argument to routine
* **Since** 4.03
```
val sigtrap : int
```
Trace/breakpoint trap
* **Since** 4.03
```
val sigurg : int
```
Urgent condition on socket
* **Since** 4.03
```
val sigxcpu : int
```
Timeout in cpu time
* **Since** 4.03
```
val sigxfsz : int
```
File size limit exceeded
* **Since** 4.03
```
exception Break
```
Exception raised on interactive interrupt if [`Sys.catch_break`](sys#VALcatch_break) is on.
```
val catch_break : bool -> unit
```
`catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. Call `catch_break true` to enable raising `Break`, and `catch_break false` to let the system terminate the program on user interrupt.
```
val ocaml_version : string
```
`ocaml_version` is the version of OCaml. It is a string of the form `"major.minor[.patchlevel][(+|~)additional-info]"`, where `major`, `minor`, and `patchlevel` are integers, and `additional-info` is an arbitrary string. The `[.patchlevel]` part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The `[(+|~)additional-info]` part may be absent.
```
val development_version : bool
```
`true` if this is a development version, `false` otherwise.
* **Since** 4.14.0
```
type extra_prefix =
```
| | |
| --- | --- |
| `|` | `Plus` |
| `|` | `Tilde` |
```
type extra_info = extra_prefix * string
```
* **Since** 4.14
```
type ocaml_release_info = {
```
| | |
| --- | --- |
| | `major : `int`;` |
| | `minor : `int`;` |
| | `patchlevel : `int`;` |
| | `extra : `[extra\_info](sys#TYPEextra_info) option`;` |
`}` * **Since** 4.14
```
val ocaml_release : ocaml_release_info
```
`ocaml_release` is the version of OCaml.
* **Since** 4.14
```
val enable_runtime_warnings : bool -> unit
```
Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default.
* **Since** 4.03.0
* **Alert unsynchronized\_access.** The status of runtime warnings is a mutable global state.
```
val runtime_warnings_enabled : unit -> bool
```
Return whether runtime warnings are currently enabled.
* **Since** 4.03.0
* **Alert unsynchronized\_access.** The status of runtime warnings is a mutable global state.
Optimization
------------
```
val opaque_identity : 'a -> 'a
```
For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function.
At runtime, `opaque_identity` disappears altogether.
A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example:
```
for _round = 1 to 100_000 do
ignore (Sys.opaque_identity (my_pure_computation ()))
done
```
* **Since** 4.03.0
```
module Immediate64: sig .. end
```
| programming_docs |
ocaml Module Stack Module Stack
============
```
module Stack: sig .. end
```
Last-in first-out stacks.
This module implements stacks (LIFOs), with in-place modification.
* **Alert unsynchronized\_accesses.** Unsynchronized accesses to stacks are a programming error.
**Unsynchronized accesses**
Unsynchronized accesses to a stack may lead to an invalid queue state. Thus, concurrent accesses to stacks must be synchronized (for instance with a [`Mutex.t`](mutex#TYPEt)).
```
type 'a t
```
The type of stacks containing elements of type `'a`.
```
exception Empty
```
Raised when [`Stack.pop`](stack#VALpop) or [`Stack.top`](stack#VALtop) is applied to an empty stack.
```
val create : unit -> 'a t
```
Return a new stack, initially empty.
```
val push : 'a -> 'a t -> unit
```
`push x s` adds the element `x` at the top of stack `s`.
```
val pop : 'a t -> 'a
```
`pop s` removes and returns the topmost element in stack `s`, or raises [`Stack.Empty`](stack#EXCEPTIONEmpty) if the stack is empty.
```
val pop_opt : 'a t -> 'a option
```
`pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty.
* **Since** 4.08
```
val top : 'a t -> 'a
```
`top s` returns the topmost element in stack `s`, or raises [`Stack.Empty`](stack#EXCEPTIONEmpty) if the stack is empty.
```
val top_opt : 'a t -> 'a option
```
`top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty.
* **Since** 4.08
```
val clear : 'a t -> unit
```
Discard all elements from a stack.
```
val copy : 'a t -> 'a t
```
Return a copy of the given stack.
```
val is_empty : 'a t -> bool
```
Return `true` if the given stack is empty, `false` otherwise.
```
val length : 'a t -> int
```
Return the number of elements in a stack. Time complexity O(1)
```
val iter : ('a -> unit) -> 'a t -> unit
```
`iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged.
```
val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
```
`fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. The stack is unchanged.
* **Since** 4.03
Stacks and Sequences
--------------------
```
val to_seq : 'a t -> 'a Seq.t
```
Iterate on the stack, top to bottom. It is safe to modify the stack during iteration.
* **Since** 4.07
```
val add_seq : 'a t -> 'a Seq.t -> unit
```
Add the elements from the sequence on the top of the stack.
* **Since** 4.07
```
val of_seq : 'a Seq.t -> 'a t
```
Create a stack from the sequence.
* **Since** 4.07
ocaml Module Bigarray.Array1 Module Bigarray.Array1
======================
```
module Array1: sig .. end
```
One-dimensional arrays. The `Array1` structure provides operations similar to those of [`Bigarray.Genarray`](bigarray.genarray), but specialized to the case of one-dimensional arrays. (The [`Bigarray.Array2`](bigarray.array2) and [`Bigarray.Array3`](bigarray.array3) structures below provide operations specialized for two- and three-dimensional arrays.) Statically knowing the number of dimensions of the array allows faster operations, and more precise static type-checking.
```
type ('a, 'b, 'c) t
```
The type of one-dimensional Bigarrays whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`.
```
val create : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int -> ('a, 'b, 'c) t
```
`Array1.create kind layout dim` returns a new Bigarray of one dimension, whose size is `dim`. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
```
val init : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> int -> (int -> 'a) -> ('a, 'b, 'c) t
```
`Array1.init kind layout dim f` returns a new Bigarray `b` of one dimension, whose size is `dim`. `kind` and `layout` determine the array element kind and the array layout as described for [`Bigarray.Genarray.create`](bigarray.genarray#VALcreate).
Each element `Array1.get b i` of the array is initialized to the result of `f i`.
In other words, `Array1.init kind layout dimensions f` tabulates the results of `f` applied to the indices of a new Bigarray whose layout is described by `kind`, `layout` and `dim`.
* **Since** 4.12.0
```
val dim : ('a, 'b, 'c) t -> int
```
Return the size (dimension) of the given one-dimensional Bigarray.
```
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```
Return the kind of the given Bigarray.
```
val layout : ('a, 'b, 'c) t -> 'c Bigarray.layout
```
Return the layout of the given Bigarray.
```
val change_layout : ('a, 'b, 'c) t -> 'd Bigarray.layout -> ('a, 'b, 'd) t
```
`Array1.change_layout a layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimension as `a`). No copying of elements is involved: the new array and the original array share the same storage space.
* **Since** 4.06.0
```
val size_in_bytes : ('a, 'b, 'c) t -> int
```
`size_in_bytes a` is the number of elements in `a` multiplied by `a`'s [`Bigarray.kind_size_in_bytes`](bigarray#VALkind_size_in_bytes).
* **Since** 4.03.0
```
val get : ('a, 'b, 'c) t -> int -> 'a
```
`Array1.get a x`, or alternatively `a.{x}`, returns the element of `a` at index `x`. `x` must be greater or equal than `0` and strictly less than `Array1.dim a` if `a` has C layout. If `a` has Fortran layout, `x` must be greater or equal than `1` and less or equal than `Array1.dim a`. Otherwise, `Invalid\_argument` is raised.
```
val set : ('a, 'b, 'c) t -> int -> 'a -> unit
```
`Array1.set a x v`, also written `a.{x} <- v`, stores the value `v` at index `x` in `a`. `x` must be inside the bounds of `a` as described in [`Bigarray.Array1.get`](bigarray.array1#VALget); otherwise, `Invalid\_argument` is raised.
```
val sub : ('a, 'b, 'c) t -> int -> int -> ('a, 'b, 'c) t
```
Extract a sub-array of the given one-dimensional Bigarray. See [`Bigarray.Genarray.sub_left`](bigarray.genarray#VALsub_left) for more details.
```
val slice : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) Bigarray.Array0.t
```
Extract a scalar (zero-dimensional slice) of the given one-dimensional Bigarray. The integer parameter is the index of the scalar to extract. See [`Bigarray.Genarray.slice_left`](bigarray.genarray#VALslice_left) and [`Bigarray.Genarray.slice_right`](bigarray.genarray#VALslice_right) for more details.
* **Since** 4.05.0
```
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```
Copy the first Bigarray to the second Bigarray. See [`Bigarray.Genarray.blit`](bigarray.genarray#VALblit) for more details.
```
val fill : ('a, 'b, 'c) t -> 'a -> unit
```
Fill the given Bigarray with the given value. See [`Bigarray.Genarray.fill`](bigarray.genarray#VALfill) for more details.
```
val of_array : ('a, 'b) Bigarray.kind -> 'c Bigarray.layout -> 'a array -> ('a, 'b, 'c) t
```
Build a one-dimensional Bigarray initialized from the given array.
```
val unsafe_get : ('a, 'b, 'c) t -> int -> 'a
```
Like [`Bigarray.Array1.get`](bigarray.array1#VALget), but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds.
```
val unsafe_set : ('a, 'b, 'c) t -> int -> 'a -> unit
```
Like [`Bigarray.Array1.set`](bigarray.array1#VALset), but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds.
ocaml Index of exceptions Index of exceptions
===================
| |
| --- |
| A |
| [Assert\_failure](stdlib#EXCEPTIONAssert_failure) [[Stdlib](stdlib)] | Exception raised when an assertion fails. |
| B |
| [Bad](arg#EXCEPTIONBad) [[Arg](arg)] | Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. |
| [Break](sys#EXCEPTIONBreak) [[Sys](sys)] | Exception raised on interactive interrupt if [`Sys.catch_break`](sys#VALcatch_break) is on. |
| C |
| [Continuation\_already\_resumed](effect#EXCEPTIONContinuation_already_resumed) [[Effect](effect)] | Exception raised when a continuation is continued or discontinued more than once. |
| D |
| [Division\_by\_zero](stdlib#EXCEPTIONDivision_by_zero) [[Stdlib](stdlib)] | Exception raised by integer division and remainder operations when their second argument is zero. |
| E |
| [Empty](stack#EXCEPTIONEmpty) [[Stack](stack)] | Raised when [`Stack.pop`](stack#VALpop) or [`Stack.top`](stack#VALtop) is applied to an empty stack. |
| [Empty](queue#EXCEPTIONEmpty) [[Queue](queue)] | Raised when [`Queue.take`](queue#VALtake) or [`Queue.peek`](queue#VALpeek) is applied to an empty queue. |
| [End\_of\_file](stdlib#EXCEPTIONEnd_of_file) [[Stdlib](stdlib)] | Exception raised by input functions to signal that the end of file has been reached. |
| [Error](dynlink#EXCEPTIONError) [[Dynlink](dynlink)] | Errors in dynamic linking are reported by raising the `Error` exception with a description of the error. |
| [Exit](thread#EXCEPTIONExit) [[Thread](thread)] | Exception raised by user code to initiate termination of the current thread. |
| [Exit](stdlib#EXCEPTIONExit) [[Stdlib](stdlib)] | The `Exit` exception is not raised by any library function. |
| F |
| [Failure](stdlib#EXCEPTIONFailure) [[Stdlib](stdlib)] | Exception raised by library functions to signal that they are undefined on the given arguments. |
| [Finally\_raised](fun#EXCEPTIONFinally_raised) [[Fun](fun)] | `Finally\_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. |
| [Forced\_twice](seq#EXCEPTIONForced_twice) [[Seq](seq)] | This exception is raised when a sequence returned by [`Seq.once`](seq#VALonce) (or a suffix of it) is queried more than once. |
| H |
| [Help](arg#EXCEPTIONHelp) [[Arg](arg)] | Raised by `Arg.parse_argv` when the user asks for help. |
| I |
| [Invalid\_argument](stdlib#EXCEPTIONInvalid_argument) [[Stdlib](stdlib)] | Exception raised by library functions to signal that the given arguments do not make sense. |
| M |
| [Match\_failure](stdlib#EXCEPTIONMatch_failure) [[Stdlib](stdlib)] | Exception raised when none of the cases of a pattern-matching apply. |
| N |
| [Not\_found](stdlib#EXCEPTIONNot_found) [[Stdlib](stdlib)] | Exception raised by search functions when the desired object could not be found. |
| O |
| [Out\_of\_memory](stdlib#EXCEPTIONOut_of_memory) [[Stdlib](stdlib)] | Exception raised by the garbage collector when there is insufficient memory to complete the computation. |
| P |
| [Parse\_error](parsing#EXCEPTIONParse_error) [[Parsing](parsing)] | Raised when a parser encounters a syntax error. |
| S |
| [Scan\_failure](scanf#EXCEPTIONScan_failure) [[Scanf](scanf)] | When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan\_failure`. |
| [Stack\_overflow](stdlib#EXCEPTIONStack_overflow) [[Stdlib](stdlib)] | Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. |
| [Sys\_blocked\_io](stdlib#EXCEPTIONSys_blocked_io) [[Stdlib](stdlib)] | A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel. |
| [Sys\_error](stdlib#EXCEPTIONSys_error) [[Stdlib](stdlib)] | Exception raised by the input/output functions to report an operating system error. |
| U |
| [Undefined](camlinternallazy#EXCEPTIONUndefined) [[CamlinternalLazy](camlinternallazy)] | |
| [Undefined](lazy#EXCEPTIONUndefined) [[Lazy](lazy)] | Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively. |
| [Undefined\_recursive\_module](stdlib#EXCEPTIONUndefined_recursive_module) [[Stdlib](stdlib)] | Exception raised when an ill-founded recursive module definition is evaluated. |
| [Unhandled](effect#EXCEPTIONUnhandled) [[Effect](effect)] | `Unhandled e` is raised when effect `e` is performed and there is no handler for it. |
| [Unix\_error](unixlabels#EXCEPTIONUnix_error) [[UnixLabels](unixlabels)] | Raised by the system calls below when an error is encountered. |
| [Unix\_error](unix#EXCEPTIONUnix_error) [[Unix](unix)] | Raised by the system calls below when an error is encountered. |
mongoose Plugins Plugins
=======
Schemas are pluggable, that is, they allow for applying pre-packaged capabilities to extend their functionality. This is a very powerful feature.
Example
-------
Plugins are a tool for reusing logic in multiple schemas. Suppose you have several models in your database and want to add a `loadedAt` property to each one. Just create a plugin once and apply it to each `Schema`:
```
// loadedAt.js
module.exports = function loadedAtPlugin(schema, options) {
schema.virtual('loadedAt').
get(function() { return this._loadedAt; }).
set(function(v) { this._loadedAt = v; });
schema.post(['find', 'findOne'], function(docs) {
if (!Array.isArray(docs)) {
docs = [docs];
}
const now = new Date();
for (const doc of docs) {
doc.loadedAt = now;
}
});
};
// game-schema.js
const loadedAtPlugin = require('./loadedAt');
const gameSchema = new Schema({ ... });
gameSchema.plugin(loadedAtPlugin);
// player-schema.js
const loadedAtPlugin = require('./loadedAt');
const playerSchema = new Schema({ ... });
playerSchema.plugin(loadedAtPlugin);
```
We just added last-modified behavior to both our `Game` and `Player` schemas and declared an index on the `lastMod` path of our Games to boot. Not bad for a few lines of code.
Global Plugins
--------------
Want to register a plugin for all schemas? The mongoose singleton has a `.plugin()` function that registers a plugin for every schema. For example:
```
const mongoose = require('mongoose');
mongoose.plugin(require('./loadedAt'));
const gameSchema = new Schema({ ... });
const playerSchema = new Schema({ ... });
// `loadedAtPlugin` gets attached to both schemas
const Game = mongoose.model('Game', gameSchema);
const Player = mongoose.model('Player', playerSchema);
```
Officially Supported Plugins
----------------------------
The Mongoose team maintains several plugins that add cool new features to Mongoose. Here's a couple:
* [mongoose-autopopulate](http://plugins.mongoosejs.io/plugins/autopopulate): Always [`populate()`](populate) certain fields in your Mongoose schemas.
* [mongoose-lean-virtuals](http://plugins.mongoosejs.io/plugins/lean-virtuals): Attach virtuals to the results of Mongoose queries when using [`.lean()`](https://mongoosejs.com/docs/api.html#query_Query-lean).
You can find a full list of officially supported plugins on [Mongoose's plugins search site](https://plugins.mongoosejs.io/).
Community!
----------
Not only can you re-use schema functionality in your own projects, but you also reap the benefits of the Mongoose community as well. Any plugin published to [npm](https://npmjs.org/) and with 'mongoose' as an [npm keyword](https://docs.npmjs.com/files/package.json#keywords) will show up on our [search results](http://plugins.mongoosejs.io) page.
mongoose Populate Populate
========
MongoDB has the join-like [$lookup](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called `populate()`, which lets you reference documents in other collections.
Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query. Let's look at some examples.
```
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
```
So far we've created two [Models](models). Our `Person` model has its `stories` field set to an array of `ObjectId`s. The `ref` option is what tells Mongoose which model to use during population, in our case the `Story` model. All `_id`s we store here must be document `_id`s from the `Story` model.
**Note**: `ObjectId`, `Number`, `String`, and `Buffer` are valid for use as refs. However, you should use `ObjectId` unless you are an advanced user and have a good reason for doing so.
Saving refs
-----------
Saving refs to other documents works the same way you normally save properties, just assign the `_id` value:
```
const author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
const story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the \_id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
```
Population
----------
So far we haven't done anything much different. We've merely created a `Person` and a `Story`. Now let's take a look at populating our story's `author` using the query builder:
```
Story.
findOne({ title: 'Casino Royale' }).
populate('author').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
// prints "The author is Ian Fleming"
});
```
Populated paths are no longer set to their original `_id` , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
Arrays of refs work the same way. Just call the [populate](https://mongoosejs.com/docs/api.html#query_Query-populate) method on the query and an array of documents will be returned *in place* of the original `_id`s.
Setting Populated Fields
------------------------
You can manually populate a property by setting it to a document. The document must be an instance of the model your `ref` property refers to.
```
Story.findOne({ title: 'Casino Royale' }, function(error, story) {
if (error) {
return handleError(error);
}
story.author = author;
console.log(story.author.name); // prints "Ian Fleming"
});
```
What If There's No Foreign Document?
------------------------------------
Mongoose populate doesn't behave like conventional [SQL joins](https://www.w3schools.com/sql/sql_join.asp). When there's no document, `story.author` will be `null`. This is analogous to a [left join](https://www.w3schools.com/sql/sql_join_left.asp) in SQL.
```
await Person.deleteMany({ name: 'Ian Fleming' });
const story = await Story.findOne({ title: 'Casino Royale' }).populate('author');
story.author; // `null`
```
If you have an array of `authors` in your `storySchema`, `populate()` will give you an empty array instead.
```
const storySchema = Schema({
authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
title: String
});
// Later
const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors; // `[]`
```
Field Selection
---------------
What if we only want a few specific fields returned for the populated documents? This can be accomplished by passing the usual [field name syntax](https://mongoosejs.com/docs/api.html#query_Query-select) as the second argument to the populate method:
```
Story.
findOne({ title: /casino royale/i }).
populate('author', 'name'). // only return the Persons name
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
// prints "The author is Ian Fleming"
console.log('The authors age is %s', story.author.age);
// prints "The authors age is null'
});
```
Populating Multiple Paths
-------------------------
What if we wanted to populate multiple paths at the same time?
```
Story.
find(...).
populate('fans').
populate('author').
exec();
```
If you call `populate()` multiple times with the same path, only the last one will take effect.
```
// The 2nd `populate()` call below overwrites the first because they
// both populate 'fans'.
Story.
find().
populate({ path: 'fans', select: 'name' }).
populate({ path: 'fans', select: 'email' });
// The above is equivalent to:
Story.find().populate({ path: 'fans', select: 'email' });
```
Query conditions and other options
----------------------------------
What if we wanted to populate our fans array based on their age and select just their names?
```
Story.
find(...).
populate({
path: 'fans',
match: { age: { $gte: 21 } },
// Explicitly exclude `\_id`, see http://bit.ly/2aEfTdB
select: 'name -\_id'
}).
exec();
```
Populate does support a `limit` option, however, it currently does **not** limit on a per-document basis. For example, suppose you have 2 stories:
```
Story.create([
{ title: 'Casino Royale', fans: [1, 2, 3, 4, 5, 6, 7, 8] },
{ title: 'Live and Let Die', fans: [9, 10] }
]);
```
If you were to `populate()` using the `limit` option, you would find that the 2nd story has 0 fans:
```
const stories = Story.find().sort({ name: 1 }).populate({
path: 'fans',
options: { limit: 2 }
});
stories[0].fans.length; // 2
stories[1].fans.length; // 0
```
That's because, in order to avoid executing a separate query for each document, Mongoose instead queries for fans using `numDocuments * limit` as the limit. As a workaround, you should populate each document individually:
```
const stories = await Story.find().sort({ name: 1 });
for (const story of stories) {
await story.
populate({ path: 'fans', options: { limit: 2 } }).
execPopulate();
}
stories[0].fans.length; // 2
stories[1].fans.length; // 2
```
Refs to children
----------------
We may find however, if we use the `author` object, we are unable to get a list of the stories. This is because no `story` objects were ever 'pushed' onto `author.stories`.
There are two perspectives here. First, you may want the `author` know which stories are theirs. Usually, your schema should resolve one-to-many relationships by having a parent pointer in the 'many' side. But, if you have a good reason to want an array of child pointers, you can `push()` documents onto the array as shown below.
```
author.stories.push(story1);
author.save(callback);
```
This allows us to perform a `find` and `populate` combo:
```
Person.
findOne({ name: 'Ian Fleming' }).
populate('stories'). // only works if we pushed refs to children
exec(function (err, person) {
if (err) return handleError(err);
console.log(person);
});
```
It is debatable that we really want two sets of pointers as they may get out of sync. Instead we could skip populating and directly `find()` the stories we are interested in.
```
Story.
find({ author: author._id }).
exec(function (err, stories) {
if (err) return handleError(err);
console.log('The stories are an array: ', stories);
});
```
The documents returned from [query population](https://mongoosejs.com/docs/api.html#query_Query-populate) become fully functional, `remove`able, `save`able documents unless the [lean](https://mongoosejs.com/docs/api.html#query_Query-lean) option is specified. Do not confuse them with [sub docs](subdocs). Take caution when calling its remove method because you'll be removing it from the database, not just the array.
Populating an existing document
-------------------------------
If we have an existing mongoose document and want to populate some of its paths, **mongoose >= 3.6** supports the [document#populate()](https://mongoosejs.com/docs/api.html#document_Document-populate) method.
Populating multiple existing documents
--------------------------------------
If we have one or many mongoose documents or even plain objects (*like [mapReduce](https://mongoosejs.com/docs/api.html#model_Model.mapReduce) output*), we may populate them using the [Model.populate()](https://mongoosejs.com/docs/api.html#model_Model.populate) method available in **mongoose >= 3.6**. This is what `document#populate()` and `query#populate()` use to populate documents.
Populating across multiple levels
---------------------------------
Say you have a user schema which keeps track of the user's friends.
```
var userSchema = new Schema({
name: String,
friends: [{ type: ObjectId, ref: 'User' }]
});
```
Populate lets you get a list of a user's friends, but what if you also wanted a user's friends of friends? Specify the `populate` option to tell mongoose to populate the `friends` array of all the user's friends:
```
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
});
```
Populating across Databases
---------------------------
Let's say you have a schema representing events, and a schema representing conversations. Each event has a corresponding conversation thread.
```
var eventSchema = new Schema({
name: String,
// The id of the corresponding conversation
// Notice there's no ref here!
conversation: ObjectId
});
var conversationSchema = new Schema({
numMessages: Number
});
```
Also, suppose that events and conversations are stored in separate MongoDB instances.
```
var db1 = mongoose.createConnection('localhost:27000/db1');
var db2 = mongoose.createConnection('localhost:27001/db2');
var Event = db1.model('Event', eventSchema);
var Conversation = db2.model('Conversation', conversationSchema);
```
In this situation, you will **not** be able to `populate()` normally. The `conversation` field will always be null, because `populate()` doesn't know which model to use. However, [you can specify the model explicitly](https://mongoosejs.com/docs/api.html#model_Model.populate).
```
Event.
find().
populate({ path: 'conversation', model: Conversation }).
exec(function(error, docs) { /\* ... \*/ });
```
This is known as a "cross-database populate," because it enables you to populate across MongoDB databases and even across MongoDB instances.
Dynamic References via `refPath`
--------------------------------
Mongoose can also populate from multiple collections based on the value of a property in the document. Let's say you're building a schema for storing comments. A user may comment on either a blog post or a product.
```
const commentSchema = new Schema({
body: { type: String, required: true },
on: {
type: Schema.Types.ObjectId,
required: true,
// Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
// will look at the `onModel` property to find the right model.
refPath: 'onModel'
},
onModel: {
type: String,
required: true,
enum: ['BlogPost', 'Product']
}
});
const Product = mongoose.model('Product', new Schema({ name: String }));
const BlogPost = mongoose.model('BlogPost', new Schema({ title: String }));
const Comment = mongoose.model('Comment', commentSchema);
```
The `refPath` option is a more sophisticated alternative to `ref`. If `ref` is just a string, Mongoose will always query the same model to find the populated subdocs. With `refPath`, you can configure what model Mongoose uses for each document.
```
const book = await Product.create({ name: 'The Count of Monte Cristo' });
const post = await BlogPost.create({ title: 'Top 10 French Novels' });
const commentOnBook = await Comment.create({
body: 'Great read',
on: book._id,
onModel: 'Product'
});
const commentOnPost = await Comment.create({
body: 'Very informative',
on: post._id,
onModel: 'BlogPost'
});
// The below `populate()` works even though one comment references the
// 'Product' collection and the other references the 'BlogPost' collection.
const comments = await Comment.find().populate('on').sort({ body: 1 });
comments[0].on.name; // "The Count of Monte Cristo"
comments[1].on.title; // "Top 10 French Novels"
```
An alternative approach is to define separate `blogPost` and `product` properties on `commentSchema`, and then `populate()` on both properties.
```
const commentSchema = new Schema({
body: { type: String, required: true },
product: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Product'
},
blogPost: {
type: Schema.Types.ObjectId,
required: true,
ref: 'BlogPost'
}
});
// ...
// The below `populate()` is equivalent to the `refPath` approach, you
// just need to make sure you `populate()` both `product` and `blogPost`.
const comments = await Comment.find().
populate('product').
populate('blogPost').
sort({ body: 1 });
comments[0].product.name; // "The Count of Monte Cristo"
comments[1].blogPost.title; // "Top 10 French Novels"
```
Defining separate `blogPost` and `product` properties works for this simple example. But, if you decide to allow users to also comment on articles or other comments, you'll need to add more properties to your schema. You'll also need an extra `populate()` call for every property, unless you use [mongoose-autopopulate](https://www.npmjs.com/package/mongoose-autopopulate). Using `refPath` means you only need 2 schema paths and one `populate()` call regardless of how many models your `commentSchema` can point to.
Populate Virtuals
-----------------
So far you've only populated based on the `_id` field. However, that's sometimes not the right choice. In particular, [arrays that grow without bound are a MongoDB anti-pattern](https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/). Using mongoose virtuals, you can define more sophisticated relationships between documents.
```
const PersonSchema = new Schema({
name: String,
band: String
});
const BandSchema = new Schema({
name: String
});
BandSchema.virtual('members', {
ref: 'Person', // The model to use
localField: 'name', // Find people where `localField`
foreignField: 'band', // is equal to `foreignField`
// If `justOne` is true, 'members' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: false,
options: { sort: { name: -1 }, limit: 5 } // Query options, see http://bit.ly/mongoose-query-options
});
const Person = mongoose.model('Person', PersonSchema);
const Band = mongoose.model('Band', BandSchema);
/\*\*
\* Suppose you have 2 bands: "Guns N' Roses" and "Motley Crue"
\* And 4 people: "Axl Rose" and "Slash" with "Guns N' Roses", and
\* "Vince Neil" and "Nikki Sixx" with "Motley Crue"
\*/
Band.find({}).populate('members').exec(function(error, bands) {
/\* `bands.members` is now an array of instances of `Person` \*/
});
```
Keep in mind that virtuals are *not* included in `toJSON()` output by default. If you want populate virtuals to show up when using functions that rely on `JSON.stringify()`, like Express' [`res.json()` function](http://expressjs.com/en/4x/api.html#res.json), set the `virtuals: true` option on your schema's `toJSON` options.
```
// Set `virtuals: true` so `res.json()` works
const BandSchema = new Schema({
name: String
}, { toJSON: { virtuals: true } });
```
If you're using populate projections, make sure `foreignField` is included in the projection.
```
Band.
find({}).
populate({ path: 'members', select: 'name' }).
exec(function(error, bands) {
// Won't work, foreign field `band` is not selected in the projection
});
Band.
find({}).
populate({ path: 'members', select: 'name band' }).
exec(function(error, bands) {
// Works, foreign field `band` is selected
});
```
Populate Virtuals: The Count Option
-----------------------------------
Populate virtuals also support counting the number of documents with matching `foreignField` as opposed to the documents themselves. Set the `count` option on your virtual:
```
const PersonSchema = new Schema({
name: String,
band: String
});
const BandSchema = new Schema({
name: String
});
BandSchema.virtual('numMembers', {
ref: 'Person', // The model to use
localField: 'name', // Find people where `localField`
foreignField: 'band', // is equal to `foreignField`
count: true // And only get the number of docs
});
// Later
const doc = await Band.findOne({ name: 'Motley Crue' }).
populate('numMembers');
doc.numMembers; // 2
```
Populate in Middleware
----------------------
You can populate in either pre or post [hooks](http://mongoosejs.com/docs/middleware.html). If you want to always populate a certain field, check out the [mongoose-autopopulate plugin](http://npmjs.com/package/mongoose-autopopulate).
```
// Always attach `populate()` to `find()` calls
MySchema.pre('find', function() {
this.populate('user');
});
```
```
// Always `populate()` after `find()` calls. Useful if you want to selectively populate
// based on the docs found.
MySchema.post('find', async function(docs) {
for (let doc of docs) {
if (doc.isPublic) {
await doc.populate('user').execPopulate();
}
}
});
```
```
// `populate()` after saving. Useful for sending populated data back to the client in an
// update API endpoint
MySchema.post('save', function(doc, next) {
doc.populate('user').execPopulate().then(function() {
next();
});
});
```
Next Up
-------
Now that we've covered `populate()`, let's take a look at <discriminators>.
| programming_docs |
mongoose Deprecation Warnings Deprecation Warnings
====================
Deprecation Warnings
--------------------
There are several deprecations in the [MongoDB Node.js driver](http://npmjs.com/package/mongodb) that Mongoose users should be aware of. Mongoose provides options to work around these deprecation warnings, but you need to test whether these options cause any problems for your application. Please [report any issues on GitHub](https://github.com/Automattic/mongoose/issues/new).
Summary
-------
To fix all deprecation warnings, follow the below steps:
* `mongoose.set('useNewUrlParser', true);`
* `mongoose.set('useFindAndModify', false);`
* `mongoose.set('useCreateIndex', true);`
* `mongoose.set('useUnifiedTopology', true);`
* Replace `update()` with `updateOne()`, `updateMany()`, or `replaceOne()`
* Replace `remove()` with `deleteOne()` or `deleteMany()`.
* Replace `count()` with `countDocuments()`, unless you want to count how many documents are in the whole collection (no filter). In the latter case, use `estimatedDocumentCount()`.
Read below for more a more detailed description of each deprecation warning.
The `useNewUrlParser` Option
----------------------------
By default, `mongoose.connect()` will print out the below warning:
```
DeprecationWarning: current URL string parser is deprecated, and will be
removed in a future version. To use the new parser, pass option
{ useNewUrlParser: true } to MongoClient.connect.
```
The MongoDB Node.js driver rewrote the tool it uses to parse [MongoDB connection strings](https://docs.mongodb.com/manual/reference/connection-string/). Because this is such a big change, they put the new connection string parser behind a flag. To turn on this option, pass the `useNewUrlParser` option to [`mongoose.connect()`](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-connect) or [`mongoose.createConnection()`](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-createConnection).
```
mongoose.connect(uri, { useNewUrlParser: true });
mongoose.createConnection(uri, { useNewUrlParser: true });
```
You can also [set the global `useNewUrlParser` option](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set) to turn on `useNewUrlParser` for every connection by default.
```
// Optional. Use this if you create a lot of connections and don't want
// to copy/paste `{ useNewUrlParser: true }`.
mongoose.set('useNewUrlParser', true);
```
To test your app with `{ useNewUrlParser: true }`, you only need to check whether your app successfully connects. Once Mongoose has successfully connected, the URL parser is no longer important. If you can't connect with `{ useNewUrlParser: true }`, please [open an issue on GitHub](https://github.com/Automattic/mongoose/issues/new).
`findAndModify()`
-----------------
If you use [`Model.findOneAndUpdate()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate), by default you'll see one of the below deprecation warnings.
```
DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#-findandmodify-
DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
```
Mongoose's `findOneAndUpdate()` long pre-dates the MongoDB driver's `findOneAndUpdate()` function, so it uses the MongoDB driver's [`findAndModify()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findAndModify) instead. You can opt in to using the MongoDB driver's `findOneAndUpdate()` function using the [`useFindAndModify` global option](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set).
```
// Make Mongoose use `findOneAndUpdate()`. Note that this option is `true`
// by default, you need to set it to false.
mongoose.set('useFindAndModify', false);
```
You can also configure `useFindAndModify` by passing it through the connection options.
```
mongoose.connect(uri, { useFindAndModify: false });
```
This option affects the following model and query functions. There are no intentional backwards breaking changes, so you should be able to turn this option on without any code changes. If you discover any issues, please [open an issue on GitHub](https://github.com/Automattic/mongoose/issues/new).
* [`Model.findByIdAndDelete()`](https://mongoosejs.com/docs/api.html#model_Model.findByIdAndDelete)
* [`Model.findByIdAndRemove()`](https://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove)
* [`Model.findByIdAndUpdate()`](https://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate)
* [`Model.findOneAndDelete()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndDelete)
* [`Model.findOneAndRemove()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove)
* [`Model.findOneAndUpdate()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate)
* [`Query.findOneAndDelete()`](https://mongoosejs.com/docs/api.html#query_Query-findOneAndDelete)
* [`Query.findOneAndRemove()`](https://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove)
* [`Query.findOneAndUpdate()`](https://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate)
`ensureIndex()`
---------------
If you define [indexes in your Mongoose schemas](guide#indexes), you'll see the below deprecation warning.
```
DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes
instead.
```
By default, Mongoose 5.x calls the [MongoDB driver's `ensureIndex()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#ensureIndex). The MongoDB driver deprecated this function in favor of [`createIndex()`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndex). Set the [`useCreateIndex` global option](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set) to opt in to making Mongoose use `createIndex()` instead.
```
mongoose.set('useCreateIndex', true);
```
You can also configure `useCreateIndex` by passing it through the connection options.
```
mongoose.connect(uri, { useCreateIndex: true });
```
There are no intentional backwards breaking changes with the `useCreateIndex` option, so you should be able to turn this option on without any code changes. If you discover any issues, please [open an issue on GitHub](https://github.com/Automattic/mongoose/issues/new).
`remove()`
----------
The MongoDB driver's [`remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove) is deprecated in favor of `deleteOne()` and `deleteMany()`. This is to comply with the [MongoDB CRUD specification](https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst), which aims to provide a consistent API for CRUD operations across all MongoDB drivers.
```
DeprecationWarning: collection.remove is deprecated. Use deleteOne,
deleteMany, or bulkWrite instead.
```
To remove this deprecation warning, replace any usage of `remove()` with `deleteMany()`, *unless* you specify the [`single` option to `remove()`](https://mongoosejs.com/docs/api.html#model_Model.remove). The `single` option limited `remove()` to deleting at most one document, so you should replace `remove(filter, { single: true })` with `deleteOne(filter)`.
```
// Replace this:
MyModel.remove({ foo: 'bar' });
// With this:
MyModel.deleteMany({ foo: 'bar' });
// Replace this:
MyModel.remove({ answer: 42 }, { single: true });
// With this:
MyModel.deleteOne({ answer: 42 });
```
`useUnifiedTopology`
--------------------
By default, `mongoose.connect()` will print out the below warning:
```
DeprecationWarning: current Server Discovery and Monitoring engine is
deprecated, and will be removed in a future version. To use the new Server
Discover and Monitoring engine, pass option { useUnifiedTopology: true } to
the MongoClient constructor.
```
Mongoose 5.7 uses MongoDB driver 3.3.x, which introduced a significant refactor of how it handles monitoring all the servers in a replica set or sharded cluster. In MongoDB parlance, this is known as [server discovery and monitoring](https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst).
To opt in to using the new topology engine, use the below line:
```
mongoose.set('useUnifiedTopology', true);
```
The `useUnifiedTopology` option removes support for several [connection options](connections#options) that are no longer relevant with the new topology engine:
* `autoReconnect`
* `reconnectTries`
* `reconnectInterval`
When you enable `useUnifiedTopology`, please remove those options from your [`mongoose.connect()`](api/mongoose#mongoose_Mongoose-connect) or [`createConnection()`](api/mongoose#mongoose_Mongoose-createConnection) calls.
If you find any unexpected behavior, please [open up an issue on GitHub](https://github.com/Automattic/mongoose/issues/new).
`update()`
----------
Like `remove()`, the [`update()` function](https://mongoosejs.com/docs/api.html#model_Model.update) is deprecated in favor of the more explicit [`updateOne()`](https://mongoosejs.com/docs/api.html#model_Model.updateOne), [`updateMany()`](https://mongoosejs.com/docs/api.html#model_Model.updateMany), and [`replaceOne()`](https://mongoosejs.com/docs/api.html#model_Model.replaceOne) functions. You should replace `update()` with `updateOne()`, unless you use the [`multi` or `overwrite` options](https://mongoosejs.com/docs/api.html#model_Model.update).
```
collection.update is deprecated. Use updateOne, updateMany, or bulkWrite
instead.
```
```
// Replace this:
MyModel.update({ foo: 'bar' }, { answer: 42 });
// With this:
MyModel.updateOne({ foo: 'bar' }, { answer: 42 });
// If you use `overwrite: true`, you should use `replaceOne()` instead:
MyModel.update(filter, update, { overwrite: true });
// Replace with this:
MyModel.replaceOne(filter, update);
// If you use `multi: true`, you should use `updateMany()` instead:
MyModel.update(filter, update, { multi: true });
// Replace with this:
MyModel.updateMany(filter, update);
```
`count()`
---------
The MongoDB server has deprecated the `count()` function in favor of two separate functions, [`countDocuments()`](#query_Query-countDocuments) and [`estimatedDocumentCount()`](#query_Query-estimatedDocumentCount).
```
DeprecationWarning: collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead
```
The difference between the two is `countDocuments()` can accept a filter parameter like [`find()`](#query_Query-find). The `estimatedDocumentCount()` function is faster, but can only tell you the total number of documents in a collection. You cannot pass a `filter` to `estimatedDocumentCount()`.
To migrate, replace `count()` with `countDocuments()` *unless* you do not pass any arguments to `count()`. If you use `count()` to count all documents in a collection as opposed to counting documents that match a query, use `estimatedDocumentCount()` instead of `countDocuments()`.
```
// Replace this:
MyModel.count({ answer: 42 });
// With this:
MyModel.countDocuments({ answer: 42 });
// If you're counting all documents in the collection, use
// `estimatedDocumentCount()` instead.
MyModel.count();
// Replace with:
MyModel.estimatedDocumentCount();
// Replace this:
MyModel.find({ answer: 42 }).count().exec();
// With this:
MyModel.find({ answer: 42 }).countDocuments().exec();
// Replace this:
MyModel.find().count().exec();
// With this, since there's no filter
MyModel.find().estimatedDocumentCount().exec();
```
`GridStore`
-----------
If you're using [gridfs-stream](https://www.npmjs.com/package/gridfs-stream), you'll see the below deprecation warning:
```
DeprecationWarning: GridStore is deprecated, and will be removed in a
future version. Please use GridFSBucket instead.
```
That is because gridfs-stream relies on a [deprecated MongoDB driver class](http://mongodb.github.io/node-mongodb-native/3.1/api/GridStore.html). You should instead use the [MongoDB driver's own streaming API](https://thecodebarbarian.com/mongodb-gridfs-stream).
```
// Replace this:
const conn = mongoose.createConnection('mongodb://localhost:27017/gfstest');
const gfs = require('gridfs-store')(conn.db);
const writeStream = gfs.createWriteStream({ filename: 'test.dat' });
// With this:
const conn = mongoose.createConnection('mongodb://localhost:27017/gfstest');
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db);
const writeStream = gridFSBucket.openUploadStream('test.dat');
```
mongoose SchemaTypes SchemaTypes
===========
SchemaTypes handle definition of path [defaults](https://mongoosejs.com/docs/api.html#schematype_SchemaType-default), [validation](https://mongoosejs.com/docs/api.html#schematype_SchemaType-validate), [getters](#getters), [setters](https://mongoosejs.com/docs/api.html#schematype_SchemaType-set), [field selection defaults](https://mongoosejs.com/docs/api.html#schematype_SchemaType-select) for [queries](https://mongoosejs.com/docs/api.html#query-js), and other general characteristics for Mongoose document properties.
* [What is a SchemaType?](#what-is-a-schematype)
* [The `type` Key](#type-key)
* [SchemaType Options](#schematype-options)
* [Usage Notes](#usage-notes)
* [Getters](#getters)
* [Custom Types](#customtypes)
* [The `schema.path()` Function](#path)
What is a SchemaType?
---------------------
You can think of a Mongoose schema as the configuration object for a Mongoose model. A SchemaType is then a configuration object for an individual property. A SchemaType says what type a given path should have, whether it has any getters/setters, and what values are valid for that path.
```
const schema = new Schema({ name: String });
schema.path('name') instanceof mongoose.SchemaType; // true
schema.path('name') instanceof mongoose.Schema.Types.String; // true
schema.path('name').instance; // 'String'
```
A SchemaType is different from a type. In other words, `mongoose.ObjectId !== mongoose.Types.ObjectId`. A SchemaType is just a configuration object for Mongoose. An instance of the `mongoose.ObjectId` SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
The following are all the valid SchemaTypes in Mongoose. Mongoose plugins can also add custom SchemaTypes like [int32](http://plugins.mongoosejs.io/plugins/int32). Check out [Mongoose's plugins search](http://plugins.mongoosejs.io) to find plugins.
* [String](#strings)
* [Number](#numbers)
* [Date](#dates)
* [Buffer](#buffers)
* [Boolean](#booleans)
* [Mixed](#mixed)
* [ObjectId](#objectids)
* [Array](#arrays)
* [Decimal128](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-Decimal128)
* [Map](#maps)
#### Example
```
var schema = new Schema({
name: String,
binary: Buffer,
living: Boolean,
updated: { type: Date, default: Date.now },
age: { type: Number, min: 18, max: 65 },
mixed: Schema.Types.Mixed,
_someId: Schema.Types.ObjectId,
decimal: Schema.Types.Decimal128,
array: [],
ofString: [String],
ofNumber: [Number],
ofDates: [Date],
ofBuffer: [Buffer],
ofBoolean: [Boolean],
ofMixed: [Schema.Types.Mixed],
ofObjectId: [Schema.Types.ObjectId],
ofArrays: [[]],
ofArrayOfNumbers: [[Number]],
nested: {
stuff: { type: String, lowercase: true, trim: true }
},
map: Map,
mapOfString: {
type: Map,
of: String
}
})
// example use
var Thing = mongoose.model('Thing', schema);
var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = Buffer.alloc(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.map = new Map([['key', 'value']]);
m.save(callback);
```
The `type` Key
--------------
`type` is a special property in Mongoose schemas. When Mongoose finds a nested property named `type` in your schema, Mongoose assumes that it needs to define a SchemaType with the given type.
```
// 3 string SchemaTypes: 'name', 'nested.firstName', 'nested.lastName'
const schema = new Schema({
name: { type: String },
nested: {
firstName: { type: String },
lastName: { type: String }
}
});
```
As a consequence, [you need a little extra work to define a property named `type` in your schema](https://mongoosejs.com/docs/faq.html#type-key). For example, suppose you're building a stock portfolio app, and you want to store the asset's `type` (stock, bond, ETF, etc.). Naively, you might define your schema as shown below:
```
const holdingSchema = new Schema({
// You might expect `asset` to be an object that has 2 properties,
// but unfortunately `type` is special in Mongoose so mongoose
// interprets this schema to mean that `asset` is a string
asset: {
type: String,
ticker: String
}
});
```
However, when Mongoose sees `type: String`, it assumes that you mean `asset` should be a string, not an object with a property `type`. The correct way to define an object with a property `type` is shown below.
```
const holdingSchema = new Schema({
asset: {
// Workaround to make sure Mongoose knows `asset` is an object
// and `asset.type` is a string, rather than thinking `asset`
// is a string.
type: { type: String },
ticker: String
}
});
```
SchemaType Options
------------------
You can declare a schema type using the type directly, or an object with a `type` property.
```
var schema1 = new Schema({
test: String // `test` is a path of type String
});
var schema2 = new Schema({
// The `test` object contains the "SchemaType options"
test: { type: String } // `test` is a path of type string
});
```
In addition to the type property, you can specify additional properties for a path. For example, if you want to lowercase a string before saving:
```
var schema2 = new Schema({
test: {
type: String,
lowercase: true // Always convert `test` to lowercase
}
});
```
You can add any property you want to your SchemaType options. Many plugins rely on custom SchemaType options. For example, the [mongoose-autopopulate](http://plugins.mongoosejs.io/plugins/autopopulate) plugin automatically populates paths if you set `autopopulate: true` in your SchemaType options. Mongoose comes with support for several built-in SchemaType options, like `lowercase` in the above example.
The `lowercase` option only works for strings. There are certain options which apply for all schema types, and some that apply for specific schema types.
##### All Schema Types
* `required`: boolean or function, if true adds a [required validator](validation#built-in-validators) for this property
* `default`: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default.
* `select`: boolean, specifies default [projections](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/) for queries
* `validate`: function, adds a [validator function](validation#built-in-validators) for this property
* `get`: function, defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
* `set`: function, defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
* `alias`: string, mongoose >= 4.10.0 only. Defines a [virtual](guide#virtuals) with the given name that gets/sets this path.
```
var numberSchema = new Schema({
integerOnly: {
type: Number,
get: v => Math.round(v),
set: v => Math.round(v),
alias: 'i'
}
});
var Number = mongoose.model('Number', numberSchema);
var doc = new Number();
doc.integerOnly = 2.001;
doc.integerOnly; // 2
doc.i; // 2
doc.i = 3.001;
doc.integerOnly; // 3
doc.i; // 3
```
##### Indexes
You can also define [MongoDB indexes](https://docs.mongodb.com/manual/indexes/) using schema type options.
* `index`: boolean, whether to define an [index](https://docs.mongodb.com/manual/indexes/) on this property.
* `unique`: boolean, whether to define a [unique index](https://docs.mongodb.com/manual/core/index-unique/) on this property.
* `sparse`: boolean, whether to define a [sparse index](https://docs.mongodb.com/manual/core/index-sparse/) on this property.
```
var schema2 = new Schema({
test: {
type: String,
index: true,
unique: true // Unique index. If you specify `unique: true`
// specifying `index: true` is optional if you do `unique: true`
}
});
```
##### String
* `lowercase`: boolean, whether to always call `.toLowerCase()` on the value
* `uppercase`: boolean, whether to always call `.toUpperCase()` on the value
* `trim`: boolean, whether to always call `.trim()` on the value
* `match`: RegExp, creates a [validator](validation) that checks if the value matches the given regular expression
* `enum`: Array, creates a [validator](validation) that checks if the value is in the given array.
* `minlength`: Number, creates a [validator](validation) that checks if the value length is not less than the given number
* `maxlength`: Number, creates a [validator](validation) that checks if the value length is not greater than the given number
##### Number
* `min`: Number, creates a [validator](validation) that checks if the value is greater than or equal to the given minimum.
* `max`: Number, creates a [validator](validation) that checks if the value is less than or equal to the given maximum.
* `enum`: Array, creates a [validator](validation) that checks if the value is strictly equal to one of the values in the given array.
##### Date
* `min`: Date
* `max`: Date
Usage Notes
-----------
#### String
To declare a path as a string, you may use either the `String` global constructor or the string `'String'`.
```
const schema1 = new Schema({ name: String }); // name will be cast to string
const schema2 = new Schema({ name: 'String' }); // Equivalent
const Person = mongoose.model('Person', schema2);
```
If you pass an element that has a `toString()` function, Mongoose will call it, unless the element is an array or the `toString()` function is strictly equal to `Object.prototype.toString()`.
```
new Person({ name: 42 }).name; // "42" as a string
new Person({ name: { toString: () => 42 } }).name; // "42" as a string
// "undefined", will get a cast error if you `save()` this document
new Person({ name: { foo: 42 } }).name;
```
#### Number
To declare a path as a number, you may use either the `Number` global constructor or the string `'Number'`.
```
const schema1 = new Schema({ age: Number }); // age will be cast to a Number
const schema2 = new Schema({ age: 'Number' }); // Equivalent
const Car = mongoose.model('Car', schema2);
```
There are several types of values that will be successfully cast to a Number.
```
new Car({ age: '15' }).age; // 15 as a Number
new Car({ age: true }).age; // 1 as a Number
new Car({ age: false }).age; // 0 as a Number
new Car({ age: { valueOf: () => 83 } }).age; // 83 as a Number
```
If you pass an object with a `valueOf()` function that returns a Number, Mongoose will call it and assign the returned value to the path.
The values `null` and `undefined` are not cast.
NaN, strings that cast to NaN, arrays, and objects that don't have a `valueOf()` function will all result in a [CastError](https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError).
#### Dates
[Built-in `Date` methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) are [**not** hooked into](https://github.com/Automattic/mongoose/issues/1598) the mongoose change tracking logic which in English means that if you use a `Date` in your document and modify it with a method like `setMonth()`, mongoose will be unaware of this change and `doc.save()` will not persist this modification. If you must modify `Date` types using built-in methods, tell mongoose about the change with `doc.markModified('pathToYourDate')` before saving.
```
var Assignment = mongoose.model('Assignment', { dueDate: Date });
Assignment.findOne(function (err, doc) {
doc.dueDate.setMonth(3);
doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE
doc.markModified('dueDate');
doc.save(callback); // works
})
```
#### Buffer
To declare a path as a Buffer, you may use either the `Buffer` global constructor or the string `'Buffer'`.
```
const schema1 = new Schema({ binData: Buffer }); // binData will be cast to a Buffer
const schema2 = new Schema({ binData: 'Buffer' }); // Equivalent
const Data = mongoose.model('Data', schema2);
```
Mongoose will successfully cast the below values to buffers.
```
const file1 = new Data({ binData: 'test'}); // {"type":"Buffer","data":[116,101,115,116]}
const file2 = new Data({ binData: 72987 }); // {"type":"Buffer","data":[27]}
const file4 = new Data({ binData: { type: 'Buffer', data: [1, 2, 3]}}); // {"type":"Buffer","data":[1,2,3]}
```
#### Mixed
An "anything goes" SchemaType. Mongoose will not do any casting on mixed paths. You can define a mixed path using `Schema.Types.Mixed` or by passing an empty object literal. The following are equivalent.
```
const Any = new Schema({ any: {} });
const Any = new Schema({ any: Object });
const Any = new Schema({ any: Schema.Types.Mixed });
const Any = new Schema({ any: mongoose.Mixed });
// Note that by default, if you're using `type`, putting \_any\_ POJO as the `type` will
// make the path mixed.
const Any = new Schema({
any: {
type: { foo: String }
} // "any" will be Mixed - everything inside is ignored.
});
// However, as of Mongoose 5.8.0, this behavior can be overridden with typePojoToMixed.
// In that case, it will create a single nested subdocument type instead.
const Any = new Schema({
any: {
type: { foo: String }
} // "any" will be a single nested subdocument.
}, {typePojoToMixed: false});
```
Since Mixed is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To tell Mongoose that the value of a Mixed type has changed, you need to call `doc.markModified(path)`, passing the path to the Mixed type you just changed.
To avoid these side-effects, a [Subdocument](subdocs) path may be used instead.
```
person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // Mongoose will save changes to `anything`.
```
#### ObjectIds
To specify a type of ObjectId, use `Schema.Types.ObjectId` in your declaration.
```
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var Car = new Schema({ driver: ObjectId });
// or just Schema.ObjectId for backwards compatibility with v2
```
#### Boolean
Booleans in Mongoose are [plain JavaScript booleans](https://www.w3schools.com/js/js_booleans.asp). By default, Mongoose casts the below values to `true`:
* `true`
* `'true'`
* `1`
* `'1'`
* `'yes'`
Mongoose casts the below values to `false`:
* `false`
* `'false'`
* `0`
* `'0'`
* `'no'`
Any other value causes a [CastError](https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError). You can modify what values Mongoose converts to true or false using the `convertToTrue` and `convertToFalse` properties, which are [JavaScript sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).
```
const M = mongoose.model('Test', new Schema({ b: Boolean }));
console.log(new M({ b: 'nay' }).b); // undefined
// Set { false, 'false', 0, '0', 'no' }
console.log(mongoose.Schema.Types.Boolean.convertToFalse);
mongoose.Schema.Types.Boolean.convertToFalse.add('nay');
console.log(new M({ b: 'nay' }).b); // false
```
#### Arrays
Mongoose supports arrays of [SchemaTypes](https://mongoosejs.com/docs/api.html#schema_Schema.Types) and arrays of [subdocuments](subdocs). Arrays of SchemaTypes are also called *primitive arrays*, and arrays of subdocuments are also called *document arrays*.
```
var ToySchema = new Schema({ name: String });
var ToyBoxSchema = new Schema({
toys: [ToySchema],
buffers: [Buffer],
strings: [String],
numbers: [Number]
// ... etc
});
```
Arrays are special because they implicitly have a default value of `[]` (empty array).
```
var ToyBox = mongoose.model('ToyBox', ToyBoxSchema);
console.log((new ToyBox()).toys); // []
```
To overwrite this default, you need to set the default value to `undefined`
```
var ToyBoxSchema = new Schema({
toys: {
type: [ToySchema],
default: undefined
}
});
```
Note: specifying an empty array is equivalent to `Mixed`. The following all create arrays of `Mixed`:
```
var Empty1 = new Schema({ any: [] });
var Empty2 = new Schema({ any: Array });
var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
var Empty4 = new Schema({ any: [{}] });
```
#### Maps
*New in Mongoose 5.1.0*
A `MongooseMap` is a subclass of [JavaScript's `Map` class](http://thecodebarbarian.com/the-80-20-guide-to-maps-in-javascript.html). In these docs, we'll use the terms 'map' and `MongooseMap` interchangeably. In Mongoose, maps are how you create a nested document with arbitrary keys.
**Note**: In Mongoose Maps, keys must be strings in order to store the document in MongoDB.
```
const userSchema = new Schema({
// `socialMediaHandles` is a map whose values are strings. A map's
// keys are always strings. You specify the type of values using `of`.
socialMediaHandles: {
type: Map,
of: String
}
});
const User = mongoose.model('User', userSchema);
// Map { 'github' => 'vkarpov15', 'twitter' => '@code\_barbarian' }
console.log(new User({
socialMediaHandles: {
github: 'vkarpov15',
twitter: '@code\_barbarian'
}
}).socialMediaHandles);
```
The above example doesn't explicitly declare `github` or `twitter` as paths, but, since `socialMediaHandles` is a map, you can store arbitrary key/value pairs. However, since `socialMediaHandles` is a map, you **must** use `.get()` to get the value of a key and `.set()` to set the value of a key.
```
const user = new User({
socialMediaHandles: {}
});
// Good
user.socialMediaHandles.set('github', 'vkarpov15');
// Works too
user.set('socialMediaHandles.twitter', '@code\_barbarian');
// Bad, the `myspace` property will \*\*not\*\* get saved
user.socialMediaHandles.myspace = 'fail';
// 'vkarpov15'
console.log(user.socialMediaHandles.get('github'));
// '@code\_barbarian'
console.log(user.get('socialMediaHandles.twitter'));
// undefined
user.socialMediaHandles.github;
// Will only save the 'github' and 'twitter' properties
user.save();
```
Map types are stored as [BSON objects in MongoDB](https://en.wikipedia.org/wiki/BSON#Data_types_and_syntax). Keys in a BSON object are ordered, so this means the [insertion order](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description) property of maps is maintained.
Getters
-------
Getters are like virtuals for paths defined in your schema. For example, let's say you wanted to store user profile pictures as relative paths and then add the hostname in your application. Below is how you would structure your `userSchema`:
```
const root = 'https://s3.amazonaws.com/mybucket';
const userSchema = new Schema({
name: String,
picture: {
type: String,
get: v => `${root}${v}`
}
});
const User = mongoose.model('User', userSchema);
const doc = new User({ name: 'Val', picture: '/123.png' });
doc.picture; // 'https://s3.amazonaws.com/mybucket/123.png'
doc.toObject({ getters: false }).picture; // '123.png'
```
Generally, you only use getters on primitive paths as opposed to arrays or subdocuments. Because getters override what accessing a Mongoose path returns, declaring a getter on an object may remove Mongoose change tracking for that path.
```
const schema = new Schema({
arr: [{ url: String }]
});
const root = 'https://s3.amazonaws.com/mybucket';
// Bad, don't do this!
schema.path('arr').get(v => {
return v.map(el => Object.assign(el, { url: root + el.url }));
});
// Later
doc.arr.push({ key: String });
doc.arr[0]; // 'undefined' because every `doc.arr` creates a new array!
```
Instead of declaring a getter on the array as shown above, you should declare a getter on the `url` string as shown below. If you need to declare a getter on a nested document or array, be very careful!
```
const schema = new Schema({
arr: [{ url: String }]
});
const root = 'https://s3.amazonaws.com/mybucket';
// Good, do this instead of declaring a getter on `arr`
schema.path('arr.0.url').get(v => `${root}${v}`);
```
Creating Custom Types
---------------------
Mongoose can also be extended with [custom SchemaTypes](customschematypes). Search the [plugins](http://plugins.mongoosejs.io) site for compatible types like [mongoose-long](https://github.com/aheckmann/mongoose-long), [mongoose-int32](https://github.com/vkarpov15/mongoose-int32), and [other](https://github.com/aheckmann/mongoose-function) [types](https://github.com/OpenifyIt/mongoose-types).
Read more about creating [custom SchemaTypes here](customschematypes).
The `schema.path()` Function
----------------------------
The `schema.path()` function returns the instantiated schema type for a given path.
```
var sampleSchema = new Schema({ name: { type: String, required: true } });
console.log(sampleSchema.path('name'));
// Output looks like:
/\*\*
\* SchemaString {
\* enumValues: [],
\* regExp: null,
\* path: 'name',
\* instance: 'String',
\* validators: ...
\*/
```
You can use this function to inspect the schema type for a given path, including what validators it has and what the type is.
Next Up
-------
Now that we've covered `SchemaTypes`, let's take a look at [Connections](connections).
| programming_docs |
mongoose Getting Started Getting Started
===============
*First be sure you have [MongoDB](http://www.mongodb.org/downloads) and [Node.js](http://nodejs.org/) installed.*
Next install Mongoose from the command line using `npm`:
```
$ npm install mongoose
```
Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is include mongoose in our project and open a connection to the `test` database on our locally running instance of MongoDB.
```
// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
```
We have a pending connection to the test database running on localhost. We now need to get notified if we connect successfully or if a connection error occurs:
```
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
```
Once our connection opens, our callback will be called. For brevity, let's assume that all following code is within this callback.
With Mongoose, everything is derived from a [Schema](guide). Let's get a reference to it and define our kittens.
```
var kittySchema = new mongoose.Schema({
name: String
});
```
So far so good. We've got a schema with one property, `name`, which will be a `String`. The next step is compiling our schema into a [Model](models).
```
var Kitten = mongoose.model('Kitten', kittySchema);
```
A model is a class with which we construct documents. In this case, each document will be a kitten with properties and behaviors as declared in our schema. Let's create a kitten document representing the little guy we just met on the sidewalk outside:
```
var silence = new Kitten({ name: 'Silence' });
console.log(silence.name); // 'Silence'
```
Kittens can meow, so let's take a look at how to add "speak" functionality to our documents:
```
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);
```
Functions added to the `methods` property of a schema get compiled into the `Model` prototype and exposed on each document instance:
```
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"
```
We have talking kittens! But we still haven't saved anything to MongoDB. Each document can be saved to the database by calling its [save](https://mongoosejs.com/docs/api.html#model_Model-save) method. The first argument to the callback will be an error if any occurred.
```
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});
```
Say time goes by and we want to display all the kittens we've seen. We can access all of the kitten documents through our Kitten [model](models).
```
Kitten.find(function (err, kittens) {
if (err) return console.error(err);
console.log(kittens);
})
```
We just logged all of the kittens in our db to the console. If we want to filter our kittens by name, Mongoose supports MongoDBs rich [querying](queries) syntax.
```
Kitten.find({ name: /^fluff/ }, callback);
```
This performs a search for all documents with a name property that begins with "Fluff" and returns the result as an array of kittens to the callback.
Congratulations
---------------
That's the end of our quick start. We created a schema, added a custom document method, saved and queried kittens in MongoDB using Mongoose. Head over to the <guide>, or [API docs](https://mongoosejs.com/docs/api.html) for more.
mongoose Schemas Schemas
=======
If you haven't yet done so, please take a minute to read the [quickstart](index) to get an idea of how Mongoose works. If you are migrating from 4.x to 5.x please take a moment to read the [migration guide](migrating_to_5).
Defining your schema
--------------------
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
```
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String, // String is shorthand for {type: String}
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
```
If you want to add additional keys later, use the [Schema#add](https://mongoosejs.com/docs/api.html#schema_Schema-add) method.
Each key in our code `blogSchema` defines a property in our documents which will be cast to its associated [SchemaType](https://mongoosejs.com/docs/api.html#schematype_SchemaType). For example, we've defined a property `title` which will be cast to the [String](https://mongoosejs.com/docs/api.html#schema-string-js) SchemaType and property `date` which will be cast to a `Date` SchemaType.
Notice above that if a property only requires a type, it can be specified using a shorthand notation (contrast the `title` property above with the `date` property).
Keys may also be assigned nested objects containing further key/type definitions like the `meta` property above. This will happen whenever a key's value is a POJO that lacks a bona-fide `type` property. In these cases, only the leaves in a tree are given actual paths in the schema (like `meta.votes` and `meta.favs` above), and the branches do not have actual paths. A side-effect of this is that `meta` above cannot have its own validation. If validation is needed up the tree, a path needs to be created up the tree - see the [Subdocuments](subdocs) section for more information no how to do this. Also read the [Mixed](schematypes) subsection of the SchemaTypes guide for some gotchas.
The permitted SchemaTypes are:
* [String](schematypes#strings)
* [Number](schematypes#numbers)
* [Date](schematypes#dates)
* [Buffer](schematypes#buffers)
* [Boolean](schematypes#booleans)
* [Mixed](schematypes#mixed)
* [ObjectId](schematypes#objectids)
* [Array](schematypes#arrays)
* [Decimal128](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-Decimal128)
* [Map](schematypes#maps)
Read more about [SchemaTypes here](schematypes).
Schemas not only define the structure of your document and casting of properties, they also define document [instance methods](#methods), [static Model methods](#statics), [compound indexes](#indexes), and document lifecycle hooks called <middleware>.
Creating a model
----------------
To use our schema definition, we need to convert our `blogSchema` into a [Model](models) we can work with. To do so, we pass it into `mongoose.model(modelName, schema)`:
```
var Blog = mongoose.model('Blog', blogSchema);
// ready to go!
```
Instance methods
----------------
Instances of `Models` are <documents>. Documents have many of their own [built-in instance methods](https://mongoosejs.com/docs/api.html#document-js). We may also define our own custom document instance methods too.
```
// define a schema
var animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
```
Now all of our `animal` instances have a `findSimilarTypes` method available to them.
```
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function(err, dogs) {
console.log(dogs); // woof
});
```
* Overwriting a default mongoose document method may lead to unpredictable results. See [this](https://mongoosejs.com/docs/api.html#schema_Schema.reserved) for more details.
* The example above uses the `Schema.methods` object directly to save an instance method. You can also use the `Schema.method()` helper as described [here](https://mongoosejs.com/docs/api.html#schema_Schema-method).
* Do **not** declare methods using ES6 arrow functions (`=>`). Arrow functions [explicitly prevent binding `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this), so your method will **not** have access to the document and the above examples will not work.
Statics
-------
You can also add static functions to your model. There are 2 equivalent ways to add a static:
* Add a function property to `schema.statics`
* Call the [`Schema#static()` function](https://mongoosejs.com/docs/api.html#schema_Schema-static)
```
// Assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function(name) {
return this.find({ name: new RegExp(name, 'i') });
};
// Or, equivalently, you can call `animalSchema.static()`.
animalSchema.static('findByBreed', function(breed) {
return this.find({ breed });
});
const Animal = mongoose.model('Animal', animalSchema);
let animals = await Animal.findByName('fido');
animls = animals.concat(await Animal.findByBreed('Poodle'));
```
Do **not** declare statics using ES6 arrow functions (`=>`). Arrow functions [explicitly prevent binding `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this), so the above examples will not work because of the value of `this`.
Query Helpers
-------------
You can also add query helper functions, which are like instance methods but for mongoose queries. Query helper methods let you extend mongoose's [chainable query builder API](queries).
```
animalSchema.query.byName = function(name) {
return this.where({ name: new RegExp(name, 'i') });
};
var Animal = mongoose.model('Animal', animalSchema);
Animal.find().byName('fido').exec(function(err, animals) {
console.log(animals);
});
Animal.findOne().byName('fido').exec(function(err, animal) {
console.log(animal);
});
```
Indexes
-------
MongoDB supports [secondary indexes](http://docs.mongodb.org/manual/indexes/). With mongoose, we define these indexes within our `Schema` [at](https://mongoosejs.com/docs/api.html#schematype_SchemaType-index) [the](https://mongoosejs.com/docs/api.html#schematype_SchemaType-unique) [path](https://mongoosejs.com/docs/api.html#schematype_SchemaType-sparse) [level](https://mongoosejs.com/docs/api.html#schema_date_SchemaDate-expires) or the `schema` level. Defining indexes at the schema level is necessary when creating [compound indexes](https://docs.mongodb.com/manual/core/index-compound/).
```
var animalSchema = new Schema({
name: String,
type: String,
tags: { type: [String], index: true } // field level
});
animalSchema.index({ name: 1, type: -1 }); // schema level
```
When your application starts up, Mongoose automatically calls [`createIndex`](https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex) for each defined index in your schema. Mongoose will call `createIndex` for each index sequentially, and emit an 'index' event on the model when all the `createIndex` calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a [significant performance impact](https://docs.mongodb.com/manual/core/index-creation/#index-build-impact-on-database-performance). Disable the behavior by setting the `autoIndex` option of your schema to `false`, or globally on the connection by setting the option `autoIndex` to `false`.
```
mongoose.connect('mongodb://user:pass@localhost:port/database', { autoIndex: false });
// or
mongoose.createConnection('mongodb://user:pass@localhost:port/database', { autoIndex: false });
// or
animalSchema.set('autoIndex', false);
// or
new Schema({..}, { autoIndex: false });
```
Mongoose will emit an `index` event on the model when indexes are done building or an error occurred.
```
// Will cause an error because mongodb has an \_id index by default that
// is not sparse
animalSchema.index({ _id: 1 }, { sparse: true });
var Animal = mongoose.model('Animal', animalSchema);
Animal.on('index', function(error) {
// "\_id index cannot be sparse"
console.log(error.message);
});
```
See also the [Model#ensureIndexes](https://mongoosejs.com/docs/api.html#model_Model.ensureIndexes) method.
Virtuals
--------
[Virtuals](https://mongoosejs.com/docs/api.html#schema_Schema-virtual) are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage.
```
// define a schema
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
// compile our model
var Person = mongoose.model('Person', personSchema);
// create a document
var axl = new Person({
name: { first: 'Axl', last: 'Rose' }
});
```
Suppose you want to print out the person's full name. You could do it yourself:
```
console.log(axl.name.first + ' ' + axl.name.last); // Axl Rose
```
But concatenating the first and last name every time can get cumbersome. And what if you want to do some extra processing on the name, like [removing diacritics](https://www.npmjs.com/package/diacritics)? A [virtual property getter](https://mongoosejs.com/docs/api.html#virtualtype_VirtualType-get) lets you define a `fullName` property that won't get persisted to MongoDB.
```
personSchema.virtual('fullName').get(function () {
return this.name.first + ' ' + this.name.last;
});
```
Now, mongoose will call your getter function every time you access the `fullName` property:
```
console.log(axl.fullName); // Axl Rose
```
If you use `toJSON()` or `toObject()` mongoose will *not* include virtuals by default. This includes the output of calling [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) on a Mongoose document, because [`JSON.stringify()` calls `toJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description). Pass `{ virtuals: true }` to either [`toObject()`](https://mongoosejs.com/docs/api.html#document_Document-toObject) or [`toJSON()`](https://mongoosejs.com/docs/api.html#document_Document-toJSON).
You can also add a custom setter to your virtual that will let you set both first name and last name via the `fullName` virtual.
```
personSchema.virtual('fullName').
get(function() { return this.name.first + ' ' + this.name.last; }).
set(function(v) {
this.name.first = v.substr(0, v.indexOf(' '));
this.name.last = v.substr(v.indexOf(' ') + 1);
});
axl.fullName = 'William Rose'; // Now `axl.name.first` is "William"
```
Virtual property setters are applied before other validation. So the example above would still work even if the `first` and `last` name fields were required.
Only non-virtual properties work as part of queries and for field selection. Since virtuals are not stored in MongoDB, you can't query with them.
##### [Aliases](#aliases)
Aliases are a particular type of virtual where the getter and setter seamlessly get and set another property. This is handy for saving network bandwidth, so you can convert a short property name stored in the database into a longer name for code readability.
```
var personSchema = new Schema({
n: {
type: String,
// Now accessing `name` will get you the value of `n`, and setting `n` will set the value of `name`
alias: 'name'
}
});
// Setting `name` will propagate to `n`
var person = new Person({ name: 'Val' });
console.log(person); // { n: 'Val' }
console.log(person.toObject({ virtuals: true })); // { n: 'Val', name: 'Val' }
console.log(person.name); // "Val"
person.name = 'Not Val';
console.log(person); // { n: 'Not Val' }
```
You can also declare aliases on nested paths. It is easier to use nested schemas and [subdocuments](subdocs), but you can also declare nested path aliases inline as long as you use the full nested path `nested.myProp` as the alias.
```
const childSchema = new Schema({
n: {
type: String,
alias: 'name'
}
}, { _id: false });
const parentSchema = new Schema({
// If in a child schema, alias doesn't need to include the full nested path
c: childSchema,
name: {
f: {
type: String,
// Alias needs to include the full nested path if declared inline
alias: 'name.first'
}
}
});
```
Options
-------
Schemas have a few configurable options which can be passed to the constructor or `set` directly:
```
new Schema({..}, options);
// or
var schema = new Schema({..});
schema.set(option, value);
```
Valid options:
* [autoIndex](#autoIndex)
* [autoCreate](#autoCreate)
* [bufferCommands](#bufferCommands)
* [capped](#capped)
* [collection](#collection)
* [id](#id)
* [\_id](#_id)
* [minimize](#minimize)
* [read](#read)
* [writeConcern](#writeConcern)
* [shardKey](#shardKey)
* [strict](#strict)
* [strictQuery](#strictQuery)
* [toJSON](#toJSON)
* [toObject](#toObject)
* [typeKey](#typeKey)
* [useNestedStrict](#useNestedStrict)
* [validateBeforeSave](#validateBeforeSave)
* [versionKey](#versionKey)
* [collation](#collation)
* [selectPopulatedPaths](#selectPopulatedPaths)
* [skipVersioning](#skipVersioning)
* [timestamps](#timestamps)
* [storeSubdocValidationError](#storeSubdocValidationError)
option: autoIndex
-----------------
By default, Mongoose's [`init()` function](https://mongoosejs.com/docs/api.html#model_Model.init) creates all the indexes defined in your model's schema by calling [`Model.createIndexes()`](https://mongoosejs.com/docs/api.html#model_Model.createIndexes) after you successfully connect to MongoDB. Creating indexes automatically is great for development and test environments. But index builds can also create significant load on your production database. If you want to manage indexes carefully in production, you can set `autoIndex` to false.
```
const schema = new Schema({..}, { autoIndex: false });
const Clock = mongoose.model('Clock', schema);
Clock.ensureIndexes(callback);
```
The `autoIndex` option is set to `true` by default. You can change this default by setting [`mongoose.set('autoIndex', false);`](api/mongoose#mongoose_Mongoose-set)
option: autoCreate
------------------
Before Mongoose builds indexes, it calls `Model.createCollection()` to create the underlying collection in MongoDB if `autoCreate` is set to true. Calling `createCollection()` sets the [collection's default collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) based on the [collation option](#collation) and establishes the collection as a capped collection if you set the [`capped` schema option](#capped). Like `autoIndex`, setting `autoCreate` to true is helpful for development and test environments.
Unfortunately, `createCollection()` cannot change an existing collection. For example, if you add `capped: 1024` to your schema and the existing collection is not capped, `createCollection()` will throw an error. Generally, `autoCreate` should be `false` for production environments.
```
const schema = new Schema({..}, { autoCreate: true, capped: 1024 });
const Clock = mongoose.model('Clock', schema);
// Mongoose will create the capped collection for you.
```
Unlike `autoIndex`, `autoCreate` is `false` by default. You can change this default by setting [`mongoose.set('autoCreate', true);`](api/mongoose#mongoose_Mongoose-set)
option: bufferCommands
----------------------
By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect. To disable buffering, set `bufferCommands` to false.
```
var schema = new Schema({..}, { bufferCommands: false });
```
The schema `bufferCommands` option overrides the global `bufferCommands` option.
```
mongoose.set('bufferCommands', true);
// Schema option below overrides the above, if the schema option is set.
var schema = new Schema({..}, { bufferCommands: false });
```
option: capped
--------------
Mongoose supports MongoDBs [capped](http://www.mongodb.org/display/DOCS/Capped+Collections) collections. To specify the underlying MongoDB collection be `capped`, set the `capped` option to the maximum size of the collection in [bytes](http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-size.).
```
new Schema({..}, { capped: 1024 });
```
The `capped` option may also be set to an object if you want to pass additional options like [max](http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-max) or [autoIndexId](http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-autoIndexId). In this case you must explicitly pass the `size` option, which is required.
```
new Schema({..}, { capped: { size: 1024, max: 1000, autoIndexId: true } });
```
option: collection
------------------
Mongoose by default produces a collection name by passing the model name to the [utils.toCollectionName](https://mongoosejs.com/docs/api.html#utils_exports.toCollectionName) method. This method pluralizes the name. Set this option if you need a different name for your collection.
```
var dataSchema = new Schema({..}, { collection: 'data' });
```
option: id
----------
Mongoose assigns each of your schemas an `id` virtual getter by default which returns the documents `_id` field cast to a string, or in the case of ObjectIds, its hexString. If you don't want an `id` getter added to your schema, you may disable it passing this option at schema construction time.
```
// default behavior
var schema = new Schema({ name: String });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p.id); // '50341373e894ad16347efe01'
// disabled id
var schema = new Schema({ name: String }, { id: false });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p.id); // undefined
```
option: \_id
------------
Mongoose assigns each of your schemas an `_id` field by default if one is not passed into the [Schema](https://mongoosejs.com/docs/api.html#schema-js) constructor. The type assigned is an [ObjectId](https://mongoosejs.com/docs/api.html#schema_Schema.Types) to coincide with MongoDB's default behavior. If you don't want an `_id` added to your schema at all, you may disable it using this option.
You can **only** use this option on subdocuments. Mongoose can't save a document without knowing its id, so you will get an error if you try to save a document without an `_id`.
```
// default behavior
var schema = new Schema({ name: String });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p); // { \_id: '50341373e894ad16347efe01', name: 'mongodb.org' }
// disabled \_id
var childSchema = new Schema({ name: String }, { _id: false });
var parentSchema = new Schema({ children: [childSchema] });
var Model = mongoose.model('Model', parentSchema);
Model.create({ children: [{ name: 'Luke' }] }, function(error, doc) {
// doc.children[0].\_id will be undefined
});
```
option: minimize
----------------
Mongoose will, by default, "minimize" schemas by removing empty objects.
```
const schema = new Schema({ name: String, inventory: {} });
const Character = mongoose.model('Character', schema);
// will store `inventory` field if it is not empty
const frodo = new Character({ name: 'Frodo', inventory: { ringOfPower: 1 }});
await frodo.save();
let doc = await Character.findOne({ name: 'Frodo' }).lean();
doc.inventory; // { ringOfPower: 1 }
// will not store `inventory` field if it is empty
const sam = new Character({ name: 'Sam', inventory: {}});
await sam.save();
doc = await Character.findOne({ name: 'Sam' }).lean();
doc.inventory; // undefined
```
This behavior can be overridden by setting `minimize` option to `false`. It will then store empty objects.
```
const schema = new Schema({ name: String, inventory: {} }, { minimize: false });
const Character = mongoose.model('Character', schema);
// will store `inventory` if empty
const sam = new Character({ name: 'Sam', inventory: {} });
await sam.save();
doc = await Character.findOne({ name: 'Sam' }).lean();
doc.inventory; // {}
```
To check whether an object is empty, you can use the `$isEmpty()` helper:
```
const sam = new Character({ name: 'Sam', inventory: {} });
sam.$isEmpty('inventory'); // true
sam.inventory.barrowBlade = 1;
sam.$isEmpty('inventory'); // false
```
option: read
------------
Allows setting [query#read](https://mongoosejs.com/docs/api.html#query_Query-read) options at the schema level, providing us a way to apply default [ReadPreferences](http://docs.mongodb.org/manual/applications/replication/#replica-set-read-preference) to all queries derived from a model.
```
var schema = new Schema({..}, { read: 'primary' }); // also aliased as 'p'
var schema = new Schema({..}, { read: 'primaryPreferred' }); // aliased as 'pp'
var schema = new Schema({..}, { read: 'secondary' }); // aliased as 's'
var schema = new Schema({..}, { read: 'secondaryPreferred' }); // aliased as 'sp'
var schema = new Schema({..}, { read: 'nearest' }); // aliased as 'n'
```
The alias of each pref is also permitted so instead of having to type out 'secondaryPreferred' and getting the spelling wrong, we can simply pass 'sp'.
The read option also allows us to specify *tag sets*. These tell the [driver](https://github.com/mongodb/node-mongodb-native/) from which members of the replica-set it should attempt to read. Read more about tag sets [here](http://docs.mongodb.org/manual/applications/replication/#tag-sets) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
*NOTE: you may also specify the driver read pref [strategy](http://mongodb.github.com/node-mongodb-native/api-generated/replset.html?highlight=strategy) option when connecting:*
```
// pings the replset members periodically to track network latency
var options = { replset: { strategy: 'ping' }};
mongoose.connect(uri, options);
var schema = new Schema({..}, { read: ['nearest', { disk: 'ssd' }] });
mongoose.model('JellyBean', schema);
```
option: writeConcern
--------------------
Allows setting [write concern](https://docs.mongodb.com/manual/reference/write-concern/) at the schema level.
```
const schema = new Schema({ name: String }, {
writeConcern: {
w: 'majority',
j: true,
wtimeout: 1000
}
});
```
option: shardKey
----------------
The `shardKey` option is used when we have a [sharded MongoDB architecture](http://www.mongodb.org/display/DOCS/Sharding+Introduction). Each sharded collection is given a shard key which must be present in all insert/update operations. We just need to set this schema option to the same shard key and we’ll be all set.
```
new Schema({ .. }, { shardKey: { tag: 1, name: 1 }})
```
*Note that Mongoose does not send the `shardcollection` command for you. You must configure your shards yourself.*
option: strict
--------------
The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.
```
var thingSchema = new Schema({..})
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is not saved to the db
// set to false..
var thingSchema = new Schema({..}, { strict: false });
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is now saved to the db!!
```
This also affects the use of `doc.set()` to set a property value.
```
var thingSchema = new Schema({..})
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing;
thing.set('iAmNotInTheSchema', true);
thing.save(); // iAmNotInTheSchema is not saved to the db
```
This value can be overridden at the model instance level by passing a second boolean argument:
```
var Thing = mongoose.model('Thing');
var thing = new Thing(doc, true); // enables strict mode
var thing = new Thing(doc, false); // disables strict mode
```
The `strict` option may also be set to `"throw"` which will cause errors to be produced instead of dropping the bad data.
*NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.*
```
var thingSchema = new Schema({..})
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing;
thing.iAmNotInTheSchema = true;
thing.save(); // iAmNotInTheSchema is never saved to the db
```
option: strictQuery
-------------------
For backwards compatibility, the `strict` option does **not** apply to the `filter` parameter for queries.
```
const mySchema = new Schema({ field: Number }, { strict: true });
const MyModel = mongoose.model('Test', mySchema);
// Mongoose will \*\*not\*\* filter out `notInSchema: 1`, despite `strict: true`
MyModel.find({ notInSchema: 1 });
```
The `strict` option does apply to updates.
```
// Mongoose will strip out `notInSchema` from the update if `strict` is
// not `false`
MyModel.updateMany({}, { $set: { notInSchema: 1 } });
```
Mongoose has a separate `strictQuery` option to toggle strict mode for the `filter` parameter to queries.
```
const mySchema = new Schema({ field: Number }, {
strict: true,
strictQuery: true // Turn on strict mode for query filters
});
const MyModel = mongoose.model('Test', mySchema);
// Mongoose will strip out `notInSchema: 1` because `strictQuery` is `true`
MyModel.find({ notInSchema: 1 });
```
option: toJSON
--------------
Exactly the same as the [toObject](#toObject) option but only applies when the documents `toJSON` method is called.
```
var schema = new Schema({ name: String });
schema.path('name').get(function (v) {
return v + ' is my name';
});
schema.set('toJSON', { getters: true, virtuals: false });
var M = mongoose.model('Person', schema);
var m = new M({ name: 'Max Headroom' });
console.log(m.toObject()); // { \_id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom' }
console.log(m.toJSON()); // { \_id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' }
// since we know toJSON is called whenever a js object is stringified:
console.log(JSON.stringify(m)); // { "\_id": "504e0cd7dd992d9be2f20b6f", "name": "Max Headroom is my name" }
```
To see all available `toJSON/toObject` options, read [this](https://mongoosejs.com/docs/api.html#document_Document-toObject).
option: toObject
----------------
Documents have a [toObject](https://mongoosejs.com/docs/api.html#document_Document-toObject) method which converts the mongoose document into a plain javascript object. This method accepts a few options. Instead of applying these options on a per-document basis we may declare the options here and have it applied to all of this schemas documents by default.
To have all virtuals show up in your `console.log` output, set the `toObject` option to `{ getters: true }`:
```
var schema = new Schema({ name: String });
schema.path('name').get(function (v) {
return v + ' is my name';
});
schema.set('toObject', { getters: true });
var M = mongoose.model('Person', schema);
var m = new M({ name: 'Max Headroom' });
console.log(m); // { \_id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' }
```
To see all available `toObject` options, read [this](https://mongoosejs.com/docs/api.html#document_Document-toObject).
option: typeKey
---------------
By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a type declaration.
```
// Mongoose interprets this as 'loc is a String'
var schema = new Schema({ loc: { type: String, coordinates: [Number] } });
```
However, for applications like [geoJSON](http://docs.mongodb.org/manual/reference/geojson/), the 'type' property is important. If you want to control which key mongoose uses to find type declarations, set the 'typeKey' schema option.
```
var schema = new Schema({
// Mongoose interpets this as 'loc is an object with 2 keys, type and coordinates'
loc: { type: String, coordinates: [Number] },
// Mongoose interprets this as 'name is a String'
name: { $type: String }
}, { typeKey: '$type' }); // A '$type' key means this object is a type declaration
```
option: validateBeforeSave
--------------------------
By default, documents are automatically validated before they are saved to the database. This is to prevent saving an invalid document. If you want to handle validation manually, and be able to save objects which don't pass validation, you can set `validateBeforeSave` to false.
```
var schema = new Schema({ name: String });
schema.set('validateBeforeSave', false);
schema.path('name').validate(function (value) {
return v != null;
});
var M = mongoose.model('Person', schema);
var m = new M({ name: null });
m.validate(function(err) {
console.log(err); // Will tell you that null is not allowed.
});
m.save(); // Succeeds despite being invalid
```
option: versionKey
------------------
The `versionKey` is a property set on each document when first created by Mongoose. This keys value contains the internal [revision](http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning) of the document. The `versionKey` option is a string that represents the path to use for versioning. The default is `__v`. If this conflicts with your application you can configure as such:
```
const schema = new Schema({ name: 'string' });
const Thing = mongoose.model('Thing', schema);
const thing = new Thing({ name: 'mongoose v3' });
await thing.save(); // { \_\_v: 0, name: 'mongoose v3' }
// customized versionKey
new Schema({..}, { versionKey: '\_somethingElse' })
const Thing = mongoose.model('Thing', schema);
const thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { \_somethingElse: 0, name: 'mongoose v3' }
```
Note that Mongoose versioning is **not** a full [optimistic concurrency](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) solution. Use [mongoose-update-if-current](https://github.com/eoin-obrien/mongoose-update-if-current) for OCC support. Mongoose versioning only operates on arrays:
```
// 2 copies of the same document
const doc1 = await Model.findOne({ _id });
const doc2 = await Model.findOne({ _id });
// Delete first 3 comments from `doc1`
doc1.comments.splice(0, 3);
await doc1.save();
// The below `save()` will throw a VersionError, because you're trying to
// modify the comment at index 1, and the above `splice()` removed that
// comment.
doc2.set('comments.1.body', 'new comment');
await doc2.save();
```
Document versioning can also be disabled by setting the `versionKey` to `false`. *DO NOT disable versioning unless you [know what you are doing](http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning).*
```
new Schema({..}, { versionKey: false });
const Thing = mongoose.model('Thing', schema);
const thing = new Thing({ name: 'no versioning please' });
thing.save(); // { name: 'no versioning please' }
```
Mongoose *only* updates the version key when you use [`save()`](https://mongoosejs.com/docs/api.html#document_Document-save). If you use `update()`, `findOneAndUpdate()`, etc. Mongoose will **not** update the version key. As a workaround, you can use the below middleware.
```
schema.pre('findOneAndUpdate', function() {
const update = this.getUpdate();
if (update.__v != null) {
delete update.__v;
}
const keys = ['$set', '$setOnInsert'];
for (const key of keys) {
if (update[key] != null && update[key].__v != null) {
delete update[key].__v;
if (Object.keys(update[key]).length === 0) {
delete update[key];
}
}
}
update.$inc = update.$inc || {};
update.$inc.__v = 1;
});
```
option: collation
-----------------
Sets a default [collation](https://docs.mongodb.com/manual/reference/collation/) for every query and aggregation. [Here's a beginner-friendly overview of collations](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations).
```
var schema = new Schema({
name: String
}, { collation: { locale: 'en\_US', strength: 1 } });
var MyModel = db.model('MyModel', schema);
MyModel.create([{ name: 'val' }, { name: 'Val' }]).
then(function() {
return MyModel.find({ name: 'val' });
}).
then(function(docs) {
// `docs` will contain both docs, because `strength: 1` means
// MongoDB will ignore case when matching.
});
```
option: skipVersioning
----------------------
`skipVersioning` allows excluding paths from versioning (i.e., the internal revision will not be incremented even if these paths are updated). DO NOT do this unless you know what you're doing. For subdocuments, include this on the parent document using the fully qualified path.
```
new Schema({..}, { skipVersioning: { dontVersionMe: true } });
thing.dontVersionMe.push('hey');
thing.save(); // version is not incremented
```
option: timestamps
------------------
If set `timestamps`, mongoose assigns `createdAt` and `updatedAt` fields to your schema, the type assigned is [Date](https://mongoosejs.com/docs/api.html#schema-date-js).
By default, the name of two fields are `createdAt` and `updatedAt`, customize the field name by setting `timestamps.createdAt` and `timestamps.updatedAt`.
```
const thingSchema = new Schema({..}, { timestamps: { createdAt: 'created\_at' } });
const Thing = mongoose.model('Thing', thingSchema);
const thing = new Thing();
await thing.save(); // `created\_at` & `updatedAt` will be included
// With updates, Mongoose will add `updatedAt` to `$set`
await Thing.updateOne({}, { $set: { name: 'Test' } });
// If you set upsert: true, Mongoose will add `created\_at` to `$setOnInsert` as well
await Thing.findOneAndUpdate({}, { $set: { name: 'Test2' } });
// Mongoose also adds timestamps to bulkWrite() operations
// See https://mongoosejs.com/docs/api.html#model\_Model.bulkWrite
await Thing.bulkWrite([
insertOne: {
document: {
name: 'Jean-Luc Picard',
ship: 'USS Stargazer'
// Mongoose will add `created\_at` and `updatedAt`
}
},
updateOne: {
filter: { name: 'Jean-Luc Picard' },
update: {
$set: {
ship: 'USS Enterprise'
// Mongoose will add `updatedAt`
}
}
}
]);
```
option: useNestedStrict
-----------------------
Write operations like `update()`, `updateOne()`, `updateMany()`, and `findOneAndUpdate()` only check the top-level schema's strict mode setting.
```
var childSchema = new Schema({}, { strict: false });
var parentSchema = new Schema({ child: childSchema }, { strict: 'throw' });
var Parent = mongoose.model('Parent', parentSchema);
Parent.update({}, { 'child.name': 'Luke Skywalker' }, function(error) {
// Error because parentSchema has `strict: throw`, even though
// `childSchema` has `strict: false`
});
var update = { 'child.name': 'Luke Skywalker' };
var opts = { strict: false };
Parent.update({}, update, opts, function(error) {
// This works because passing `strict: false` to `update()` overwrites
// the parent schema.
});
```
If you set `useNestedStrict` to true, mongoose will use the child schema's `strict` option for casting updates.
```
var childSchema = new Schema({}, { strict: false });
var parentSchema = new Schema({ child: childSchema },
{ strict: 'throw', useNestedStrict: true });
var Parent = mongoose.model('Parent', parentSchema);
Parent.update({}, { 'child.name': 'Luke Skywalker' }, function(error) {
// Works!
});
```
option: selectPopulatedPaths
-----------------------------
By default, Mongoose will automatically `select()` any populated paths for you, unless you explicitly exclude them.
```
const bookSchema = new Schema({
title: 'String',
author: { type: 'ObjectId', ref: 'Person' }
});
const Book = mongoose.model('Book', bookSchema);
// By default, Mongoose will add `author` to the below `select()`.
await Book.find().select('title').populate('author');
// In other words, the below query is equivalent to the above
await Book.find().select('title author').populate('author');
```
To opt out of selecting populated fields by default, set `selectPopulatedPaths` to `false` in your schema.
```
const bookSchema = new Schema({
title: 'String',
author: { type: 'ObjectId', ref: 'Person' }
}, { selectPopulatedPaths: false });
const Book = mongoose.model('Book', bookSchema);
// Because `selectPopulatedPaths` is false, the below doc will \*\*not\*\*
// contain an `author` property.
const doc = await Book.findOne().select('title').populate('author');
```
option: storeSubdocValidationError
-----------------------------------
For legacy reasons, when there is a validation error in subpath of a single nested schema, Mongoose will record that there was a validation error in the single nested schema path as well. For example:
```
const childSchema = new Schema({ name: { type: String, required: true } });
const parentSchema = new Schema({ child: childSchema });
const Parent = mongoose.model('Parent', parentSchema);
// Will contain an error for both 'child.name' \_and\_ 'child'
new Parent({ child: {} }).validateSync().errors;
```
Set the `storeSubdocValidationError` to `false` on the child schema to make Mongoose only report the parent error.
```
const childSchema = new Schema({
name: { type: String, required: true }
}, { storeSubdocValidationError: false }); // <-- set on the child schema
const parentSchema = new Schema({ child: childSchema });
const Parent = mongoose.model('Parent', parentSchema);
// Will only contain an error for 'child.name'
new Parent({ child: {} }).validateSync().errors;
```
Pluggable
---------
Schemas are also [pluggable](plugins) which allows us to package up reusable features into plugins that can be shared with the community or just between your projects.
Further Reading
---------------
Here's an [alternative introduction to Mongoose schemas](https://masteringjs.io/tutorials/mongoose/schema).
To get the most out of MongoDB, you need to learn the basics of MongoDB schema design. SQL schema design (third normal form) was designed to [minimize storage costs](https://en.wikipedia.org/wiki/Third_normal_form), whereas MongoDB schema design is about making common queries as fast as possible. The [*6 Rules of Thumb for MongoDB Schema Design* blog series](https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1) is an excellent resource for learning the basic rules for making your queries fast.
Users looking to master MongoDB schema design in Node.js should look into [*The Little MongoDB Schema Design Book*](http://bit.ly/mongodb-schema-design) by Christian Kvalheim, the original author of the [MongoDB Node.js driver](http://npmjs.com/package/mongodb). This book shows you how to implement performant schemas for a laundry list of use cases, including ecommerce, wikis, and appointment bookings.
Next Up
-------
Now that we've covered `Schemas`, let's take a look at [SchemaTypes](schematypes).
| programming_docs |
mongoose Discriminators Discriminators
==============
The `model.discriminator()` function
------------------------------------
Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.
Suppose you wanted to track different types of events in a single collection. Every event will have a timestamp, but events that represent clicked links should have a URL. You can achieve this using the `model.discriminator()` function. This function takes 3 parameters, a model name, a discriminator schema and an optional key (defaults to the model name). It returns a model whose schema is the union of the base schema and the discriminator schema.
```
var options = {discriminatorKey: 'kind'};
var eventSchema = new mongoose.Schema({time: Date}, options);
var Event = mongoose.model('Event', eventSchema);
// ClickedLinkEvent is a special type of Event that has
// a URL.
var ClickedLinkEvent = Event.discriminator('ClickedLink',
new mongoose.Schema({url: String}, options));
// When you create a generic event, it can't have a URL field...
var genericEvent = new Event({time: Date.now(), url: 'google.com'});
assert.ok(!genericEvent.url);
// But a ClickedLinkEvent can
var clickedEvent =
new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
assert.ok(clickedEvent.url);
```
Discriminators save to the Event model's collection
---------------------------------------------------
Suppose you created another discriminator to track events where a new user registered. These `SignedUpEvent` instances will be stored in the same collection as generic events and `ClickedLinkEvent` instances.
```
var event1 = new Event({time: Date.now()});
var event2 = new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
var event3 = new SignedUpEvent({time: Date.now(), user: 'testuser'});
var save = function (doc, callback) {
doc.save(function (error, doc) {
callback(error, doc);
});
};
Promise.all([event1.save(), event2.save(), event3.save()]).
then(() => Event.countDocuments()).
then(count => {
assert.equal(count, 3);
});
```
Discriminator keys
------------------
The way mongoose tells the difference between the different discriminator models is by the 'discriminator key', which is `__t` by default. Mongoose adds a String path called `__t` to your schemas that it uses to track which discriminator this document is an instance of.
```
var event1 = new Event({time: Date.now()});
var event2 = new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
var event3 = new SignedUpEvent({time: Date.now(), user: 'testuser'});
assert.ok(!event1.__t);
assert.equal(event2.__t, 'ClickedLink');
assert.equal(event3.__t, 'SignedUp');
```
Discriminators add the discriminator key to queries
---------------------------------------------------
Discriminator models are special; they attach the discriminator key to queries. In other words, `find()`, `count()`, `aggregate()`, etc. are smart enough to account for discriminators.
```
var event1 = new Event({time: Date.now()});
var event2 = new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
var event3 = new SignedUpEvent({time: Date.now(), user: 'testuser'});
Promise.all([event1.save(), event2.save(), event3.save()]).
then(() => ClickedLinkEvent.find({})).
then(docs => {
assert.equal(docs.length, 1);
assert.equal(docs[0]._id.toString(), event2._id.toString());
assert.equal(docs[0].url, 'google.com');
});
```
Discriminators copy pre and post hooks
--------------------------------------
Discriminators also take their base schema's pre and post middleware. However, you can also attach middleware to the discriminator schema without affecting the base schema.
```
var options = {discriminatorKey: 'kind'};
var eventSchema = new mongoose.Schema({time: Date}, options);
var eventSchemaCalls = 0;
eventSchema.pre('validate', function (next) {
++eventSchemaCalls;
next();
});
var Event = mongoose.model('GenericEvent', eventSchema);
var clickedLinkSchema = new mongoose.Schema({url: String}, options);
var clickedSchemaCalls = 0;
clickedLinkSchema.pre('validate', function (next) {
++clickedSchemaCalls;
next();
});
var ClickedLinkEvent = Event.discriminator('ClickedLinkEvent',
clickedLinkSchema);
var event1 = new ClickedLinkEvent();
event1.validate(function() {
assert.equal(eventSchemaCalls, 1);
assert.equal(clickedSchemaCalls, 1);
var generic = new Event();
generic.validate(function() {
assert.equal(eventSchemaCalls, 2);
assert.equal(clickedSchemaCalls, 1);
});
});
```
Handling custom \_id fields
---------------------------
A discriminator's fields are the union of the base schema's fields and the discriminator schema's fields, and the discriminator schema's fields take precedence. There is one exception: the default `_id` field.
You can work around this by setting the `_id` option to false in the discriminator schema as shown below.
```
var options = {discriminatorKey: 'kind'};
// Base schema has a String `\_id` and a Date `time`...
var eventSchema = new mongoose.Schema({_id: String, time: Date},
options);
var Event = mongoose.model('BaseEvent', eventSchema);
var clickedLinkSchema = new mongoose.Schema({
url: String,
time: String
}, options);
// But the discriminator schema has a String `time`, and an implicitly added
// ObjectId `\_id`.
assert.ok(clickedLinkSchema.path('\_id'));
assert.equal(clickedLinkSchema.path('\_id').instance, 'ObjectID');
var ClickedLinkEvent = Event.discriminator('ChildEventBad',
clickedLinkSchema);
var event1 = new ClickedLinkEvent({ _id: 'custom id', time: '4pm' });
// Woops, clickedLinkSchema overwrites the `time` path, but \*\*not\*\*
// the `\_id` path because that was implicitly added.
assert.ok(typeof event1._id === 'string');
assert.ok(typeof event1.time === 'string');
```
Using discriminators with `Model.create()`
------------------------------------------
When you use `Model.create()`, mongoose will pull the correct type from the discriminator key for you.
```
var Schema = mongoose.Schema;
var shapeSchema = new Schema({
name: String
}, { discriminatorKey: 'kind' });
var Shape = db.model('Shape', shapeSchema);
var Circle = Shape.discriminator('Circle',
new Schema({ radius: Number }));
var Square = Shape.discriminator('Square',
new Schema({ side: Number }));
var shapes = [
{ name: 'Test' },
{ kind: 'Circle', radius: 5 },
{ kind: 'Square', side: 10 }
];
Shape.create(shapes, function(error, shapes) {
assert.ifError(error);
assert.ok(shapes[0] instanceof Shape);
assert.ok(shapes[1] instanceof Circle);
assert.equal(shapes[1].radius, 5);
assert.ok(shapes[2] instanceof Square);
assert.equal(shapes[2].side, 10);
});
```
Embedded discriminators in arrays
---------------------------------
You can also define discriminators on embedded document arrays. Embedded discriminators are different because the different discriminator types are stored in the same document array (within a document) rather than the same collection. In other words, embedded discriminators let you store subdocuments matching different schemas in the same array.
As a general best practice, make sure you declare any hooks on your schemas **before** you use them. You should **not** call `pre()` or `post()` after calling `discriminator()`
```
var eventSchema = new Schema({ message: String },
{ discriminatorKey: 'kind', _id: false });
var batchSchema = new Schema({ events: [eventSchema] });
// `batchSchema.path('events')` gets the mongoose `DocumentArray`
var docArray = batchSchema.path('events');
// The `events` array can contain 2 different types of events, a
// 'clicked' event that requires an element id that was clicked...
var clickedSchema = new Schema({
element: {
type: String,
required: true
}
}, { _id: false });
// Make sure to attach any hooks to `eventSchema` and `clickedSchema`
// \*\*before\*\* calling `discriminator()`.
var Clicked = docArray.discriminator('Clicked', clickedSchema);
// ... and a 'purchased' event that requires the product that was purchased.
var Purchased = docArray.discriminator('Purchased', new Schema({
product: {
type: String,
required: true
}
}, { _id: false }));
var Batch = db.model('EventBatch', batchSchema);
// Create a new batch of events with different kinds
var batch = {
events: [
{ kind: 'Clicked', element: '#hero', message: 'hello' },
{ kind: 'Purchased', product: 'action-figure-1', message: 'world' }
]
};
Batch.create(batch).
then(function(doc) {
assert.equal(doc.events.length, 2);
assert.equal(doc.events[0].element, '#hero');
assert.equal(doc.events[0].message, 'hello');
assert.ok(doc.events[0] instanceof Clicked);
assert.equal(doc.events[1].product, 'action-figure-1');
assert.equal(doc.events[1].message, 'world');
assert.ok(doc.events[1] instanceof Purchased);
doc.events.push({ kind: 'Purchased', product: 'action-figure-2' });
return doc.save();
}).
then(function(doc) {
assert.equal(doc.events.length, 3);
assert.equal(doc.events[2].product, 'action-figure-2');
assert.ok(doc.events[2] instanceof Purchased);
done();
}).
catch(done);
```
Recursive embedded discriminators in arrays
-------------------------------------------
You can also define embedded discriminators on embedded discriminators. In the below example, `sub_events` is an embedded discriminator, and for `sub_event` keys with value 'SubEvent', `sub_events.events` is an embedded discriminator.
```
var singleEventSchema = new Schema({ message: String },
{ discriminatorKey: 'kind', _id: false });
var eventListSchema = new Schema({ events: [singleEventSchema] });
var subEventSchema = new Schema({
sub_events: [singleEventSchema]
}, { _id: false });
var SubEvent = subEventSchema.path('sub\_events').
discriminator('SubEvent', subEventSchema);
eventListSchema.path('events').discriminator('SubEvent', subEventSchema);
var Eventlist = db.model('EventList', eventListSchema);
// Create a new batch of events with different kinds
var list = {
events: [
{ kind: 'SubEvent', sub_events: [{kind:'SubEvent', sub_events:[], message:'test1'}], message: 'hello' },
{ kind: 'SubEvent', sub_events: [{kind:'SubEvent', sub_events:[{kind:'SubEvent', sub_events:[], message:'test3'}], message:'test2'}], message: 'world' }
]
};
Eventlist.create(list).
then(function(doc) {
assert.equal(doc.events.length, 2);
assert.equal(doc.events[0].sub_events[0].message, 'test1');
assert.equal(doc.events[0].message, 'hello');
assert.ok(doc.events[0].sub_events[0] instanceof SubEvent);
assert.equal(doc.events[1].sub_events[0].sub_events[0].message, 'test3');
assert.equal(doc.events[1].message, 'world');
assert.ok(doc.events[1].sub_events[0].sub_events[0] instanceof SubEvent);
doc.events.push({kind:'SubEvent', sub_events:[{kind:'SubEvent', sub_events:[], message:'test4'}], message:'pushed'});
return doc.save();
}).
then(function(doc) {
assert.equal(doc.events.length, 3);
assert.equal(doc.events[2].message, 'pushed');
assert.ok(doc.events[2].sub_events[0] instanceof SubEvent);
done();
}).
catch(done);
```
Single nested discriminators
----------------------------
You can also define discriminators on single nested subdocuments, similar to how you can define discriminators on arrays of subdocuments.
As a general best practice, make sure you declare any hooks on your schemas **before** you use them. You should **not** call `pre()` or `post()` after calling `discriminator()`
```
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shape: shapeSchema });
schema.path('shape').discriminator('Circle', Schema({ radius: String }));
schema.path('shape').discriminator('Square', Schema({ side: Number }));
const MyModel = mongoose.model('ShapeTest', schema);
// If `kind` is set to 'Circle', then `shape` will have a `radius` property
let doc = new MyModel({ shape: { kind: 'Circle', radius: 5 } });
doc.shape.radius; // 5
// If `kind` is set to 'Square', then `shape` will have a `side` property
doc = new MyModel({ shape: { kind: 'Square', side: 10 } });
doc.shape.side; // 10
```
mongoose Transactions in Mongoose Transactions in Mongoose
========================
[Transactions](https://www.mongodb.com/transactions) are new in MongoDB 4.0 and Mongoose 5.2.0. Transactions let you execute multiple operations in isolation and potentially undo all the operations if one of them fails. This guide will get you started using transactions with Mongoose.
Your First Transaction
----------------------
[MongoDB currently only supports transactions on replica sets](https://docs.mongodb.com/manual/replication/#transactions), not standalone servers. To run a [local replica set for development](http://thecodebarbarian.com/introducing-run-rs-zero-config-mongodb-runner.html) on macOS, Linux or Windows, use npm to install [run-rs](https://www.npmjs.com/package/run-rs) globally and run `run-rs --version 4.0.0`. Run-rs will download MongoDB 4.0.0 for you.
To use transactions with Mongoose, you should use Mongoose `>= 5.2.0`. To check your current version of Mongoose, run `npm list | grep "mongoose"` or check the [`mongoose.version` property](http://mongoosejs.com/docs/api.html#mongoose_Mongoose-version).
Transactions are built on [MongoDB sessions](https://docs.mongodb.com/manual/reference/server-sessions/). To start a transaction, you first need to call [`startSession()`](https://mongoosejs.com/docs/api.html#startsession_startSession) and then call the session's `startTransaction()` function. To execute an operation in a transaction, you need to pass the `session` as an option.
```
const Customer = db.model('Customer', new Schema({ name: String }));
let session = null;
return Customer.createCollection().
then(() => db.startSession()).
then(_session => {
session = _session;
// Start a transaction
session.startTransaction();
// This `create()` is part of the transaction because of the `session`
// option.
return Customer.create([{ name: 'Test' }], { session: session });
}).
// Transactions execute in isolation, so unless you pass a `session`
// to `findOne()` you won't see the document until the transaction
// is committed.
then(() => Customer.findOne({ name: 'Test' })).
then(doc => assert.ok(!doc)).
// This `findOne()` will return the doc, because passing the `session`
// means this `findOne()` will run as part of the transaction.
then(() => Customer.findOne({ name: 'Test' }).session(session)).
then(doc => assert.ok(doc)).
// Once the transaction is committed, the write operation becomes
// visible outside of the transaction.
then(() => session.commitTransaction()).
then(() => Customer.findOne({ name: 'Test' })).
then(doc => assert.ok(doc));
```
In the above example, `session` is an instance of the [MongoDB Node.js driver's `ClientSession` class](https://mongodb.github.io/node-mongodb-native/3.2/api/ClientSession.html). Please refer to the [MongoDB driver docs](https://mongodb.github.io/node-mongodb-native/3.2/api/ClientSession.html) for more information on what methods `session` has.
Aborting a Transaction
----------------------
The most important feature of transactions is the ability to roll back *all* operations in the transaction using the [`abortTransaction()` function](https://docs.mongodb.com/manual/reference/method/Session.abortTransaction/).
Think about [modeling a bank account in Mongoose](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html#transactions-with-mongoose). To transfer money from account `A` to account `B`, you would decrement `A`'s balance and increment `B`'s balance. However, if `A` only has a balance of $5 and you try to transfer $10, you want to abort the transaction and undo incrementing `B`'s balance.
```
let session = null;
return Customer.createCollection().
then(() => Customer.startSession()).
then(_session => {
session = _session;
session.startTransaction();
return Customer.create([{ name: 'Test' }], { session: session });
}).
then(() => Customer.create([{ name: 'Test2' }], { session: session })).
then(() => session.abortTransaction()).
then(() => Customer.countDocuments()).
then(count => assert.strictEqual(count, 0));
```
The `withTransaction()` Helper
------------------------------
The previous examples explicitly create a transaction and commits it. In practice, you'll want to use the [`session.withTransaction()` helper](https://mongodb.github.io/node-mongodb-native/3.2/api/ClientSession.html#withTransaction) instead. The `session.withTransaction()` helper handles:
* Creating a transaction
* Committing the transaction if it succeeds
* Aborting the transaction if your operation throws
* Retrying in the event of a [transient transaction error](https://stackoverflow.com/questions/52153538/what-is-a-transienttransactionerror-in-mongoose-or-mongodb).
```
return Customer.createCollection().
then(() => Customer.startSession()).
// The `withTransaction()` function's first parameter is a function
// that returns a promise.
then(session => session.withTransaction(() => {
return Customer.create([{ name: 'Test' }], { session: session });
})).
then(() => Customer.countDocuments()).
then(count => assert.strictEqual(count, 1));
```
For more information on the `ClientSession#withTransaction()` function, please see [the MongoDB Node.js driver docs](https://mongodb.github.io/node-mongodb-native/3.2/api/ClientSession.html#withTransaction).
With Mongoose Documents and `save()`
------------------------------------
If you get a [Mongoose document](documents) from [`findOne()`](https://mongoosejs.com/docs/api.html#findone_findOne) or [`find()`](https://mongoosejs.com/docs/api.html#find_find) using a session, the document will keep a reference to the session and use that session for [`save()`](https://mongoosejs.com/docs/api.html#document_Document-save).
To get/set the session associated with a given document, use [`doc.$session()`](https://mongoosejs.com/docs/api.html#document_Document-%24session).
```
const User = db.model('User', new Schema({ name: String }));
let session = null;
return User.createCollection().
then(() => db.startSession()).
then(_session => {
session = _session;
return User.create({ name: 'foo' });
}).
then(() => {
session.startTransaction();
return User.findOne({ name: 'foo' }).session(session);
}).
then(user => {
// Getter/setter for the session associated with this document.
assert.ok(user.$session());
user.name = 'bar';
// By default, `save()` uses the associated session
return user.save();
}).
then(() => User.findOne({ name: 'bar' })).
// Won't find the doc because `save()` is part of an uncommitted transaction
then(doc => assert.ok(!doc)).
then(() => {
session.commitTransaction();
return User.findOne({ name: 'bar' });
}).
then(doc => assert.ok(doc));
```
With the Aggregation Framework
------------------------------
The `Model.aggregate()` function also supports transactions. Mongoose aggregations have a [`session()` helper](https://mongoosejs.com/docs/api.html#aggregate_Aggregate-session) that sets the [`session` option](https://mongoosejs.com/docs/api.html#aggregate_Aggregate-option). Below is an example of executing an aggregation within a transaction.
```
const Event = db.model('Event', new Schema({ createdAt: Date }), 'Event');
let session = null;
return Event.createCollection().
then(() => db.startSession()).
then(_session => {
session = _session;
session.startTransaction();
return Event.insertMany([
{ createdAt: new Date('2018-06-01') },
{ createdAt: new Date('2018-06-02') },
{ createdAt: new Date('2017-06-01') },
{ createdAt: new Date('2017-05-31') }
], { session: session });
}).
then(() => Event.aggregate([
{
$group: {
_id: {
month: { $month: '$createdAt' },
year: { $year: '$createdAt' }
},
count: { $sum: 1 }
}
},
{ $sort: { count: -1, '\_id.year': -1, '\_id.month': -1 } }
]).session(session)).
then(res => {
assert.deepEqual(res, [
{ _id: { month: 6, year: 2018 }, count: 2 },
{ _id: { month: 6, year: 2017 }, count: 1 },
{ _id: { month: 5, year: 2017 }, count: 1 }
]);
session.commitTransaction();
});
```
| programming_docs |
mongoose Promises Promises
========
Built-in Promises
-----------------
Mongoose async operations, like `.save()` and queries, return thenables. This means that you can do things like `MyModel.findOne({}).then()` and `await MyModel.findOne({}).exec()` if you're using [async/await](http://thecodebarbarian.com/80-20-guide-to-async-await-in-node.js.html).
You can find the return type of specific operations [in the api docs](https://mongoosejs.com/docs/api.html)
```
var gnr = new Band({
name: "Guns N' Roses",
members: ['Axl', 'Slash']
});
var promise = gnr.save();
assert.ok(promise instanceof Promise);
promise.then(function (doc) {
assert.equal(doc.name, "Guns N' Roses");
});
```
Queries are not promises
------------------------
[Mongoose queries](http://mongoosejs.com/docs/queries.html) are **not** promises. They have a `.then()` function for [co](https://www.npmjs.com/package/co) and async/await as a convenience. If you need a fully-fledged promise, use the `.exec()` function.
```
var query = Band.findOne({name: "Guns N' Roses"});
assert.ok(!(query instanceof Promise));
// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (doc) {
// use doc
});
// `.exec()` gives you a fully-fledged promise
var promise = query.exec();
assert.ok(promise instanceof Promise);
promise.then(function (doc) {
// use doc
});
```
Queries are thenable
--------------------
Although queries are not promises, queries are [thenables](https://promisesaplus.com/#terminology). That means they have a `.then()` function, so you can use queries as promises with either promise chaining or [async await](https://asyncawait.net)
```
Band.findOne({name: "Guns N' Roses"}).then(function(doc) {
// use doc
});
```
Plugging in your own Promises Library
-------------------------------------
If you're an advanced user, you may want to plug in your own promise library like [bluebird](https://www.npmjs.com/package/bluebird). Just set `mongoose.Promise` to your favorite ES6-style promise constructor and mongoose will use it.
```
var query = Band.findOne({name: "Guns N' Roses"});
// Use bluebird
mongoose.Promise = require('bluebird');
assert.equal(query.exec().constructor, require('bluebird'));
// Use q. Note that you \*\*must\*\* use `require('q').Promise`.
mongoose.Promise = require('q').Promise;
assert.ok(query.exec() instanceof require('q').makePromise);
```
*Want to learn how to check whether your favorite npm modules work with async/await without cobbling together contradictory answers from Google and Stack Overflow? Chapter 4 of Mastering Async/Await explains the basic principles for determining whether frameworks like React and Mongoose support async/await. [Get your copy!](http://asyncawait.net/?utm_source=mongoosejs&utm_campaign=promises)*
mongoose Documents Documents
=========
Mongoose [documents](https://mongoosejs.com/docs/api.html#document-js) represent a one-to-one mapping to documents as stored in MongoDB. Each document is an instance of its [Model](models).
Documents vs Models
-------------------
[Document](https://mongoosejs.com/docs/api.html#Document) and [Model](https://mongoosejs.com/docs/api.html#Model) are distinct classes in Mongoose. The Model class is a subclass of the Document class. When you use the [Model constructor](https://mongoosejs.com/docs/api.html#Model), you create a new document.
```
const MyModel = mongoose.model('Test', new Schema({ name: String }));
const doc = new MyModel();
doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true
```
In Mongoose, a "document" generally means an instance of a model. You should not have to create an instance of the Document class without going through a model.
Retrieving
----------
When you load documents from MongoDB using model functions like [`findOne()`](https://mongoosejs.com/docs/api.html#model_Model.findOne), you get a Mongoose document back.
```
const doc = await MyModel.findOne();
doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true
```
Updating
--------
Mongoose documents track changes. You can modify a document using vanilla JavaScript assignments and Mongoose will convert it into [MongoDB update operators](https://docs.mongodb.com/manual/reference/operator/update/).
```
doc.name = 'foo';
// Mongoose sends a `updateOne({ \_id: doc.\_id }, { $set: { name: 'foo' } })`
// to MongoDB.
await doc.save();
```
If the document with the corresponding `_id` is not found, Mongoose will report a `DocumentNotFoundError`:
```
const doc = await MyModel.findOne();
// Delete the document so Mongoose won't be able to save changes
await MyModel.deleteOne({ _id: doc._id });
doc.name = 'foo';
await doc.save(); // Throws DocumentNotFoundError
```
The [`save()`](https://mongoosejs.com/docs/api.html#model_Model-save) function is generally the right way to update a document with Mongoose. With `save()`, you get full <validation> and <middleware>.
For cases when `save()` isn't flexible enough, Mongoose lets you create your own [MongoDB updates](https://docs.mongodb.com/manual/reference/operator/update/) with casting, [middleware](middleware#notes), and [limited validation](validation#update-validators).
```
// Update all documents in the `mymodels` collection
await MyModel.updateMany({}, { $set: { name: 'foo' } });
```
*Note that `update()`, `updateMany()`, `findOneAndUpdate()`, etc. do *not* execute `save()` middleware. If you need save middleware and full validation, first query for the document and then `save()` it.*
Validating
----------
Documents are casted validated before they are saved. Mongoose first casts values to the specified type and then validates them. Internally, Mongoose calls the document's [`validate()` method](https://mongoosejs.com/docs/api.html#document_Document-validate) before saving.
```
const schema = new Schema({ name: String, age: { type: Number, min: 0 } });
const Person = mongoose.model('Person', schema);
let p = new Person({ name: 'foo', age: 'bar' });
// Cast to Number failed for value "bar" at path "age"
await p.validate();
let p2 = new Person({ name: 'foo', age: -1 });
// Path `age` (-1) is less than minimum allowed value (0).
await p2.validate();
```
Mongoose also supports limited validation on updates using the [`runValidators` option](validation#update-validators). Mongoose casts parameters to query functions like `findOne()`, `updateOne()` by default. However, Mongoose does *not* run validation on query function parameters by default. You need to set `runValidators: true` for Mongoose to validate.
```
// Cast to number failed for value "bar" at path "age"
await Person.updateOne({}, { age: 'bar' });
// Path `age` (-1) is less than minimum allowed value (0).
await Person.updateOne({}, { age: -1 }, { runValidators: true });
```
Read the <validation> guide for more details.
Overwriting
-----------
There are 2 different ways to overwrite a document (replacing all keys in the document). One way is to use the [`Document#overwrite()` function](api/document#document_Document-overwrite) followed by `save()`.
```
const doc = await Person.findOne({ _id });
// Sets `name` and unsets all other properties
doc.overwrite({ name: 'Jean-Luc Picard' });
await doc.save();
```
The other way is to use [`Model.replaceOne()`](api/model#model_Model.replaceOne).
```
// Sets `name` and unsets all other properties
await Person.replaceOne({ _id }, { name: 'Jean-Luc Picard' });
```
Next Up
-------
Now that we've covered Documents, let's take a look at [Subdocuments](subdocs).
mongoose Validation Validation
==========
Validation
----------
Before we get into the specifics of validation syntax, please keep the following rules in mind:
* Validation is defined in the [SchemaType](schematypes)
* Validation is <middleware>. Mongoose registers validation as a `pre('save')` hook on every schema by default.
* You can manually run validation using `doc.validate(callback)` or `doc.validateSync()`
* Validators are not run on undefined values. The only exception is the [`required` validator](https://mongoosejs.com/docs/api.html#schematype_SchemaType-required).
* Validation is asynchronously recursive; when you call [Model#save](https://mongoosejs.com/docs/api.html#model_Model-save), sub-document validation is executed as well. If an error occurs, your [Model#save](https://mongoosejs.com/docs/api.html#model_Model-save) callback receives it
* Validation is customizable
```
var schema = new Schema({
name: {
type: String,
required: true
}
});
var Cat = db.model('Cat', schema);
// This cat has no name :(
var cat = new Cat();
cat.save(function(error) {
assert.equal(error.errors['name'].message,
'Path `name` is required.');
error = cat.validateSync();
assert.equal(error.errors['name'].message,
'Path `name` is required.');
});
```
Built-in Validators
-------------------
Mongoose has several built-in validators.
* All [SchemaTypes](schematypes) have the built-in [required](https://mongoosejs.com/docs/api.html#schematype_SchemaType-required) validator. The required validator uses the [SchemaType's `checkRequired()` function](https://mongoosejs.com/docs/api.html#schematype_SchemaType-checkRequired) to determine if the value satisfies the required validator.
* [Numbers](https://mongoosejs.com/docs/api.html#schema-number-js) have [`min` and `max`](schematypes#number-validators) validators.
* [Strings](https://mongoosejs.com/docs/api.html#schema-string-js) have [`enum`, `match`, `minlength`, and `maxlength`](schematypes#string-validators) validators.
Each of the validator links above provide more information about how to enable them and customize their error messages.
```
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() {
return this.bacon > 3;
}
}
});
var Breakfast = db.model('Breakfast', breakfastSchema);
var badBreakfast = new Breakfast({
eggs: 2,
bacon: 0,
drink: 'Milk'
});
var error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
'Too few eggs');
assert.ok(!error.errors['bacon']);
assert.equal(error.errors['drink'].message,
'`Milk` is not a valid enum value for path `drink`.');
badBreakfast.bacon = 5;
badBreakfast.drink = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['drink'].message, 'Path `drink` is required.');
badBreakfast.bacon = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['bacon'].message, 'Why no bacon?');
```
The `unique` Option is Not a Validator
--------------------------------------
A common gotcha for beginners is that the `unique` option for schemas is *not* a validator. It's a convenient helper for building [MongoDB unique indexes](https://docs.mongodb.com/manual/core/index-unique/). See the [FAQ](https://mongoosejs.com/docs/faq.html) for more information.
```
var uniqueUsernameSchema = new Schema({
username: {
type: String,
unique: true
}
});
var U1 = db.model('U1', uniqueUsernameSchema);
var U2 = db.model('U2', uniqueUsernameSchema);
var dup = [{ username: 'Val' }, { username: 'Val' }];
U1.create(dup, function(error) {
// Race condition! This may save successfully, depending on whether
// MongoDB built the index before writing the 2 docs.
});
// Need to wait for the index to finish building before saving,
// otherwise unique constraints may be violated.
U2.once('index', function(error) {
assert.ifError(error);
U2.create(dup, function(error) {
// Will error, but will \*not\* be a mongoose validation error, it will be
// a duplicate key error.
assert.ok(error);
assert.ok(!error.errors);
assert.ok(error.message.indexOf('duplicate key error') !== -1);
});
});
// There's also a promise-based equivalent to the event emitter API.
// The `init()` function is idempotent and returns a promise that
// will resolve once indexes are done building;
U2.init().then(function() {
U2.create(dup, function(error) {
// Will error, but will \*not\* be a mongoose validation error, it will be
// a duplicate key error.
assert.ok(error);
assert.ok(!error.errors);
assert.ok(error.message.indexOf('duplicate key error') !== -1);
});
});
```
Custom Validators
-----------------
If the built-in validators aren't enough, you can define custom validators to suit your needs.
Custom validation is declared by passing a validation function. You can find detailed instructions on how to do this in the [`SchemaType#validate()` API docs](https://mongoosejs.com/docs/api.html#schematype_SchemaType-validate).
```
var userSchema = new Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: props => `${props.value} is not a valid phone number!`
},
required: [true, 'User phone number required']
}
});
var User = db.model('user', userSchema);
var user = new User();
var error;
user.phone = '555.0123';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
'555.0123 is not a valid phone number!');
user.phone = '';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
'User phone number required');
user.phone = '201-555-0123';
// Validation succeeds! Phone number is defined
// and fits `DDD-DDD-DDDD`
error = user.validateSync();
assert.equal(error, null);
```
Async Custom Validators
-----------------------
Custom validators can also be asynchronous. If your validator function returns a promise (like an `async` function), mongoose will wait for that promise to settle. If the returned promise rejects, or fulfills with the value `false`, Mongoose will consider that a validation error.
```
const userSchema = new Schema({
name: {
type: String,
// You can also make a validator async by returning a promise.
validate: () => Promise.reject(new Error('Oops!'))
},
email: {
type: String,
// There are two ways for an promise-based async validator to fail:
// 1) If the promise rejects, Mongoose assumes the validator failed with the given error.
// 2) If the promise resolves to `false`, Mongoose assumes the validator failed and creates an error with the given `message`.
validate: {
validator: () => Promise.resolve(false),
message: 'Email validation failed'
}
}
});
const User = db.model('User', userSchema);
const user = new User();
user.email = '[email protected]';
user.name = 'test';
user.validate().catch(error => {
assert.ok(error);
assert.equal(error.errors['name'].message, 'Oops!');
assert.equal(error.errors['email'].message, 'Email validation failed');
});
```
Validation Errors
-----------------
Errors returned after failed validation contain an `errors` object whose values are `ValidatorError` objects. Each [ValidatorError](https://mongoosejs.com/docs/api.html#error-validation-js) has `kind`, `path`, `value`, and `message` properties. A ValidatorError also may have a `reason` property. If an error was thrown in the validator, this property will contain the error that was thrown.
```
var toySchema = new Schema({
color: String,
name: String
});
var validator = function(value) {
return /red|white|gold/i.test(value);
};
toySchema.path('color').validate(validator,
'Color `{VALUE}` not valid', 'Invalid color');
toySchema.path('name').validate(function(v) {
if (v !== 'Turbo Man') {
throw new Error('Need to get a Turbo Man for Christmas');
}
return true;
}, 'Name `{VALUE}` is not valid');
var Toy = db.model('Toy', toySchema);
var toy = new Toy({ color: 'Green', name: 'Power Ranger' });
toy.save(function (err) {
// `err` is a ValidationError object
// `err.errors.color` is a ValidatorError object
assert.equal(err.errors.color.message, 'Color `Green` not valid');
assert.equal(err.errors.color.kind, 'Invalid color');
assert.equal(err.errors.color.path, 'color');
assert.equal(err.errors.color.value, 'Green');
// This is new in mongoose 5. If your validator throws an exception,
// mongoose will use that message. If your validator returns `false`,
// mongoose will use the 'Name `Power Ranger` is not valid' message.
assert.equal(err.errors.name.message,
'Need to get a Turbo Man for Christmas');
assert.equal(err.errors.name.value, 'Power Ranger');
// If your validator threw an error, the `reason` property will contain
// the original error thrown, including the original stack trace.
assert.equal(err.errors.name.reason.message,
'Need to get a Turbo Man for Christmas');
assert.equal(err.name, 'ValidationError');
});
```
Cast Errors
-----------
Before running validators, Mongoose attempts to coerce values to the correct type. This process is called *casting* the document. If casting fails for a given path, the `error.errors` object will contain a `CastError` object.
Casting runs before validation, and validation does not run if casting fails. That means your custom validators may assume `v` is `null`, `undefined`, or an instance of the type specified in your schema.
```
const vehicleSchema = new mongoose.Schema({
numWheels: { type: Number, max: 18 }
});
const Vehicle = db.model('Vehicle', vehicleSchema);
const doc = new Vehicle({ numWheels: 'not a number' });
const err = doc.validateSync();
err.errors['numWheels'].name; // 'CastError'
// 'Cast to Number failed for value "not a number" at path "numWheels"'
err.errors['numWheels'].message;
```
Required Validators On Nested Objects
-------------------------------------
Defining validators on nested objects in mongoose is tricky, because nested objects are not fully fledged paths.
```
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
assert.throws(function() {
// This throws an error, because 'name' isn't a full fledged path
personSchema.path('name').required(true);
}, /Cannot.\*'required'/);
// To make a nested object required, use a single nested schema
var nameSchema = new Schema({
first: String,
last: String
});
personSchema = new Schema({
name: {
type: nameSchema,
required: true
}
});
var Person = db.model('Person', personSchema);
var person = new Person();
var error = person.validateSync();
assert.ok(error.errors['name']);
```
Update Validators
-----------------
In the above examples, you learned about document validation. Mongoose also supports validation for [`update()`](https://mongoosejs.com/docs/api.html#query_Query-update), [`updateOne()`](https://mongoosejs.com/docs/api.html#query_Query-updateOne), [`updateMany()`](https://mongoosejs.com/docs/api.html#query_Query-updateMany), and [`findOneAndUpdate()`](https://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate) operations. Update validators are off by default - you need to specify the `runValidators` option.
To turn on update validators, set the `runValidators` option for `update()`, `updateOne()`, `updateMany()`, or `findOneAndUpdate()`. Be careful: update validators are off by default because they have several caveats.
```
var toySchema = new Schema({
color: String,
name: String
});
var Toy = db.model('Toys', toySchema);
Toy.schema.path('color').validate(function (value) {
return /red|green|blue/i.test(value);
}, 'Invalid color');
var opts = { runValidators: true };
Toy.updateOne({}, { color: 'not a color' }, opts, function (err) {
assert.equal(err.errors.color.message,
'Invalid color');
});
```
Update Validators and `this`
----------------------------
There are a couple of key differences between update validators and document validators. In the color validation function above, `this` refers to the document being validated when using document validation. However, when running update validators, the document being updated may not be in the server's memory, so by default the value of `this` is not defined.
```
var toySchema = new Schema({
color: String,
name: String
});
toySchema.path('color').validate(function(value) {
// When running in `validate()` or `validateSync()`, the
// validator can access the document using `this`.
// Does \*\*not\*\* work with update validators.
if (this.name.toLowerCase().indexOf('red') !== -1) {
return value !== 'red';
}
return true;
});
var Toy = db.model('ActionFigure', toySchema);
var toy = new Toy({ color: 'red', name: 'Red Power Ranger' });
var error = toy.validateSync();
assert.ok(error.errors['color']);
var update = { color: 'red', name: 'Red Power Ranger' };
var opts = { runValidators: true };
Toy.updateOne({}, update, opts, function(error) {
// The update validator throws an error:
// "TypeError: Cannot read property 'toLowerCase' of undefined",
// because `this` is \*\*not\*\* the document being updated when using
// update validators
assert.ok(error);
});
```
The `context` option
--------------------
The `context` option lets you set the value of `this` in update validators to the underlying query.
```
toySchema.path('color').validate(function(value) {
// When running update validators with the `context` option set to
// 'query', `this` refers to the query object.
if (this.getUpdate().$set.name.toLowerCase().indexOf('red') !== -1) {
return value === 'red';
}
return true;
});
var Toy = db.model('Figure', toySchema);
var update = { color: 'blue', name: 'Red Power Ranger' };
// Note the context option
var opts = { runValidators: true, context: 'query' };
Toy.updateOne({}, update, opts, function(error) {
assert.ok(error.errors['color']);
});
```
Update Validators Only Run On Updated Paths
-------------------------------------------
The other key difference that update validators only run on the paths specified in the update. For instance, in the below example, because 'name' is not specified in the update operation, update validation will succeed.
When using update validators, `required` validators **only** fail when you try to explicitly `$unset` the key.
```
var kittenSchema = new Schema({
name: { type: String, required: true },
age: Number
});
var Kitten = db.model('Kitten', kittenSchema);
var update = { color: 'blue' };
var opts = { runValidators: true };
Kitten.updateOne({}, update, opts, function(err) {
// Operation succeeds despite the fact that 'name' is not specified
});
var unset = { $unset: { name: 1 } };
Kitten.updateOne({}, unset, opts, function(err) {
// Operation fails because 'name' is required
assert.ok(err);
assert.ok(err.errors['name']);
});
```
Update Validators Only Run For Some Operations
----------------------------------------------
One final detail worth noting: update validators **only** run on the following update operators:
* `$set`
* `$unset`
* `$push` (>= 4.8.0)
* `$addToSet` (>= 4.8.0)
* `$pull` (>= 4.12.0)
* `$pullAll` (>= 4.12.0)
For instance, the below update will succeed, regardless of the value of `number`, because update validators ignore `$inc`.
Also, `$push`, `$addToSet`, `$pull`, and `$pullAll` validation does **not** run any validation on the array itself, only individual elements of the array.
```
var testSchema = new Schema({
number: { type: Number, max: 0 },
arr: [{ message: { type: String, maxlength: 10 } }]
});
// Update validators won't check this, so you can still `$push` 2 elements
// onto the array, so long as they don't have a `message` that's too long.
testSchema.path('arr').validate(function(v) {
return v.length < 2;
});
var Test = db.model('Test', testSchema);
var update = { $inc: { number: 1 } };
var opts = { runValidators: true };
Test.updateOne({}, update, opts, function(error) {
// There will never be a validation error here
update = { $push: [{ message: 'hello' }, { message: 'world' }] };
Test.updateOne({}, update, opts, function(error) {
// This will never error either even though the array will have at
// least 2 elements.
});
});
```
On $push and $addToSet
----------------------
New in 4.8.0: update validators also run on `$push` and `$addToSet`
```
var testSchema = new Schema({
numbers: [{ type: Number, max: 0 }],
docs: [{
name: { type: String, required: true }
}]
});
var Test = db.model('TestPush', testSchema);
var update = {
$push: {
numbers: 1,
docs: { name: null }
}
};
var opts = { runValidators: true };
Test.updateOne({}, update, opts, function(error) {
assert.ok(error.errors['numbers']);
assert.ok(error.errors['docs']);
});
```
| programming_docs |
mongoose Creating a Basic Custom Schema Type Creating a Basic Custom Schema Type
===================================
*New in Mongoose 4.4.0:* Mongoose supports custom types. Before you reach for a custom type, however, know that a custom type is overkill for most use cases. You can do most basic tasks with [custom getters/setters](http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html), [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), and [single embedded docs](http://mongoosejs.com/docs/subdocs.html#single-embedded).
Let's take a look at an example of a basic schema type: a 1-byte integer. To create a new schema type, you need to inherit from `mongoose.SchemaType` and add the corresponding property to `mongoose.Schema.Types`. The one method you need to implement is the `cast()` method.
```
function Int8(key, options) {
mongoose.SchemaType.call(this, key, options, 'Int8');
}
Int8.prototype = Object.create(mongoose.SchemaType.prototype);
// `cast()` takes a parameter that can be anything. You need to
// validate the provided `val` and throw a `CastError` if you
// can't convert it.
Int8.prototype.cast = function(val) {
var _val = Number(val);
if (isNaN(_val)) {
throw new Error('Int8: ' + val + ' is not a number');
}
_val = Math.round(_val);
if (_val < -0x80 || _val > 0x7F) {
throw new Error('Int8: ' + val +
' is outside of the range of valid 8-bit ints');
}
return _val;
};
// Don't forget to add `Int8` to the type registry
mongoose.Schema.Types.Int8 = Int8;
var testSchema = new Schema({ test: Int8 });
var Test = mongoose.model('CustomTypeExample', testSchema);
var t = new Test();
t.test = 'abc';
assert.ok(t.validateSync());
assert.equal(t.validateSync().errors['test'].name, 'CastError');
assert.equal(t.validateSync().errors['test'].message,
'Cast to Int8 failed for value "abc" at path "test"');
assert.equal(t.validateSync().errors['test'].reason.message,
'Int8: abc is not a number');
```
mongoose Middleware Middleware
==========
Middleware (also called pre and post *hooks*) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing <plugins>.
Types of Middleware
-------------------
Mongoose has 4 types of middleware: document middleware, model middleware, aggregate middleware, and query middleware. Document middleware is supported for the following document functions. In document middleware functions, `this` refers to the document.
* [validate](api/document#document_Document-validate)
* [save](api/model#model_Model-save)
* [remove](api/model#model_Model-remove)
* [updateOne](api/document#document_Document-updateOne)
* [deleteOne](api/model#model_Model-deleteOne)
* [init](api/document#document_Document-init) (note: init hooks are [synchronous](#synchronous))
Query middleware is supported for the following Model and Query functions. In query middleware functions, `this` refers to the query.
* [count](https://mongoosejs.com/docs/api.html#query_Query-count)
* [deleteMany](https://mongoosejs.com/docs/api.html#query_Query-deleteMany)
* [deleteOne](https://mongoosejs.com/docs/api.html#query_Query-deleteOne)
* [find](https://mongoosejs.com/docs/api.html#query_Query-find)
* [findOne](https://mongoosejs.com/docs/api.html#query_Query-findOne)
* [findOneAndDelete](https://mongoosejs.com/docs/api.html#query_Query-findOneAndDelete)
* [findOneAndRemove](https://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove)
* [findOneAndUpdate](https://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate)
* [remove](https://mongoosejs.com/docs/api.html#model_Model.remove)
* [update](https://mongoosejs.com/docs/api.html#query_Query-update)
* [updateOne](https://mongoosejs.com/docs/api.html#query_Query-updateOne)
* [updateMany](https://mongoosejs.com/docs/api.html#query_Query-updateMany)
Aggregate middleware is for `MyModel.aggregate()`. Aggregate middleware executes when you call `exec()` on an aggregate object. In aggregate middleware, `this` refers to the [aggregation object](https://mongoosejs.com/docs/api.html#model_Model.aggregate).
* [aggregate](https://mongoosejs.com/docs/api.html#model_Model.aggregate)
Model middleware is supported for the following model functions. In model middleware functions, `this` refers to the model.
* [insertMany](https://mongoosejs.com/docs/api.html#model_Model.insertMany)
All middleware types support pre and post hooks. How pre and post hooks work is described in more detail below.
**Note:** If you specify `schema.pre('remove')`, Mongoose will register this middleware for [`doc.remove()`](https://mongoosejs.com/docs/api.html#model_Model-remove) by default. If you want to your middleware to run on [`Query.remove()`](https://mongoosejs.com/docs/api.html#query_Query-remove) use [`schema.pre('remove', { query: true, document: false }, fn)`](https://mongoosejs.com/docs/api.html#schema_Schema-pre).
**Note:** The [`create()`](https://mongoosejs.com/docs/api.html#model_Model.create) function fires `save()` hooks.
Pre
---
Pre middleware functions are executed one after another, when each middleware calls `next`.
```
var schema = new Schema(..);
schema.pre('save', function(next) {
// do stuff
next();
});
```
In [mongoose 5.x](http://thecodebarbarian.com/introducing-mongoose-5.html#promises-and-async-await-with-middleware), instead of calling `next()` manually, you can use a function that returns a promise. In particular, you can use [`async/await`](http://thecodebarbarian.com/common-async-await-design-patterns-in-node.js.html).
```
schema.pre('save', function() {
return doStuff().
then(() => doMoreStuff());
});
// Or, in Node.js >= 7.6.0:
schema.pre('save', async function() {
await doStuff();
await doMoreStuff();
});
```
If you use `next()`, the `next()` call does **not** stop the rest of the code in your middleware function from executing. Use [the early `return` pattern](https://www.bennadel.com/blog/2323-use-a-return-statement-when-invoking-callbacks-especially-in-a-guard-statement.htm) to prevent the rest of your middleware function from running when you call `next()`.
```
var schema = new Schema(..);
schema.pre('save', function(next) {
if (foo()) {
console.log('calling next!');
// `return next();` will make sure the rest of this function doesn't run
/\*return\*/ next();
}
// Unless you comment out the `return` above, 'after next' will print
console.log('after next');
});
```
#### Use Cases
Middleware are useful for atomizing model logic. Here are some other ideas:
* complex validation
* removing dependent documents (removing a user removes all his blogposts)
* asynchronous defaults
* asynchronous tasks that a certain action triggers
#### Errors in Pre Hooks
If any pre hook errors out, mongoose will not execute subsequent middleware or the hooked function. Mongoose will instead pass an error to the callback and/or reject the returned promise. There are several ways to report an error in middleware:
```
schema.pre('save', function(next) {
const err = new Error('something went wrong');
// If you call `next()` with an argument, that argument is assumed to be
// an error.
next(err);
});
schema.pre('save', function() {
// You can also return a promise that rejects
return new Promise((resolve, reject) => {
reject(new Error('something went wrong'));
});
});
schema.pre('save', function() {
// You can also throw a synchronous error
throw new Error('something went wrong');
});
schema.pre('save', async function() {
await Promise.resolve();
// You can also throw an error in an `async` function
throw new Error('something went wrong');
});
// later...
// Changes will not be persisted to MongoDB because a pre hook errored out
myDoc.save(function(err) {
console.log(err.message); // something went wrong
});
```
Calling `next()` multiple times is a no-op. If you call `next()` with an error `err1` and then throw an error `err2`, mongoose will report `err1`.
Post middleware
---------------
[post](https://mongoosejs.com/docs/api.html#schema_Schema-post) middleware are executed *after* the hooked method and all of its `pre` middleware have completed.
```
schema.post('init', function(doc) {
console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
console.log('%s has been saved', doc._id);
});
schema.post('remove', function(doc) {
console.log('%s has been removed', doc._id);
});
```
Asynchronous Post Hooks
-----------------------
If your post hook function takes at least 2 parameters, mongoose will assume the second parameter is a `next()` function that you will call to trigger the next middleware in the sequence.
```
// Takes 2 parameters: this is an asynchronous post hook
schema.post('save', function(doc, next) {
setTimeout(function() {
console.log('post1');
// Kick off the second post hook
next();
}, 10);
});
// Will not execute until the first middleware calls `next()`
schema.post('save', function(doc, next) {
console.log('post2');
next();
});
```
Define Middleware Before Compiling Models
-----------------------------------------
Calling `pre()` or `post()` after [compiling a model](models#compiling) does **not** work in Mongoose in general. For example, the below `pre('save')` middleware will not fire.
```
const schema = new mongoose.Schema({ name: String });
// Compile a model from the schema
const User = mongoose.model('User', schema);
// Mongoose will \*\*not\*\* call the middleware function, because
// this middleware was defined after the model was compiled
schema.pre('save', () => console.log('Hello from pre save'));
new User({ name: 'test' }).save();
```
This means that you must add all middleware and <plugins> **before** calling [`mongoose.model()](api/mongoose#mongoose_Mongoose-model). The below script will print out "Hello from pre save":
```
const schema = new mongoose.Schema({ name: String });
// Mongoose will call this middleware function, because this script adds
// the middleware to the schema before compiling the model.
schema.pre('save', () => console.log('Hello from pre save'));
// Compile a model from the schema
const User = mongoose.model('User', schema);
new User({ name: 'test' }).save();
```
As a consequence, be careful about exporting Mongoose models from the same file that you define your schema. If you choose to use this pattern, you must define [global plugins](api/mongoose#mongoose_Mongoose-plugin) **before** calling `require()` on your model file.
```
const schema = new mongoose.Schema({ name: String });
// Once you `require()` this file, you can no longer add any middleware
// to this schema.
module.exports = mongoose.model('User', schema);
```
Save/Validate Hooks
-------------------
The `save()` function triggers `validate()` hooks, because mongoose has a built-in `pre('save')` hook that calls `validate()`. This means that all `pre('validate')` and `post('validate')` hooks get called **before** any `pre('save')` hooks.
```
schema.pre('validate', function() {
console.log('this gets printed first');
});
schema.post('validate', function() {
console.log('this gets printed second');
});
schema.pre('save', function() {
console.log('this gets printed third');
});
schema.post('save', function() {
console.log('this gets printed fourth');
});
```
Naming Conflicts
----------------
Mongoose has both query and document hooks for `remove()`.
```
schema.pre('remove', function() { console.log('Removing!'); });
// Prints "Removing!"
doc.remove();
// Does \*\*not\*\* print "Removing!". Query middleware for `remove` is not
// executed by default.
Model.remove();
```
You can pass options to [`Schema.pre()`](https://mongoosejs.com/docs/api.html#schema_Schema-pre) and [`Schema.post()`](https://mongoosejs.com/docs/api.html#schema_Schema-post) to switch whether Mongoose calls your `remove()` hook for [`Document.remove()`](https://mongoosejs.com/docs/api.html#model_Model-remove) or [`Model.remove()`](https://mongoosejs.com/docs/api.html#model_Model.remove):
```
// Only document middleware
schema.pre('remove', { document: true }, function() {
console.log('Removing doc!');
});
// Only query middleware. This will get called when you do `Model.remove()`
// but not `doc.remove()`.
schema.pre('remove', { query: true }, function() {
console.log('Removing!');
});
```
Notes on findAndUpdate() and Query Middleware
---------------------------------------------
Pre and post `save()` hooks are **not** executed on `update()`, `findOneAndUpdate()`, etc. You can see a more detailed discussion why in [this GitHub issue](http://github.com/Automattic/mongoose/issues/964). Mongoose 4.0 introduced distinct hooks for these functions.
```
schema.pre('find', function() {
console.log(this instanceof mongoose.Query); // true
this.start = Date.now();
});
schema.post('find', function(result) {
console.log(this instanceof mongoose.Query); // true
// prints returned documents
console.log('find() returned ' + JSON.stringify(result));
// prints number of milliseconds the query took
console.log('find() took ' + (Date.now() - this.start) + ' millis');
});
```
Query middleware differs from document middleware in a subtle but important way: in document middleware, `this` refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so `this` refers to the **query** object rather than the document being updated.
For instance, if you wanted to add an `updatedAt` timestamp to every `updateOne()` call, you would use the following pre hook.
```
schema.pre('updateOne', function() {
this.set({ updatedAt: new Date() });
});
```
You **cannot** access the document being updated in `pre('updateOne')` or `pre('findOneAndUpdate')` middleware. If you need to access the document that will be updated, you need to execute an explicit query for the document.
```
schema.pre('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery());
console.log(docToUpdate); // The document that `findOneAndUpdate()` will modify
});
```
Error Handling Middleware
-------------------------
*New in 4.5.0*
Middleware execution normally stops the first time a piece of middleware calls `next()` with an error. However, there is a special kind of post middleware called "error handling middleware" that executes specifically when an error occurs. Error handling middleware is useful for reporting errors and making error messages more readable.
Error handling middleware is defined as middleware that takes one extra parameter: the 'error' that occurred as the first parameter to the function. Error handling middleware can then transform the error however you want.
```
var schema = new Schema({
name: {
type: String,
// Will trigger a MongoError with code 11000 when
// you save a duplicate
unique: true
}
});
// Handler \*\*must\*\* take 3 parameters: the error that occurred, the document
// in question, and the `next()` function
schema.post('save', function(error, doc, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('There was a duplicate key error'));
} else {
next();
}
});
// Will trigger the `post('save')` error handler
Person.create([{ name: 'Axl Rose' }, { name: 'Axl Rose' }]);
```
Error handling middleware also works with query middleware. You can also define a post `update()` hook that will catch MongoDB duplicate key errors.
```
// The same E11000 error can occur when you call `update()`
// This function \*\*must\*\* take 3 parameters. If you use the
// `passRawResult` function, this function \*\*must\*\* take 4
// parameters
schema.post('update', function(error, res, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('There was a duplicate key error'));
} else {
next(); // The `update()` call will still error out.
}
});
var people = [{ name: 'Axl Rose' }, { name: 'Slash' }];
Person.create(people, function(error) {
Person.update({ name: 'Slash' }, { $set: { name: 'Axl Rose' } }, function(error) {
// `error.message` will be "There was a duplicate key error"
});
});
```
Error handling middleware can transform an error, but it can't remove the error. Even if you call `next()` with no error as shown above, the function call will still error out.
Aggregation Hooks
-----------------
You can also define hooks for the [`Model.aggregate()` function](https://mongoosejs.com/docs/api.html#model_Model.aggregate). In aggregation middleware functions, `this` refers to the [Mongoose `Aggregate` object](https://mongoosejs.com/docs/api.html#Aggregate). For example, suppose you're implementing soft deletes on a `Customer` model by adding an `isDeleted` property. To make sure `aggregate()` calls only look at customers that aren't soft deleted, you can use the below middleware to add a [`$match` stage](https://mongoosejs.com/docs/api.html#aggregate_Aggregate-match) to the beginning of each [aggregation pipeline](https://docs.mongodb.com/manual/core/aggregation-pipeline/).
```
customerSchema.pre('aggregate', function() {
// Add a $match state to the beginning of each pipeline.
this.pipeline().unshift({ $match: { isDeleted: { $ne: true } } });
});
```
The [`Aggregate#pipeline()` function](https://mongoosejs.com/docs/api.html#aggregate_Aggregate-pipeline) lets you access the MongoDB aggregation pipeline that Mongoose will send to the MongoDB server. It is useful for adding stages to the beginning of the pipeline from middleware.
Synchronous Hooks
-----------------
Certain Mongoose hooks are synchronous, which means they do **not** support functions that return promises or receive a `next()` callback. Currently, only `init` hooks are synchronous, because the [`init()` function](https://mongoosejs.com/docs/api.html#document_Document-init) is synchronous. Below is an example of using pre and post init hooks.
```
const schema = new Schema({ title: String, loadedAt: Date });
schema.pre('init', pojo => {
assert.equal(pojo.constructor.name, 'Object'); // Plain object before init
});
const now = new Date();
schema.post('init', doc => {
assert.ok(doc instanceof mongoose.Document); // Mongoose doc after init
doc.loadedAt = now;
});
const Test = db.model('TestPostInitMiddleware', schema);
return Test.create({ title: 'Casino Royale' }).
then(doc => Test.findById(doc)).
then(doc => assert.equal(doc.loadedAt.valueOf(), now.valueOf()));
```
To report an error in an init hook, you must throw a **synchronous** error. Unlike all other middleware, init middleware does **not** handle promise rejections.
```
const schema = new Schema({ title: String });
const swallowedError = new Error('will not show');
// init hooks do \*\*not\*\* handle async errors or any sort of async behavior
schema.pre('init', () => Promise.reject(swallowedError));
schema.post('init', () => { throw Error('will show'); });
const Test = db.model('PostInitBook', schema);
return Test.create({ title: 'Casino Royale' }).
then(doc => Test.findById(doc)).
catch(error => assert.equal(error.message, 'will show'));
```
Next Up
-------
Now that we've covered middleware, let's take a look at Mongoose's approach to faking JOINs with its query [population](populate) helper.
mongoose Migrating from 4.x to 5.x Migrating from 4.x to 5.x
=========================
There are several [backwards-breaking changes](https://github.com/Automattic/mongoose/blob/master/History.md) you should be aware of when migrating from Mongoose 4.x to Mongoose 5.x.
If you're still on Mongoose 3.x, please read the [Mongoose 3.x to 4.x migration guide](https://mongoosejs.com/docs/migration.html).
* [Version Requirements](#version-requirements)
* [Query Middleware](#query-middleware)
* [Promises and Callbacks for `mongoose.connect()`](#promises-and-callbacks)
* [Connection Logic and `useMongoClient`](#connection-logic)
* [Setter Order](#setter-order)
* [Checking if a path is populated](#id-getter)
* [Return Values for `remove()` and `deleteX()`](#return-value-for-delete)
* [Aggregation Cursors](#aggregation-cursors)
* [geoNear](#geonear)
* [Required URI encoding of connection strings](#uri-encoding)
* [Passwords which contain certain characters](#password-characters)
* [Domain sockets](#domain-sockets)
* [`toObject()` Options](#toobject-options)
* [Aggregate Parameters](#aggregate-parameters)
* [Boolean Casting](#boolean-casting)
* [Query Casting](#query-casting)
* [Post Save Hooks Get Flow Control](#post-save-flow-control)
* [The `$pushAll` Operator](#pushall)
* [Always Use Forward Key Order](#retain-key-order)
* [Run setters on queries](#run-setters-on-queries)
* [Pre-compiled Browser Bundle](#browser-bundle)
* [Save Errors](#save-errors)
* [Init hook signatures](#init-hooks)
* [`numAffected` and `save()`](#save-num-affected)
* [`remove()` and debouncing](#remove-debounce)
* [`getPromiseConstructor()`](#get-promise-constructor)
* [Passing Parameters from Pre Hooks](#pre-hook-params)
* [`required` validator for arrays](#array-required)
* [debug output defaults to stdout instead of stderr](#debug-output)
* [Overwriting filter properties](#overwrite-filter)
* [`bulkWrite()` results](#bulkwrite-results)
Version Requirements
--------------------
Mongoose now requires Node.js >= 4.0.0 and MongoDB >= 3.0.0. [MongoDB 2.6](https://www.mongodb.com/blog/post/mongodb-2-6-end-of-life) and [Node.js < 4](https://github.com/nodejs/Release) where both EOL-ed in 2016.
Query Middleware
----------------
Query middleware is now compiled when you call `mongoose.model()` or `db.model()`. If you add query middleware after calling `mongoose.model()`, that middleware will **not** get called.
```
const schema = new Schema({ name: String });
const MyModel = mongoose.model('Test', schema);
schema.pre('find', () => { console.log('find!'); });
MyModel.find().exec(function() {
// In mongoose 4.x, the above `.find()` will print "find!"
// In mongoose 5.x, "find!" will \*\*not\*\* be printed.
// Call `pre('find')` \*\*before\*\* calling `mongoose.model()` to make the middleware apply.
});
```
Promises and Callbacks for `mongoose.connect()`
------------------------------------------------
`mongoose.connect()` and `mongoose.disconnect()` now return a promise if no callback specified, or `null` otherwise. It does **not** return the mongoose singleton.
```
// Worked in mongoose 4. Does \*\*not\*\* work in mongoose 5, `mongoose.connect()`
// now returns a promise consistently. This is to avoid the horrible things
// we've done to allow mongoose to be a thenable that resolves to itself.
mongoose.connect('mongodb://localhost:27017/test').model('Test', new Schema({}));
// Do this instead
mongoose.connect('mongodb://localhost:27017/test');
mongoose.model('Test', new Schema({}));
```
Connection Logic and `useMongoClient`
--------------------------------------
The [`useMongoClient` option](http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client) was removed in Mongoose 5, it is now always `true`. As a consequence, Mongoose 5 no longer supports several function signatures for `mongoose.connect()` that worked in Mongoose 4.x if the `useMongoClient` option was off. Below are some examples of `mongoose.connect()` calls that do **not** work in Mongoose 5.x.
* `mongoose.connect('localhost', 27017);`
* `mongoose.connect('localhost', 'mydb', 27017);`
* `mongoose.connect('mongodb://host1:27017,mongodb://host2:27017');`
In Mongoose 5.x, the first parameter to `mongoose.connect()` and `mongoose.createConnection()`, if specified, **must** be a [MongoDB connection string](https://docs.mongodb.com/manual/reference/connection-string/). The connection string and options are then passed down to [the MongoDB Node.js driver's `MongoClient.connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#.connect). Mongoose does not modify the connection string, although `mongoose.connect()` and `mongoose.createConnection()` support a [few additional options in addition to the ones the MongoDB driver supports](http://mongoosejs.com/docs/connections.html#options).
Setter Order
-------------
Setters run in reverse order in 4.x:
```
const schema = new Schema({ name: String });
schema.path('name').
set(() => console.log('This will print 2nd')).
set(() => console.log('This will print first'));
```
In 5.x, setters run in the order they're declared.
```
const schema = new Schema({ name: String });
schema.path('name').
set(() => console.log('This will print first')).
set(() => console.log('This will print 2nd'));
```
Checking if a path is populated
--------------------------------
Mongoose 5.1.0 introduced an `_id` getter to ObjectIds that lets you get an ObjectId regardless of whether a path is populated.
```
const blogPostSchema = new Schema({
title: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Author'
}
});
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
await BlogPost.create({ title: 'test', author: author._id });
const blogPost = await BlogPost.findOne();
console.log(blogPost.author); // '5b207f84e8061d1d2711b421'
// New in Mongoose 5.1.0: this will print '5b207f84e8061d1d2711b421' as well
console.log(blogPost.author._id);
await blogPost.populate('author');
console.log(blogPost.author._id); '5b207f84e8061d1d2711b421'
```
As a consequence, checking whether `blogPost.author._id` is [no longer viable as a way to check whether `author` is populated](https://github.com/Automattic/mongoose/issues/6415#issuecomment-388579185). Use `blogPost.populated('author') != null` or `blogPost.author instanceof mongoose.Types.ObjectId` to check whether `author` is populated instead.
Note that you can call `mongoose.set('objectIdGetter', false)` to change this behavior.
Return Values for `remove()` and `deleteX()`
---------------------------------------------
`deleteOne()`, `deleteMany()`, and `remove()` now resolve to the result object rather than the full [driver `WriteOpResult` object](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~writeOpCallback).
```
// In 4.x, this is how you got the number of documents deleted
MyModel.deleteMany().then(res => console.log(res.result.n));
// In 5.x this is how you get the number of documents deleted
MyModel.deleteMany().then(res => res.n);
```
Aggregation Cursors
--------------------
The `useMongooseAggCursor` option from 4.x is now always on. This is the new syntax for aggregation cursors in mongoose 5:
```
// When you call `.cursor()`, `.exec()` will now return a mongoose aggregation
// cursor.
const cursor = MyModel.aggregate([{ $match: { name: 'Val' } }]).cursor().exec();
// No need to `await` on the cursor or wait for a promise to resolve
cursor.eachAsync(doc => console.log(doc));
// Can also pass options to `cursor()`
const cursorWithOptions = MyModel.
aggregate([{ $match: { name: 'Val' } }]).
cursor({ batchSize: 10 }).
exec();
```
geoNear
--------
`Model.geoNear()` has been removed because the [MongoDB driver no longer supports it](https://github.com/mongodb/node-mongodb-native/blob/master/CHANGES_3.0.0.md#geonear-command-helper)
Required URI encoding of connection strings
--------------------------------------------
Due to changes in the MongoDB driver, connection strings must be URI encoded.
If they are not, connections may fail with an illegal character message.
Passwords which contain certain characters
-------------------------------------------
See a [full list of affected characters](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
If your app is used by a lot of different connection strings, it's possible that your test cases will pass, but production passwords will fail. Encode all your connection strings to be safe.
If you want to continue to use unencoded connection strings, the easiest fix is to use the `mongodb-uri` module to parse the connection strings, and then produce the properly encoded versions. You can use a function like this:
```
const uriFormat = require('mongodb-uri')
function encodeMongoURI (urlString) {
if (urlString) {
let parsed = uriFormat.parse(urlString)
urlString = uriFormat.format(parsed);
}
return urlString;
}
}
// Your un-encoded string.
const mongodbConnectString = "mongodb://...";
mongoose.connect(encodeMongoURI(mongodbConnectString))
```
The function above is safe to use whether the existing string is already encoded or not.
Domain sockets
---------------
Domain sockets must be URI encoded. For example:
```
// Works in mongoose 4. Does \*\*not\*\* work in mongoose 5 because of more
// stringent URI parsing.
const host = '/tmp/mongodb-27017.sock';
mongoose.createConnection(`mongodb://aaron:psw@${host}/fake`);
// Do this instead
const host = encodeURIComponent('/tmp/mongodb-27017.sock');
mongoose.createConnection(`mongodb://aaron:psw@${host}/fake`);
```
`toObject()` Options
---------------------
The `options` parameter to `toObject()` and `toJSON()` merge defaults rather than overwriting them.
```
// Note the `toObject` option below
const schema = new Schema({ name: String }, { toObject: { virtuals: true } });
schema.virtual('answer').get(() => 42);
const MyModel = db.model('MyModel', schema);
const doc = new MyModel({ name: 'test' });
// In mongoose 4.x this prints "undefined", because `{ minimize: false }`
// overwrites the entire schema-defined options object.
// In mongoose 5.x this prints "42", because `{ minimize: false }` gets
// merged with the schema-defined options.
console.log(doc.toJSON({ minimize: false }).answer);
```
Aggregate Parameters
---------------------
`aggregate()` no longer accepts a spread, you **must** pass your aggregation pipeline as an array. The below code worked in 4.x:
```
MyModel.aggregate({ $match: { isDeleted: false } }, { $skip: 10 }).exec(cb);
```
The above code does **not** work in 5.x, you **must** wrap the `$match` and `$skip` stages in an array.
```
MyModel.aggregate([{ $match: { isDeleted: false } }, { $skip: 10 }]).exec(cb);
```
Boolean Casting
----------------
By default, mongoose 4 would coerce any value to a boolean without error.
```
// Fine in mongoose 4, would save a doc with `boolField = true`
const MyModel = mongoose.model('Test', new Schema({
boolField: Boolean
}));
MyModel.create({ boolField: 'not a boolean' });
```
Mongoose 5 only casts the following values to `true`:
* `true`
* `'true'`
* `1`
* `'1'`
* `'yes'`
And the following values to `false`:
* `false`
* `'false'`
* `0`
* `'0'`
* `'no'`
All other values will cause a `CastError`
Query Casting
--------------
Casting for `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `remove()`, `deleteOne()`, and `deleteMany()` doesn't happen until `exec()`. This makes it easier for hooks and custom query helpers to modify data, because mongoose won't restructure the data you passed in until after your hooks and query helpers have ran. It also makes it possible to set the `overwrite` option *after* passing in an update.
```
// In mongoose 4.x, this becomes `{ $set: { name: 'Baz' } }` despite the `overwrite`
// In mongoose 5.x, this overwrite is respected and the first document with
// `name = 'Bar'` will be replaced with `{ name: 'Baz' }`
User.where({ name: 'Bar' }).update({ name: 'Baz' }).setOptions({ overwrite: true });
```
Post Save Hooks Get Flow Control
---------------------------------
Post hooks now get flow control, which means async post save hooks and child document post save hooks execute **before** your `save()` callback.
```
const ChildModelSchema = new mongoose.Schema({
text: {
type: String
}
});
ChildModelSchema.post('save', function(doc) {
// In mongoose 5.x this will print \*\*before\*\* the `console.log()`
// in the `save()` callback. In mongoose 4.x this was reversed.
console.log('Child post save');
});
const ParentModelSchema = new mongoose.Schema({
children: [ChildModelSchema]
});
const Model = mongoose.model('Parent', ParentModelSchema);
const m = new Model({ children: [{ text: 'test' }] });
m.save(function() {
// In mongoose 5.xm this prints \*\*after\*\* the "Child post save" message.
console.log('Save callback');
});
```
The `$pushAll` Operator
------------------------
`$pushAll` is no longer supported and no longer used internally for `save()`, since it has been [deprecated since MongoDB 2.4](https://docs.mongodb.com/manual/reference/operator/update/pushAll/). Use `$push` with `$each` instead.
Always Use Forward Key Order
-----------------------------
The `retainKeyOrder` option was removed, mongoose will now always retain the same key position when cloning objects. If you have queries or indexes that rely on reverse key order, you will have to change them.
Run setters on queries
-----------------------
Setters now run on queries by default, and the old `runSettersOnQuery` option has been removed.
```
const schema = new Schema({
email: { type: String, lowercase: true }
});
const Model = mongoose.model('Test', schema);
Model.find({ email: '[email protected]' }); // Converted to `find({ email: '[email protected]' })`
```
Pre-compiled Browser Bundle
----------------------------
We no longer have a pre-compiled version of mongoose for the browser. If you want to use mongoose schemas in the browser, you need to build your own bundle with browserify/webpack.
Save Errors
------------
The `saveErrorIfNotFound` option was removed, mongoose will now always error out from `save()` if the underlying document was not found
Init hook signatures
---------------------
`init` hooks are now fully synchronous and do not receive `next()` as a parameter.
`Document.prototype.init()` no longer takes a callback as a parameter. It was always synchronous, just had a callback for legacy reasons.
`numAffected` and `save()`
---------------------------
`doc.save()` no longer passes `numAffected` as a 3rd param to its callback.
`remove()` and debouncing
--------------------------
`doc.remove()` no longer debounces
`getPromiseConstructor()`
--------------------------
`getPromiseConstructor()` is gone, just use `mongoose.Promise`.
Passing Parameters from Pre Hooks
----------------------------------
You cannot pass parameters to the next pre middleware in the chain using `next()` in mongoose 5.x. In mongoose 4, `next('Test')` in pre middleware would call the next middleware with 'Test' as a parameter. Mongoose 5.x has removed support for this.
`required` validator for arrays
--------------------------------
In mongoose 5 the `required` validator only verifies if the value is an array. That is, it will **not** fail for *empty* arrays as it would in mongoose 4.
debug output defaults to stdout instead of stderr
--------------------------------------------------
In mongoose 5 the default debug function uses `console.info()` to display messages instead of `console.error()`.
Overwriting filter properties
------------------------------
In Mongoose 4.x, overwriting a filter property that's a primitive with one that is an object would silently fail. For example, the below code would ignore the `where()` and be equivalent to `Sport.find({ name: 'baseball' })`
```
Sport.find({ name: 'baseball' }).where({name: {$ne: 'softball'}});
```
In Mongoose 5.x, the above code will correctly overwrite `'baseball'` with `{ $ne: 'softball' }`
`bulkWrite()` results
----------------------
Mongoose 5.x uses version 3.x of the [MongoDB Node.js driver](http://npmjs.com/package/mongodb). MongoDB driver 3.x changed the format of the result of [`bulkWrite()` calls](http://localhost:8088/docs/api.html#model_Model.bulkWrite) so there is no longer a top-level `nInserted`, `nModified`, etc. property. The new result object structure is [described here](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult).
```
const Model = mongoose.model('Test', new Schema({ name: String }));
const res = await Model.bulkWrite([{ insertOne: { document: { name: 'test' } } }]);
console.log(res);
```
In Mongoose 4.x, the above will print:
```
BulkWriteResult {
ok: [Getter],
nInserted: [Getter],
nUpserted: [Getter],
nMatched: [Getter],
nModified: [Getter],
nRemoved: [Getter],
getInsertedIds: [Function],
getUpsertedIds: [Function],
getUpsertedIdAt: [Function],
getRawResponse: [Function],
hasWriteErrors: [Function],
getWriteErrorCount: [Function],
getWriteErrorAt: [Function],
getWriteErrors: [Function],
getLastOp: [Function],
getWriteConcernError: [Function],
toJSON: [Function],
toString: [Function],
isOk: [Function],
insertedCount: 1,
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: { '0': 5be9a3101638a066702a0d38 },
n: 1 }
```
In Mongoose 5.x, the script will print:
```
BulkWriteResult {
result:
{ ok: 1,
writeErrors: [],
writeConcernErrors: [],
insertedIds: [ [Object] ],
nInserted: 1,
nUpserted: 0,
nMatched: 0,
nModified: 0,
nRemoved: 0,
upserted: [],
lastOp: { ts: [Object], t: 1 } },
insertedCount: 1,
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: { '0': 5be9a1c87decfc6443dd9f18 },
n: 1 }
```
| programming_docs |
mongoose Subdocuments Subdocuments
============
Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments.
```
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
// Array of subdocuments
children: [childSchema],
// Single nested subdocuments. Caveat: single nested subdocs only work
// in mongoose >= 4.2.0
child: childSchema
});
```
Aside from code reuse, one important reason to use subdocuments is to create a path where there would otherwise not be one to allow for validation over a group of fields (e.g. dateRange.fromDate <= dateRange.toDate).
What is a Subdocument?
----------------------
Subdocuments are similar to normal documents. Nested schemas can have <middleware>, [custom validation logic](validation), virtuals, and any other feature top-level schemas can use. The major difference is that subdocuments are not saved individually, they are saved whenever their top-level parent document is saved.
```
var Parent = mongoose.model('Parent', parentSchema);
var parent = new Parent({ children: [{ name: 'Matt' }, { name: 'Sarah' }] })
parent.children[0].name = 'Matthew';
// `parent.children[0].save()` is a no-op, it triggers middleware but
// does \*\*not\*\* actually save the subdocument. You need to save the parent
// doc.
parent.save(callback);
```
Subdocuments have `save` and `validate` <middleware> just like top-level documents. Calling `save()` on the parent document triggers the `save()` middleware for all its subdocuments, and the same for `validate()` middleware.
```
childSchema.pre('save', function (next) {
if ('invalid' == this.name) {
return next(new Error('#sadpanda'));
}
next();
});
var parent = new Parent({ children: [{ name: 'invalid' }] });
parent.save(function (err) {
console.log(err.message) // #sadpanda
});
```
Subdocuments' `pre('save')` and `pre('validate')` middleware execute **before** the top-level document's `pre('save')` but **after** the top-level document's `pre('validate')` middleware. This is because validating before `save()` is actually a piece of built-in middleware.
```
// Below code will print out 1-4 in order
var childSchema = new mongoose.Schema({ name: 'string' });
childSchema.pre('validate', function(next) {
console.log('2');
next();
});
childSchema.pre('save', function(next) {
console.log('3');
next();
});
var parentSchema = new mongoose.Schema({
child: childSchema,
});
parentSchema.pre('validate', function(next) {
console.log('1');
next();
});
parentSchema.pre('save', function(next) {
console.log('4');
next();
});
```
Finding a Subdocument
---------------------
Each subdocument has an `_id` by default. Mongoose document arrays have a special [id](https://mongoosejs.com/docs/api.html#types_documentarray_MongooseDocumentArray-id) method for searching a document array to find a document with a given `_id`.
```
var doc = parent.children.id(_id);
```
Adding Subdocs to Arrays
------------------------
MongooseArray methods such as [push](https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-push), [unshift](https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-unshift), [addToSet](https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-addToSet), and others cast arguments to their proper types transparently:
```
var Parent = mongoose.model('Parent');
var parent = new Parent;
// create a comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { \_id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
parent.save(function (err) {
if (err) return handleError(err)
console.log('Success!');
});
```
Subdocs may also be created without adding them to the array by using the [create](https://mongoosejs.com/docs/api.html#types_documentarray_MongooseDocumentArray.create) method of MongooseArrays.
```
var newdoc = parent.children.create({ name: 'Aaron' });
```
Removing Subdocs
----------------
Each subdocument has it's own [remove](https://mongoosejs.com/docs/api.html#types_embedded_EmbeddedDocument-remove) method. For an array subdocument, this is equivalent to calling `.pull()` on the subdocument. For a single nested subdocument, `remove()` is equivalent to setting the subdocument to `null`.
```
// Equivalent to `parent.children.pull(\_id)`
parent.children.id(_id).remove();
// Equivalent to `parent.child = null`
parent.child.remove();
parent.save(function (err) {
if (err) return handleError(err);
console.log('the subdocs were removed');
});
```
Parents of Subdocs
------------------
Sometimes, you need to get the parent of a subdoc. You can access the parent using the `parent()` function.
```
const schema = new Schema({
docArr: [{ name: String }],
singleNested: new Schema({ name: String })
});
const Model = mongoose.model('Test', schema);
const doc = new Model({
docArr: [{ name: 'foo' }],
singleNested: { name: 'bar' }
});
doc.singleNested.parent() === doc; // true
doc.docArr[0].parent() === doc; // true
```
If you have a deeply nested subdoc, you can access the top-level document using the `ownerDocument()` function.
```
const schema = new Schema({
level1: new Schema({
level2: new Schema({
test: String
})
})
});
const Model = mongoose.model('Test', schema);
const doc = new Model({ level1: { level2: 'test' } });
doc.level1.level2.parent() === doc; // false
doc.level1.level2.parent() === doc.level1; // true
doc.level1.level2.ownerDocument() === doc; // true
```
#### Alternate declaration syntax for arrays
If you create a schema with an array of objects, mongoose will automatically convert the object to a schema for you:
```
var parentSchema = new Schema({
children: [{ name: 'string' }]
});
// Equivalent
var parentSchema = new Schema({
children: [new Schema({ name: 'string' })]
});
```
#### Alternate declaration syntax for single subdocuments
Similarly, single subdocuments also have a shorthand whereby you can omit wrapping the schema with an instance of Schema. However, for historical reasons, this alternate declaration must be enabled via an option (either on the parent schema instantiation or on the mongoose instance).
```
var parentSchema = new Schema({
child: { type: { name: 'string' } }
}, { typePojoToMixed: false });
// Equivalent
var parentSchema = new Schema({
child: new Schema({ name: 'string' })
});
// Not equivalent! Careful - a Mixed path is created instead!
var parentSchema = new Schema({
child: { type: { name: 'string' } }
});
```
Next Up
-------
Now that we've covered Subdocuments, let's take a look at [querying](queries).
mongoose Queries Queries
=======
Mongoose <models> provide several static helper functions for [CRUD operations](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete). Each of these functions returns a [mongoose `Query` object](http://mongoosejs.com/docs/api.html#Query).
* [`Model.deleteMany()`](https://mongoosejs.com/docs/api.html#model_Model.deleteMany)
* [`Model.deleteOne()`](https://mongoosejs.com/docs/api.html#model_Model.deleteOne)
* [`Model.find()`](https://mongoosejs.com/docs/api.html#model_Model.find)
* [`Model.findById()`](https://mongoosejs.com/docs/api.html#model_Model.findById)
* [`Model.findByIdAndDelete()`](https://mongoosejs.com/docs/api.html#model_Model.findByIdAndDelete)
* [`Model.findByIdAndRemove()`](https://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove)
* [`Model.findByIdAndUpdate()`](https://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate)
* [`Model.findOne()`](https://mongoosejs.com/docs/api.html#model_Model.findOne)
* [`Model.findOneAndDelete()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndDelete)
* [`Model.findOneAndRemove()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove)
* [`Model.findOneAndReplace()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndReplace)
* [`Model.findOneAndUpdate()`](https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate)
* [`Model.replaceOne()`](https://mongoosejs.com/docs/api.html#model_Model.replaceOne)
* [`Model.updateMany()`](https://mongoosejs.com/docs/api.html#model_Model.updateMany)
* [`Model.updateOne()`](https://mongoosejs.com/docs/api.html#model_Model.updateOne)
A mongoose query can be executed in one of two ways. First, if you pass in a `callback` function, Mongoose will execute the query asynchronously and pass the results to the `callback`.
A query also has a `.then()` function, and thus can be used as a promise.
Executing
---------
When executing a query with a `callback` function, you specify your query as a JSON document. The JSON document's syntax is the same as the [MongoDB shell](http://docs.mongodb.org/manual/tutorial/query-documents/).
```
var Person = mongoose.model('Person', yourSchema);
// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
if (err) return handleError(err);
// Prints "Space Ghost is a talk show host".
console.log('%s %s is a %s.', person.name.first, person.name.last,
person.occupation);
});
```
Mongoose executed the query and passed the results passed to `callback`. All callbacks in Mongoose use the pattern: `callback(error, result)`. If an error occurs executing the query, the `error` parameter will contain an error document, and `result` will be null. If the query is successful, the `error` parameter will be null, and the `result` will be populated with the results of the query.
Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern `callback(error, results)`. What `results` is depends on the operation: For `findOne()` it is a [potentially-null single document](https://mongoosejs.com/docs/api.html#model_Model.findOne), `find()` a [list of documents](https://mongoosejs.com/docs/api.html#model_Model.find), `count()` [the number of documents](https://mongoosejs.com/docs/api.html#model_Model.count), `update()` the [number of documents affected](https://mongoosejs.com/docs/api.html#model_Model.update), etc. The [API docs for Models](https://mongoosejs.com/docs/api.html#model-js) provide more detail on what is passed to the callbacks.
Now let's look at what happens when no `callback` is passed:
```
// find each person with a last name matching 'Ghost'
var query = Person.findOne({ 'name.last': 'Ghost' });
// selecting the `name` and `occupation` fields
query.select('name occupation');
// execute the query at a later time
query.exec(function (err, person) {
if (err) return handleError(err);
// Prints "Space Ghost is a talk show host."
console.log('%s %s is a %s.', person.name.first, person.name.last,
person.occupation);
});
```
In the above code, the `query` variable is of type [Query](https://mongoosejs.com/docs/api.html#query-js). A `Query` enables you to build up a query using chaining syntax, rather than specifying a JSON object. The below 2 examples are equivalent.
```
// With a JSON doc
Person.
find({
occupation: /host/,
'name.last': 'Ghost',
age: { $gt: 17, $lt: 66 },
likes: { $in: ['vaporizing', 'talking'] }
}).
limit(10).
sort({ occupation: -1 }).
select({ name: 1, occupation: 1 }).
exec(callback);
// Using query builder
Person.
find({ occupation: /host/ }).
where('name.last').equals('Ghost').
where('age').gt(17).lt(66).
where('likes').in(['vaporizing', 'talking']).
limit(10).
sort('-occupation').
select('name occupation').
exec(callback);
```
A full list of [Query helper functions can be found in the API docs](https://mongoosejs.com/docs/api.html#query-js).
Queries are Not Promises
-------------------------
Mongoose queries are **not** promises. They have a `.then()` function for [co](https://www.npmjs.com/package/co) and [async/await](http://thecodebarbarian.com/common-async-await-design-patterns-in-node.js.html) as a convenience. However, unlike promises, calling a query's `.then()` can execute the query multiple times.
For example, the below code will execute 3 `updateMany()` calls, one because of the callback, and two because `.then()` is called twice.
```
const q = MyModel.updateMany({}, { isDeleted: true }, function() {
console.log('Update 1');
});
q.then(() => console.log('Update 2'));
q.then(() => console.log('Update 3'));
```
Don't mix using callbacks and promises with queries, or you may end up with duplicate operations.
References to other documents
-----------------------------
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where [population](populate) comes in. Read more about how to include documents from other collections in your query results [here](https://mongoosejs.com/docs/api.html#query_Query-populate).
Streaming
---------
You can [stream](http://nodejs.org/api/stream.html) query results from MongoDB. You need to call the [Query#cursor()](https://mongoosejs.com/docs/api.html#query_Query-cursor) function to return an instance of [QueryCursor](https://mongoosejs.com/docs/api.html#query_Query-cursor).
```
var cursor = Person.find({ occupation: /host/ }).cursor();
cursor.on('data', function(doc) {
// Called once for every document
});
cursor.on('close', function() {
// Called when done
});
```
Next Up
-------
Now that we've covered `Queries`, let's take a look at [Validation](validation).
mongoose Defaults Defaults
========
Declaring defaults in your schema
---------------------------------
Your schemas can define default values for certain paths. If you create a new document without that path set, the default will kick in.
Note: Mongoose only applies a default if the value of the path is strictly `undefined`.
```
var schema = new Schema({
name: String,
role: { type: String, default: 'guitarist' }
});
var Person = db.model('Person', schema);
var axl = new Person({ name: 'Axl Rose', role: 'singer' });
assert.equal(axl.role, 'singer');
var slash = new Person({ name: 'Slash' });
assert.equal(slash.role, 'guitarist');
var izzy = new Person({ name: 'Izzy', role: undefined });
assert.equal(izzy.role, 'guitarist');
// Defaults do \*\*not\*\* run on `null`, `''`, or value other than `undefined`.
var foo = new Person({ name: 'Bar', role: null });
assert.strictEqual(foo.role, null);
Person.create(axl, slash, function(error) {
assert.ifError(error);
Person.find({ role: 'guitarist' }, function(error, docs) {
assert.ifError(error);
assert.equal(docs.length, 1);
assert.equal(docs[0].name, 'Slash');
});
});
```
Default functions
-----------------
You can also set the `default` schema option to a function. Mongoose will execute that function and use the return value as the default.
```
var schema = new Schema({
title: String,
date: {
type: Date,
// `Date.now()` returns the current unix timestamp as a number
default: Date.now
}
});
var BlogPost = db.model('BlogPost', schema);
var post = new BlogPost({title: '5 Best Arnold Schwarzenegger Movies'});
// The post has a default Date set to now
assert.ok(post.date.getTime() >= Date.now() - 1000);
assert.ok(post.date.getTime() <= Date.now());
```
The `setDefaultsOnInsert` option
--------------------------------
By default, mongoose only applies defaults when you create a new document. It will **not** set defaults if you use `update()` and `findOneAndUpdate()`. However, mongoose 4.x lets you opt-in to this behavior using the `setDefaultsOnInsert` option.
Important
---------
The `setDefaultsOnInsert` option relies on the [MongoDB `$setOnInsert` operator](https://docs.mongodb.org/manual/reference/operator/update/setOnInsert/). The `$setOnInsert` operator was introduced in MongoDB 2.4. If you're using MongoDB server < 2.4.0, do **not** use `setDefaultsOnInsert`.
```
var schema = new Schema({
title: String,
genre: {type: String, default: 'Action'}
});
var Movie = db.model('Movie', schema);
var query = {};
var update = {title: 'The Terminator'};
var options = {
// Return the document after updates are applied
new: true,
// Create a document if one isn't found. Required
// for `setDefaultsOnInsert`
upsert: true,
setDefaultsOnInsert: true
};
Movie.
findOneAndUpdate(query, update, options, function (error, doc) {
assert.ifError(error);
assert.equal(doc.title, 'The Terminator');
assert.equal(doc.genre, 'Action');
});
```
Default functions and `this`
----------------------------
Unless it is running on a query with `setDefaultsOnInsert`, a default function's `this` refers to the document.
```
const schema = new Schema({
title: String,
released: Boolean,
releaseDate: {
type: Date,
default: function() {
if (this.released) {
return Date.now();
}
return null;
}
}
});
const Movie = db.model('Movie', schema);
const movie1 = new Movie({ title: 'The Terminator', released: true });
// The post has a default Date set to now
assert.ok(movie1.releaseDate.getTime() >= Date.now() - 1000);
assert.ok(movie1.releaseDate.getTime() <= Date.now());
const movie2 = new Movie({ title: 'The Legend of Conan', released: false });
// Since `released` is false, the default function will return null
assert.strictEqual(movie2.releaseDate, null);
```
mongoose Models Models
======
[Models](https://mongoosejs.com/docs/api.html#model-js) are fancy constructors compiled from `Schema` definitions. An instance of a model is called a [document](documents). Models are responsible for creating and reading documents from the underlying MongoDB database.
* [Compiling your first model](#compiling)
* [Constructing Documents](#constructing-documents)
* [Querying](#querying)
* [Deleting](#deleting)
* [Updating](#updating)
* [Change Streams](#change-streams)
Compiling your first model
--------------------------
When you call `mongoose.model()` on a schema, Mongoose *compiles* a model for you.
```
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
```
The first argument is the *singular* name of the collection your model is for. \*\* Mongoose automatically looks for the plural, lowercased version of your model name. \*\* Thus, for the example above, the model Tank is for the **tanks** collection in the database.
**Note:** The `.model()` function makes a copy of `schema`. Make sure that you've added everything you want to `schema`, including hooks, before calling `.model()`!
Constructing Documents
----------------------
An instance of a model is called a [document](documents). Creating them and saving to the database is easy.
```
var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });
small.save(function (err) {
if (err) return handleError(err);
// saved!
});
// or
Tank.create({ size: 'small' }, function (err, small) {
if (err) return handleError(err);
// saved!
});
// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {
});
```
Note that no tanks will be created/removed until the connection your model uses is open. Every model has an associated connection. When you use `mongoose.model()`, your model will use the default mongoose connection.
```
mongoose.connect('mongodb://localhost/gettingstarted', {useNewUrlParser: true});
```
If you create a custom connection, use that connection's `model()` function instead.
```
var connection = mongoose.createConnection('mongodb://localhost:27017/test');
var Tank = connection.model('Tank', yourSchema);
```
Querying
--------
Finding documents is easy with Mongoose, which supports the [rich](http://www.mongodb.org/display/DOCS/Advanced+Queries) query syntax of MongoDB. Documents can be retreived using each `models` [find](https://mongoosejs.com/docs/api.html#model_Model.find), [findById](https://mongoosejs.com/docs/api.html#model_Model.findById), [findOne](https://mongoosejs.com/docs/api.html#model_Model.findOne), or [where](https://mongoosejs.com/docs/api.html#model_Model.where) static methods.
```
Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);
```
See the chapter on <queries> for more details on how to use the [Query](https://mongoosejs.com/docs/api.html#query-js) api.
Deleting
--------
Models have static `deleteOne()` and `deleteMany()` functions for removing all documents matching the given `filter`.
```
Tank.deleteOne({ size: 'large' }, function (err) {
if (err) return handleError(err);
// deleted at most one tank document
});
```
Updating
--------
Each `model` has its own `update` method for modifying documents in the database without returning them to your application. See the [API](https://mongoosejs.com/docs/api.html#model_Model.updateOne) docs for more detail.
```
Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) {
// Updated at most one doc, `res.modifiedCount` contains the number
// of docs that MongoDB updated
});
```
*If you want to update a single document in the db and return it to your application, use [findOneAndUpdate](https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate) instead.*
Change Streams
--------------
*New in MongoDB 3.6.0 and Mongoose 5.0.0*
[Change streams](https://docs.mongodb.com/manual/changeStreams/) provide a way for you to listen to all inserts and updates going through your MongoDB database. Note that change streams do **not** work unless you're connected to a [MongoDB replica set](https://docs.mongodb.com/manual/replication/).
```
async function run() {
// Create a new mongoose model
const personSchema = new mongoose.Schema({
name: String
});
const Person = mongoose.model('Person', personSchema, 'Person');
// Create a change stream. The 'change' event gets emitted when there's a
// change in the database
Person.watch().
on('change', data => console.log(new Date(), data));
// Insert a doc, will trigger the change stream handler above
console.log(new Date(), 'Inserting doc');
await Person.create({ name: 'Axl Rose' });
}
```
The output from the above [async function](http://thecodebarbarian.com/80-20-guide-to-async-await-in-node.js.html) will look like what you see below.
```
2018-05-11T15:05:35.467Z 'Inserting doc'
2018-05-11T15:05:35.487Z 'Inserted doc'
2018-05-11T15:05:35.491Z { _id: { _data: ... },
operationType: 'insert',
fullDocument: { _id: 5af5b13fe526027666c6bf83, name: 'Axl Rose', __v: 0 },
ns: { db: 'test', coll: 'Person' },
documentKey: { _id: 5af5b13fe526027666c6bf83 } }
```
You can read more about [change streams in mongoose in this blog post](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-change-streams.html#change-streams-in-mongoose).
Yet more
--------
The [API docs](https://mongoosejs.com/docs/api.html#model_Model) cover many additional methods available like [count](https://mongoosejs.com/docs/api.html#model_Model.count), [mapReduce](https://mongoosejs.com/docs/api.html#model_Model.mapReduce), [aggregate](https://mongoosejs.com/docs/api.html#model_Model.aggregate), and [more](https://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove).
Next Up
-------
Now that we've covered `Models`, let's take a look at [Documents](documents).
| programming_docs |
mongoose Connections Connections
===========
You can connect to MongoDB with the `mongoose.connect()` method.
```
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
```
This is the minimum needed to connect the `myapp` database running locally on the default port (27017). If connecting fails on your machine, try using `127.0.0.1` instead of `localhost`.
You can also specify several more parameters in the `uri`:
```
mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});
```
See the [mongodb connection string spec](http://docs.mongodb.org/manual/reference/connection-string/) for more detail.
Operation Buffering
-------------------
Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.
```
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
var MyModel = mongoose.model('Test', new Schema({ name: String }));
// Works
MyModel.findOne(function(error, result) { /\* ... \*/ });
```
That's because mongoose buffers model function calls internally. This buffering is convenient, but also a common source of confusion. Mongoose will *not* throw any errors by default if you use a model without connecting.
```
var MyModel = mongoose.model('Test', new Schema({ name: String }));
// Will just hang until mongoose successfully connects
MyModel.findOne(function(error, result) { /\* ... \*/ });
setTimeout(function() {
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
}, 60000);
```
To disable buffering, turn off the [`bufferCommands` option on your schema](guide#bufferCommands). If you have `bufferCommands` on and your connection is hanging, try turning `bufferCommands` off to see if you haven't opened a connection properly. You can also disable `bufferCommands` globally:
```
mongoose.set('bufferCommands', false);
```
Error Handling
--------------
There are two classes of errors that can occur with a Mongoose connection.
* Error on initial connection. If initial connection fails, Mongoose will **not** attempt to reconnect, it will emit an 'error' event, and the promise `mongoose.connect()` returns will reject.
* Error after initial connection was established. Mongoose will attempt to reconnect, and it will emit an 'error' event.
To handle initial connection errors, you should use `.catch()` or `try/catch` with async/await.
```
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }).
catch(error => handleError(error));
// Or:
try {
await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
handleError(error);
}
```
To handle errors after initial connection was established, you should listen for error events on the connection. However, you still need to handle initial connection errors as shown above.
```
mongoose.connection.on('error', err => {
logError(err);
});
```
Options
-------
The `connect` method also accepts an `options` object which will be passed on to the underlying MongoDB driver.
```
mongoose.connect(uri, options);
```
A full list of options can be found on the [MongoDB Node.js driver docs for `connect()`](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect). Mongoose passes options to the driver without modification, modulo a few exceptions that are explained below.
* `bufferCommands` - This is a mongoose-specific option (not passed to the MongoDB driver) that disables [mongoose's buffering mechanism](http://mongoosejs.com/docs/faq.html#callback_never_executes)
* `user`/`pass` - The username and password for authentication. These options are mongoose-specific, they are equivalent to the MongoDB driver's `auth.user` and `auth.password` options.
* `autoIndex` - By default, mongoose will automatically build indexes defined in your schema when it connects. This is great for development, but not ideal for large production deployments, because index builds can cause performance degradation. If you set `autoIndex` to false, mongoose will not automatically build indexes for **any** model associated with this connection.
* `dbName` - Specifies which database to connect to and overrides any database specified in the connection string. This is useful if you are unable to specify a default database in the connection string like with [some `mongodb+srv` syntax connections](https://stackoverflow.com/questions/48917591/fail-to-connect-mongoose-to-atlas/48917626#48917626).
Below are some of the options that are important for tuning Mongoose.
* `useNewUrlParser` - The underlying MongoDB driver has deprecated their current [connection string](https://docs.mongodb.com/manual/reference/connection-string/) parser. Because this is a major change, they added the `useNewUrlParser` flag to allow users to fall back to the old parser if they find a bug in the new parser. You should set `useNewUrlParser: true` unless that prevents you from connecting. Note that if you specify `useNewUrlParser: true`, you **must** specify a port in your connection string, like `mongodb://localhost:27017/dbname`. The new url parser does *not* support connection strings that do not have a port, like `mongodb://localhost/dbname`.
* `useCreateIndex` - False by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver.
* `useFindAndModify` - True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
* `useUnifiedTopology`- False by default. Set to `true` to opt in to using [the MongoDB driver's new connection management engine](deprecations#useunifiedtopology). You should set this option to `true`, except for the unlikely case that it prevents you from maintaining a stable connection.
* `promiseLibrary` - Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
* `poolSize` - The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
* `connectTimeoutMS` - How long the MongoDB driver will wait before killing a socket due to inactivity *during initial connection*. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
* `socketTimeoutMS` - How long the MongoDB driver will wait before killing a socket due to inactivity *after initial connection*. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
* `family` - Whether to connect using IPv4 or IPv6. This option passed to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. If you don't specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails. If your `mongoose.connect(uri)` call takes a long time, try `mongoose.connect(uri, { family: 4 })`
The following options are important for tuning Mongoose only if you are running **without** [the `useUnifiedTopology` option](deprecations#useunifiedtopology):
* `autoReconnect` - The underlying MongoDB driver will automatically try to reconnect when it loses connection to MongoDB. Unless you are an extremely advanced user that wants to manage their own connection pool, do **not** set this option to `false`.
* `reconnectTries` - If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
* `reconnectInterval` - See `reconnectTries`
* `bufferMaxEntries` - The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.
Example:
```
const options = {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0,
connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
};
mongoose.connect(uri, options);
```
See [this page](http://mongodb.github.io/node-mongodb-native/3.1/reference/faq/) for more information about `connectTimeoutMS` and `socketTimeoutMS`
Callback
--------
The `connect()` function also accepts a callback parameter and returns a [promise](promises).
```
mongoose.connect(uri, options, function(error) {
// Check error in initial connection. There is no 2nd param to the callback.
});
// Or using promises
mongoose.connect(uri, options).then(
() => { /\*\* ready to use. The `mongoose.connect()` promise resolves to mongoose instance. \*/ },
err => { /\*\* handle initial connection error \*/ }
);
```
Connection String Options
-------------------------
You can also specify driver options in your connection string as [parameters in the query string](https://en.wikipedia.org/wiki/Query_string) portion of the URI. This only applies to options passed to the MongoDB driver. You **can't** set Mongoose-specific options like `bufferCommands` in the query string.
```
mongoose.connect('mongodb://localhost:27017/test?connectTimeoutMS=1000&bufferCommands=false');
// The above is equivalent to:
mongoose.connect('mongodb://localhost:27017/test', {
connectTimeoutMS: 1000
// Note that mongoose will \*\*not\*\* pull `bufferCommands` from the query string
});
```
The disadvantage of putting options in the query string is that query string options are harder to read. The advantage is that you only need a single configuration option, the URI, rather than separate options for `socketTimeoutMS`, `connectTimeoutMS`, etc. Best practice is to put options that likely differ between development and production, like `replicaSet` or `ssl`, in the connection string, and options that should remain constant, like `connectTimeoutMS` or `poolSize`, in the options object.
The MongoDB docs have a full list of [supported connection string options](https://docs.mongodb.com/manual/reference/connection-string/)
Connection Events
-----------------
Connections inherit from [Node.js' `EventEmitter` class](https://nodejs.org/api/events.html#events_class_eventemitter), and emit events when something happens to the connection, like losing connectivity to the MongoDB server. Below is a list of events that a connection may emit.
* `connecting`: Emitted when Mongoose starts making its initial connection to the MongoDB server
* `connected`: Emitted when Mongoose successfully makes its initial connection to the MongoDB server
* `open`: Equivalent to `connected`
* `disconnecting`: Your app called [`Connection#close()`](https://mongoosejs.com/docs/api.html#connection_Connection-close) to disconnect from MongoDB
* `disconnected`: Emitted when Mongoose lost connection to the MongoDB server. This event may be due to your code explicitly closing the connection, the database server crashing, or network connectivity issues.
* `close`: Emitted after [`Connection#close()`](https://mongoosejs.com/docs/api.html#connection_Connection-close) successfully closes the connection. If you call `conn.close()`, you'll get both a 'disconnected' event and a 'close' event.
* `reconnected`: Emitted if Mongoose lost connectivity to MongoDB and successfully reconnected. Mongoose attempts to [automatically reconnect](https://thecodebarbarian.com/managing-connections-with-the-mongodb-node-driver.html) when it loses connection to the database.
* `error`: Emitted if an error occurs on a connection, like a `parseError` due to malformed data or a payload larger than [16MB](https://docs.mongodb.com/manual/reference/limits/#BSON-Document-Size).
* `fullsetup`: Emitted when you're connecting to a replica set and Mongoose has successfully connected to the primary and at least one secondary.
* `all`: Emitted when you're connecting to a replica set and Mongoose has successfully connected to all servers specified in your connection string.
* `reconnectFailed`: Emitted when you're connected to a standalone server and Mongoose has run out of [`reconnectTries`](https://thecodebarbarian.com/managing-connections-with-the-mongodb-node-driver.html#handling-single-server-outages). The [MongoDB driver](http://npmjs.com/package/mongodb) will no longer attempt to reconnect after this event is emitted. This event will never be emitted if you're connected to a replica set.
A note about keepAlive
----------------------
For long running applications, it is often prudent to enable `keepAlive` with a number of milliseconds. Without it, after some period of time you may start to see `"connection closed"` errors for what seems like no reason. If so, after [reading this](http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html), you may decide to enable `keepAlive`:
```
mongoose.connect(uri, { keepAlive: true, keepAliveInitialDelay: 300000 });
```
`keepAliveInitialDelay` is the number of milliseconds to wait before initiating `keepAlive` on the socket. `keepAlive` is true by default since mongoose 5.2.0.
Replica Set Connections
-----------------------
To connect to a replica set you pass a comma delimited list of hosts to connect to rather than a single host.
```
mongoose.connect('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]' [, options]);
```
For example:
```
mongoose.connect('mongodb://user:[email protected]:27017,host2.com:27017,host3.com:27017/testdb');
```
To connect to a single node replica set, specify the `replicaSet` option.
```
mongoose.connect('mongodb://host1:port1/?replicaSet=rsName');
```
Server Selection
----------------
If you enable the `useUnifiedTopology` option, the underlying MongoDB driver will use [server selection](https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst) to connect to MongoDB and send operations to MongoDB. If the MongoDB driver can't find a server to send an operation to after `serverSelectionTimeoutMS`, you'll get the below error:
```
MongoTimeoutError: Server selection timed out after 30000 ms
```
You can configure the timeout using the `serverSelectionTimeoutMS` option to `mongoose.connect()`:
```
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000 // Timeout after 5s instead of 30s
});
```
A `MongoTimeoutError` has a `reason` property that explains why server selection timed out. For example, if you're connecting to a standalone server with an incorrect password, `reason` will contain an "Authentication failed" error.
```
const mongoose = require('mongoose');
const uri = 'mongodb+srv://username:[email protected]/' +
'test?retryWrites=true&w=majority';
// Prints "MongoError: bad auth Authentication failed."
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000
}).catch(err => console.log(err.reason));
```
Replica Set Host Names
----------------------
MongoDB replica sets rely on being able to reliably figure out the domain name for each member. On Linux and OSX, the MongoDB server uses the output of the [`hostname` command](https://linux.die.net/man/1/hostname) to figure out the domain name to report to the replica set. This can cause confusing errors if you're connecting to a remote MongoDB replica set running on a machine that reports its `hostname` as `localhost`:
```
// Can get this error even if your connection string doesn't include
// `localhost` if `rs.conf()` reports that one replica set member has
// `localhost` as its host name.
failed to connect to server [localhost:27017] on first connect
```
If you're experiencing a similar error, connect to the replica set using the `mongo` shell and run the [`rs.conf()`](https://docs.mongodb.com/manual/reference/method/rs.conf/) command to check the host names of each replica set member. Follow [this page's instructions to change a replica set member's host name](https://docs.mongodb.com/manual/tutorial/change-hostnames-in-a-replica-set/#change-hostnames-while-maintaining-replica-set-availability).
Multi-mongos support
--------------------
You can also connect to multiple [mongos](https://docs.mongodb.com/manual/reference/program/mongos/) instances for high availability in a sharded cluster. You do [not need to pass any special options to connect to multiple mongos](http://mongodb.github.io/node-mongodb-native/3.0/tutorials/connect/#connect-to-sharded-cluster) in mongoose 5.x.
```
// Connect to 2 mongos servers
mongoose.connect('mongodb://mongosA:27501,mongosB:27501', cb);
```
Multiple connections
--------------------
So far we've seen how to connect to MongoDB using Mongoose's default connection. At times we may need multiple connections open to Mongo, each with different read/write settings, or maybe just to different databases for example. In these cases we can utilize `mongoose.createConnection()` which accepts all the arguments already discussed and returns a fresh connection for you.
```
const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);
```
This [connection](https://mongoosejs.com/docs/api.html#connection_Connection) object is then used to create and retrieve [models](https://mongoosejs.com/docs/api.html#model_Model). Models are **always** scoped to a single connection.
```
const UserModel = conn.model('User', userSchema);
```
If you use multiple connections, you should make sure you export schemas, **not** models.
```
const userSchema = new Schema({ name: String, email: String });
// The correct pattern is to export a schema
module.exports = userSchema;
// Because if you export a model as shown below, the model will be scoped
// to Mongoose's default connection.
// module.exports = mongoose.model('User', userSchema);
```
In addition, you should define a factory function that registers models on a connection to make it easy to register all your models on a given connection.
```
const userSchema = require('./userSchema');
module.exports = conn => {
conn.model('User', userSchema);
};
```
Mongoose creates a *default connection* when you call `mongoose.connect()`. You can access the default connection using `mongoose.connection`.
Connection Pools
----------------
Each `connection`, whether created with `mongoose.connect` or `mongoose.createConnection` are all backed by an internal configurable connection pool defaulting to a maximum size of 5. Adjust the pool size using your connection options:
```
// With object options
mongoose.createConnection(uri, { poolSize: 4 });
const uri = 'mongodb://localhost:27017/test?poolSize=4';
mongoose.createConnection(uri);
```
Option Changes in v5.x
----------------------
You may see the following deprecation warning if upgrading from 4.x to 5.x and you didn't use the `useMongoClient` option in 4.x:
```
the server/replset/mongos options are deprecated, all their options are supported at the top level of the options object
```
In older version of the MongoDB driver you had to specify distinct options for server connections, replica set connections, and mongos connections:
```
mongoose.connect(myUri, {
server: {
socketOptions: {
socketTimeoutMS: 0,
keepAlive: true
},
reconnectTries: 30
},
replset: {
socketOptions: {
socketTimeoutMS: 0,
keepAlive: true
},
reconnectTries: 30
},
mongos: {
socketOptions: {
socketTimeoutMS: 0,
keepAlive: true
},
reconnectTries: 30
}
});
```
In mongoose v5.x you can instead declare these options at the top level, without all that extra nesting. [Here's the list of all supported options](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html).
```
// Equivalent to the above code
mongoose.connect(myUri, {
socketTimeoutMS: 0,
keepAlive: true,
reconnectTries: 30
});
```
Next Up
-------
Now that we've covered connections, let's take a look at <models>.
| programming_docs |
mongoose SingleNestedPath SingleNestedPath
================
### SingleNestedPath()
##### Parameters
* schema «Schema»
* key «String»
* options «Object»
##### Inherits:
* «SchemaType»
Single nested subdocument SchemaType constructor.
### SingleNestedPath.prototype.discriminator()
##### Parameters
* name «String»
* schema «Schema» fields to add to the schema for instances of this sub-class
* [value] «String» the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
##### Returns:
* «Function» the constructor Mongoose will use for creating instances of this discriminator model
Adds a discriminator to this single nested subdocument.
#### Example:
```
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shape: shapeSchema });
const singleNestedPath = parentSchema.path('shape');
singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
```
mongoose AggregationCursor AggregationCursor
=================
### AggregationCursor()
##### Parameters
* agg «Aggregate»
* options «Object»
##### Inherits:
* «Readable»
An AggregationCursor is a concurrency primitive for processing aggregation results one document at a time. It is analogous to QueryCursor.
An AggregationCursor fulfills the Node.js streams3 API, in addition to several other mechanisms for loading documents from MongoDB one at a time.
Creating an AggregationCursor executes the model's pre aggregate hooks, but **not** the model's post aggregate hooks.
Unless you're an advanced user, do **not** instantiate this class directly. Use [`Aggregate#cursor()`](https://mongoosejs.com/docs/api.html#aggregate_Aggregate-cursor) instead.
### AggregationCursor.prototype.addCursorFlag()
##### Parameters
* flag «String»
* value «Boolean»
##### Returns:
* «AggregationCursor» this
Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). Useful for setting the `noCursorTimeout` and `tailable` flags.
### AggregationCursor.prototype.close()
##### Parameters
* callback «Function»
##### Returns:
* «Promise»
Marks this cursor as closed. Will stop streaming and subsequent calls to `next()` will error.
### AggregationCursor.prototype.eachAsync()
##### Parameters
* fn «Function»
* [options] «Object»
+ [options.parallel] «Number» the number of promises to execute in parallel. Defaults to 1.
* [callback] «Function» executed when all docs have been processed
##### Returns:
* «Promise»
Execute `fn` for every document in the cursor. If `fn` returns a promise, will wait for the promise to resolve before iterating on to the next one. Returns a promise that resolves when done.
### AggregationCursor.prototype.map()
##### Parameters
* fn «Function»
##### Returns:
* «AggregationCursor»
Registers a transform function which subsequently maps documents retrieved via the streams interface or `.next()`
#### Example
```
// Map documents returned by `data` events
Thing.
find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
})
on('data', function(doc) { console.log(doc.foo); });
// Or map documents returned by `.next()`
var cursor = Thing.find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
});
cursor.next(function(error, doc) {
console.log(doc.foo);
});
```
### AggregationCursor.prototype.next()
##### Parameters
* callback «Function»
##### Returns:
* «Promise»
Get the next document from this cursor. Will return `null` when there are no documents left.
mongoose Schema Schema
======
### Schema()
##### Parameters
* [definition] «Object|Schema|Array» Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
* [options] «Object»
##### Inherits:
* «NodeJS EventEmitter http://nodejs.org/api/events.html#events\_class\_events\_eventemitter»
Schema constructor.
#### Example:
```
var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number, children: [child] });
var Tree = mongoose.model('Tree', schema);
// setting schema options
new Schema({ name: String }, { _id: false, autoIndex: false })
```
#### Options:
* [autoIndex](../guide#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
* [autoCreate](../guide#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
* [bufferCommands](../guide#bufferCommands): bool - defaults to true
* [capped](../guide#capped): bool - defaults to false
* [collection](../guide#collection): string - no default
* [id](../guide#id): bool - defaults to true
* [\_id](../guide#_id): bool - defaults to true
* [minimize](../guide#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
* [read](../guide#read): string
* [writeConcern](../guide#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/)
* [shardKey](../guide#shardKey): object - defaults to `null`
* [strict](../guide#strict): bool - defaults to true
* [strictQuery](../guide#strictQuery): bool - defaults to false
* [toJSON](../guide#toJSON) - object - no default
* [toObject](../guide#toObject) - object - no default
* [typeKey](../guide#typeKey) - string - defaults to 'type'
* [typePojoToMixed](../guide#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument
* [useNestedStrict](../guide#useNestedStrict) - boolean - defaults to false
* [validateBeforeSave](../guide#validateBeforeSave) - bool - defaults to `true`
* [versionKey](../guide#versionKey): string - defaults to "\_\_v"
* [collation](../guide#collation): object - defaults to null (which means use no collation)
* [selectPopulatedPaths](../guide#selectPopulatedPaths): boolean - defaults to `true`
* [skipVersioning](../guide#skipVersioning): object - paths to exclude from versioning
* [timestamps](../guide#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
* [storeSubdocValidationError](../guide#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path.
#### Options for Nested Schemas:
* `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths.
#### Note:
*When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent.*
### Schema.Types
##### Type:
* «property»
The various built-in Mongoose Schema Types.
#### Example:
```
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
```
#### Types:
* [String](#schema-string-js)
* [Number](#schema-number-js)
* [Boolean](#schema-boolean-js) | Bool
* [Array](#schema-array-js)
* [Buffer](#schema-buffer-js)
* [Date](#schema-date-js)
* [ObjectId](#schema-objectid-js) | Oid
* [Mixed](#schema-mixed-js)
Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
```
var Mixed = mongoose.Schema.Types.Mixed;
new mongoose.Schema({ _user: Mixed })
```
### Schema.indexTypes
##### Type:
* «property»
The allowed index types
### Schema.prototype.add()
##### Parameters
* obj «Object|Schema» plain object with paths to add, or another schema
* [prefix] «String» path to prefix the newly added paths with
##### Returns:
* «Schema» the Schema instance
Adds key path / schema type pairs to this schema.
#### Example:
```
const ToySchema = new Schema();
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
const TurboManSchema = new Schema();
// You can also `add()` another schema and copy over all paths, virtuals,
// getters, setters, indexes, methods, and statics.
TurboManSchema.add(ToySchema).add({ year: Number });
```
### Schema.prototype.childSchemas
##### Type:
* «property»
Array of child schemas (from document arrays and single nested subdocs) and their corresponding compiled models. Each element of the array is an object with 2 properties: `schema` and `model`.
This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.
### Schema.prototype.clone()
##### Returns:
* «Schema» the cloned schema
Returns a deep copy of the schema
#### Example:
```
const schema = new Schema({ name: String });
const clone = schema.clone();
clone === schema; // false
clone.path('name'); // SchemaString { ... }
```
### Schema.prototype.eachPath()
##### Parameters
* fn «Function» callback function
##### Returns:
* «Schema» this
Iterates the schemas paths similar to Array#forEach.
The callback is passed the pathname and the schemaType instance.
#### Example:
```
const userSchema = new Schema({ name: String, registeredAt: Date });
userSchema.eachPath((pathname, schematype) => {
// Prints twice:
// name SchemaString { ... }
// registeredAt SchemaDate { ... }
console.log(pathname, schematype);
});
```
### Schema.prototype.get()
##### Parameters
* key «String» option name
##### Returns:
* «Any» the option's value
Gets a schema option.
#### Example:
```
schema.get('strict'); // true
schema.set('strict', false);
schema.get('strict'); // false
```
### Schema.prototype.index()
##### Parameters
* fields «Object»
* [options] «Object» Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
+ [options.expires=null] «String» Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
Defines an index (most likely compound) for this schema.
#### Example
```
schema.index({ first: 1, last: -1 })
```
### Schema.prototype.indexes()
##### Returns:
* «Array» list of indexes defined in the schema
Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
#### Example:
```
const userSchema = new Schema({
email: { type: String, required: true, unique: true },
registeredAt: { type: Date, index: true }
});
// [ [ { email: 1 }, { unique: true, background: true } ],
// [ { registeredAt: 1 }, { background: true } ] ]
userSchema.indexes();
```
### Schema.prototype.loadClass()
##### Parameters
* model «Function»
* [virtualsOnly] «Boolean» if truthy, only pulls virtuals from the class, not methods or statics
Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), [statics](http://mongoosejs.com/docs/guide.html#statics), and [methods](http://mongoosejs.com/docs/guide.html#methods).
#### Example:
```
const md5 = require('md5');
const userSchema = new Schema({ email: String });
class UserClass {
// `gravatarImage` becomes a virtual
get gravatarImage() {
const hash = md5(this.email.toLowerCase());
return `[https://www.gravatar.com/avatar/${hash}`](#);
}
// `getProfileUrl()` becomes a document method
getProfileUrl() {
return `[https://mysite.com/${this.email}`](#);
}
// `findByEmail()` becomes a static
static findByEmail(email) {
return this.findOne({ email });
}
}
// `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
// and a `findByEmail()` static
userSchema.loadClass(UserClass);
```
### Schema.prototype.method()
##### Parameters
* method «String|Object» name
* [fn] «Function»
Adds an instance method to documents constructed from Models compiled from this schema.
#### Example
```
var schema = kittySchema = new Schema(..);
schema.method('meow', function () {
console.log('meeeeeoooooooooooow');
})
var Kitty = mongoose.model('Kitty', schema);
var fizz = new Kitty;
fizz.meow(); // meeeeeooooooooooooow
```
If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
```
schema.method({
purr: function () {}
, scratch: function () {}
});
// later
fizz.purr();
fizz.scratch();
```
NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](guide#methods)
### Schema.prototype.obj
##### Type:
* «property»
The original object passed to the schema constructor
#### Example:
```
var schema = new Schema({ a: String }).add({ b: String });
schema.obj; // { a: String }
```
### Schema.prototype.path()
##### Parameters
* path «String»
* constructor «Object»
Gets/sets schema paths.
Sets a path (if arity 2) Gets a path (if arity 1)
#### Example
```
schema.path('name') // returns a SchemaType
schema.path('name', Number) // changes the schemaType of `name` to Number
```
### Schema.prototype.pathType()
##### Parameters
* path «String»
##### Returns:
* «String»
Returns the pathType of `path` for this schema.
Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
#### Example:
```
const s = new Schema({ name: String, nested: { foo: String } });
s.virtual('foo').get(() => 42);
s.pathType('name'); // "real"
s.pathType('nested'); // "nested"
s.pathType('foo'); // "virtual"
s.pathType('fail'); // "adhocOrUndefined"
```
### Schema.prototype.paths
##### Type:
* «property»
The paths defined on this schema. The keys are the top-level paths in this schema, and the values are instances of the SchemaType class.
#### Example:
```
const schema = new Schema({ name: String }, { _id: false });
schema.paths; // { name: SchemaString { ... } }
schema.add({ age: Number });
schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
```
### Schema.prototype.pick()
##### Parameters
* paths «Array» list of paths to pick
* [options] «Object» options to pass to the schema constructor. Defaults to `this.options` if not set.
##### Returns:
* «Schema»
Returns a new schema that has the picked `paths` from this schema.
This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas.
#### Example:
```
const schema = Schema({ name: String, age: Number });
// Creates a new schema with the same `name` path as `schema`,
// but no `age` path.
const newSchema = schema.pick(['name']);
newSchema.path('name'); // SchemaString { ... }
newSchema.path('age'); // undefined
```
### Schema.prototype.plugin()
##### Parameters
* plugin «Function» callback
* [opts] «Object»
Registers a plugin for this schema.
#### Example:
```
const s = new Schema({ name: String });
s.plugin(schema => console.log(schema.path('name').path));
mongoose.model('Test', s); // Prints 'name'
```
### Schema.prototype.post()
##### Parameters
* The «String|RegExp» method name or regular expression to match method name
* [options] «Object»
+ [options.document] «Boolean» If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
+ [options.query] «Boolean» If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
* fn «Function» callback
Defines a post hook for the document
```
var schema = new Schema(..);
schema.post('save', function (doc) {
console.log('this fired after a document was saved');
});
schema.post('find', function(docs) {
console.log('this fired after you ran a find query');
});
schema.post(/Many$/, function(res) {
console.log('this fired after you ran `updateMany()` or `deleteMany()`);
});
var Model = mongoose.model('Model', schema);
var m = new Model(..);
m.save(function(err) {
console.log('this fires after the `post` hook');
});
m.find(function(err, docs) {
console.log('this fires after the post find hook');
});
```
### Schema.prototype.pre()
##### Parameters
* The «String|RegExp» method name or regular expression to match method name
* [options] «Object»
+ [options.document] «Boolean» If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
+ [options.query] «Boolean» If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
* callback «Function»
Defines a pre hook for the document.
#### Example
```
var toySchema = new Schema({ name: String, created: Date });
toySchema.pre('save', function(next) {
if (!this.created) this.created = new Date;
next();
});
toySchema.pre('validate', function(next) {
if (this.name !== 'Woody') this.name = 'Woody';
next();
});
// Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
toySchema.pre(/^find/, function(next) {
console.log(this.getFilter());
});
// Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
console.log(this.getFilter());
});
```
### Schema.prototype.queue()
##### Parameters
* name «String» name of the document method to call later
* args «Array» arguments to pass to the method
Adds a method call to the queue.
#### Example:
```
schema.methods.print = function() { console.log(this); };
schema.queue('print', []); // Print the doc every one is instantiated
const Model = mongoose.model('Test', schema);
new Model({ name: 'test' }); // Prints '{"\_id": ..., "name": "test" }'
```
### Schema.prototype.remove()
##### Parameters
* path «String|Array»
##### Returns:
* «Schema» the Schema instance
Removes the given `path` (or [`paths`]).
#### Example:
```
const schema = new Schema({ name: String, age: Number });
schema.remove('name');
schema.path('name'); // Undefined
schema.path('age'); // SchemaNumber { ... }
```
### Schema.prototype.requiredPaths()
##### Parameters
* invalidate «Boolean» refresh the cache
##### Returns:
* «Array»
Returns an Array of path strings that are required by this schema.
#### Example:
```
const s = new Schema({
name: { type: String, required: true },
age: { type: String, required: true },
notes: String
});
s.requiredPaths(); // [ 'age', 'name' ]
```
### Schema.prototype.set()
##### Parameters
* key «String» option name
* [value] «Object» if not passed, the current option value is returned
Sets/gets a schema option.
#### Example
```
schema.set('strict'); // 'true' by default
schema.set('strict', false); // Sets 'strict' to false
schema.set('strict'); // 'false'
```
### Schema.prototype.static()
##### Parameters
* name «String|Object»
* [fn] «Function»
Adds static "class" methods to Models compiled from this schema.
#### Example
```
const schema = new Schema(..);
// Equivalent to `schema.statics.findByName = function(name) {}`;
schema.static('findByName', function(name) {
return this.find({ name: name });
});
const Drink = mongoose.model('Drink', schema);
await Drink.findByName('LaCroix');
```
If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
### Schema.prototype.virtual()
##### Parameters
* name «String»
* [options] «Object»
+ [options.ref] «String|Model» model name or model instance. Marks this as a [populate virtual](populate#populate-virtuals).
+ [options.localField] «String|Function» Required for populate virtuals. See [populate virtual docs](populate#populate-virtuals) for more information.
+ [options.foreignField] «String|Function» Required for populate virtuals. See [populate virtual docs](populate#populate-virtuals) for more information.
+ [options.justOne=false] «Boolean|Function» Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
+ [options.count=false] «Boolean» Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
##### Returns:
* «VirtualType»
Creates a virtual type with the given name.
### Schema.prototype.virtualpath()
##### Parameters
* name «String»
##### Returns:
* «VirtualType»
Returns the virtual type with the given `name`.
### Schema.reserved
##### Type:
* «property»
Reserved document keys.
Keys in this object are names that are rejected in schema declarations because they conflict with Mongoose functionality. If you create a schema using `new Schema()` with one of these property names, Mongoose will throw an error.
* prototype
* emit
* on
* once
* listeners
* removeListener
* collection
* db
* errors
* init
* isModified
* isNew
* get
* modelName
* save
* schema
* toObject
* validate
* remove
* populated
* \_pres
* \_posts
*NOTE:* Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.
```
var schema = new Schema(..);
schema.methods.init = function () {} // potentially breaking
```
| programming_docs |
mongoose QueryCursor QueryCursor
===========
### QueryCursor()
##### Parameters
* query «Query»
* options «Object» query options passed to `.find()`
##### Inherits:
* «Readable»
A QueryCursor is a concurrency primitive for processing query results one document at a time. A QueryCursor fulfills the Node.js streams3 API, in addition to several other mechanisms for loading documents from MongoDB one at a time.
QueryCursors execute the model's pre find hooks, but **not** the model's post find hooks.
Unless you're an advanced user, do **not** instantiate this class directly. Use [`Query#cursor()`](https://mongoosejs.com/docs/api.html#query_Query-cursor) instead.
### QueryCursor.prototype.addCursorFlag()
##### Parameters
* flag «String»
* value «Boolean»
##### Returns:
* «AggregationCursor» this
Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). Useful for setting the `noCursorTimeout` and `tailable` flags.
### QueryCursor.prototype.close()
##### Parameters
* callback «Function»
##### Returns:
* «Promise»
Marks this cursor as closed. Will stop streaming and subsequent calls to `next()` will error.
### QueryCursor.prototype.eachAsync()
##### Parameters
* fn «Function»
* [options] «Object»
+ [options.parallel] «Number» the number of promises to execute in parallel. Defaults to 1.
* [callback] «Function» executed when all docs have been processed
##### Returns:
* «Promise»
Execute `fn` for every document in the cursor. If `fn` returns a promise, will wait for the promise to resolve before iterating on to the next one. Returns a promise that resolves when done.
### QueryCursor.prototype.map()
##### Parameters
* fn «Function»
##### Returns:
* «QueryCursor»
Registers a transform function which subsequently maps documents retrieved via the streams interface or `.next()`
#### Example
```
// Map documents returned by `data` events
Thing.
find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
})
on('data', function(doc) { console.log(doc.foo); });
// Or map documents returned by `.next()`
var cursor = Thing.find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
});
cursor.next(function(error, doc) {
console.log(doc.foo);
});
```
### QueryCursor.prototype.next()
##### Parameters
* callback «Function»
##### Returns:
* «Promise»
Get the next document from this cursor. Will return `null` when there are no documents left.
### function Object() { [native code] }.prototype.options
##### Type:
* «property»
The `options` passed in to the `QueryCursor` constructor.
mongoose Document Document
========
### Document.prototype.$ignore()
##### Parameters
* path «String» the path to ignore
Don't run validation on this path or persist changes to this path.
#### Example:
```
doc.foo = null;
doc.$ignore('foo');
doc.save(); // changes to foo will not be persisted and validators won't be run
```
### Document.prototype.$isDefault()
##### Parameters
* [path] «String»
##### Returns:
* «Boolean»
Checks if a path is set to its default.
#### Example
```
MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
var m = new MyModel();
m.$isDefault('name'); // true
```
### Document.prototype.$isDeleted()
##### Parameters
* [val] «Boolean» optional, overrides whether mongoose thinks the doc is deleted
##### Returns:
* «Boolean» whether mongoose thinks this doc is deleted.
Getter/setter, determines whether the document was removed or not.
#### Example:
```
product.remove(function (err, product) {
product.$isDeleted(); // true
product.remove(); // no-op, doesn't send anything to the db
product.$isDeleted(false);
product.$isDeleted(); // false
product.remove(); // will execute a remove against the db
})
```
### Document.prototype.$isEmpty()
##### Returns:
* «Boolean»
Returns true if the given path is nullish or only contains empty objects. Useful for determining whether this subdoc will get stripped out by the [minimize option](../guide#minimize).
#### Example:
```
const schema = new Schema({ nested: { foo: String } });
const Model = mongoose.model('Test', schema);
const doc = new Model({});
doc.$isEmpty('nested'); // true
doc.nested.$isEmpty(); // true
doc.nested.foo = 'bar';
doc.$isEmpty('nested'); // false
doc.nested.$isEmpty(); // false
```
### Document.prototype.$locals
##### Type:
* «property»
Empty object that you can use for storing properties on the document. This is handy for passing data to middleware without conflicting with Mongoose internals.
#### Example:
```
schema.pre('save', function() {
// Mongoose will set `isNew` to `false` if `save()` succeeds
this.$locals.wasNew = this.isNew;
});
schema.post('save', function() {
// Prints true if `isNew` was set before `save()`
console.log(this.$locals.wasNew);
});
```
### Document.prototype.$markValid()
##### Parameters
* path «String» the field to mark as valid
Marks a path as valid, removing existing validation errors.
### Document.prototype.$session()
##### Parameters
* [session] «ClientSession» overwrite the current session
##### Returns:
* «ClientSession»
Getter/setter around the session associated with this document. Used to automatically set `session` if you `save()` a doc that you got from a query with an associated session.
#### Example:
```
const session = MyModel.startSession();
const doc = await MyModel.findOne().session(session);
doc.$session() === session; // true
doc.$session(null);
doc.$session() === null; // true
```
If this is a top-level document, setting the session propagates to all child docs.
### Document.prototype.$set()
##### Parameters
* path «String|Object» path or object of key/vals to set
* val «Any» the value to set
* [type] «Schema|String|Number|Buffer|\*» optionally specify a type for "on-the-fly" attributes
* [options] «Object» optionally specify options that modify the behavior of the set
Alias for `set()`, used internally to avoid conflicts
### Document.prototype.depopulate()
##### Parameters
* path «String»
##### Returns:
* «Document» this
Takes a populated field and returns it to its unpopulated state.
#### Example:
```
Model.findOne().populate('author').exec(function (err, doc) {
console.log(doc.author.name); // Dr.Seuss
console.log(doc.depopulate('author'));
console.log(doc.author); // '5144cf8050f071d979c118a7'
})
```
If the path was not populated, this is a no-op.
### Document.prototype.directModifiedPaths()
##### Returns:
* «Array»
Returns the list of paths that have been directly modified. A direct modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` because a child of `a` was directly modified.
#### Example
```
const schema = new Schema({ foo: String, nested: { bar: String } });
const Model = mongoose.model('Test', schema);
await Model.create({ foo: 'original', nested: { bar: 'original' } });
const doc = await Model.findOne();
doc.nested.bar = 'modified';
doc.directModifiedPaths(); // ['nested.bar']
doc.modifiedPaths(); // ['nested', 'nested.bar']
```
### Document.prototype.equals()
##### Parameters
* doc «Document» a document to compare
##### Returns:
* «Boolean»
Returns true if the Document stores the same data as doc.
Documents are considered equal when they have matching `_id`s, unless neither document has an `_id`, in which case this function falls back to using `deepEqual()`.
### Document.prototype.errors
##### Type:
* «property»
Hash containing current validation errors.
### Document.prototype.execPopulate()
##### Parameters
* [callback] «Function» optional callback. If specified, a promise will **not** be returned
##### Returns:
* «Promise» promise that resolves to the document when population is done
Explicitly executes population and returns a promise. Useful for ES2015 integration.
#### Example:
```
var promise = doc.
populate('company').
populate({
path: 'notes',
match: /airline/,
select: 'text',
model: 'modelName'
options: opts
}).
execPopulate();
// summary
doc.execPopulate().then(resolve, reject);
```
### Document.prototype.get()
##### Parameters
* path «String»
* [type] «Schema|String|Number|Buffer|\*» optionally specify a type for on-the-fly attributes
* [options] «Object»
+ [options.virtuals=false] «Boolean» Apply virtuals before getting this path
+ [options.getters=true] «Boolean» If false, skip applying getters and just get the raw value
Returns the value of a path.
#### Example
```
// path
doc.get('age') // 47
// dynamic casting to a string
doc.get('age', String) // "47"
```
### Document.prototype.id
##### Type:
* «property»
The string version of this documents \_id.
#### Note:
This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](../guide#id) of its `Schema` to false at construction time.
```
new Schema({ name: String }, { id: false });
```
### Document.prototype.init()
##### Parameters
* doc «Object» document returned by mongo
Initializes the document without setters or marking anything modified.
Called internally after a document is returned from mongodb. Normally, you do **not** need to call this function on your own.
This function triggers `init` [middleware](../middleware). Note that `init` hooks are [synchronous](../middleware#synchronous).
### Document.prototype.inspect()
Helper for console.log
### Document.prototype.invalidate()
##### Parameters
* path «String» the field to invalidate
* errorMsg «String|Error» the error which states the reason `path` was invalid
* value «Object|String|Number|any» optional invalid value
* [kind] «String» optional `kind` property for the error
##### Returns:
* «ValidationError» the current ValidationError, with all currently invalidated paths
Marks a path as invalid, causing validation to fail.
The `errorMsg` argument will become the message of the `ValidationError`.
The `value` argument (if passed) will be available through the `ValidationError.value` property.
```
doc.invalidate('size', 'must be less than 20', 14);
doc.validate(function (err) {
console.log(err)
// prints
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ size:
{ message: 'must be less than 20',
name: 'ValidatorError',
path: 'size',
type: 'user defined',
value: 14 } } }
})
```
### Document.prototype.isDirectModified()
##### Parameters
* path «String»
##### Returns:
* «Boolean»
Returns true if `path` was directly set and modified, else false.
#### Example
```
doc.set('documents.0.title', 'changed');
doc.isDirectModified('documents.0.title') // true
doc.isDirectModified('documents') // false
```
### Document.prototype.isDirectSelected()
##### Parameters
* path «String»
##### Returns:
* «Boolean»
Checks if `path` was explicitly selected. If no projection, always returns true.
#### Example
```
Thing.findOne().select('nested.name').exec(function (err, doc) {
doc.isDirectSelected('nested.name') // true
doc.isDirectSelected('nested.otherName') // false
doc.isDirectSelected('nested') // false
})
```
### Document.prototype.isInit()
##### Parameters
* path «String»
##### Returns:
* «Boolean»
Checks if `path` was initialized.
### Document.prototype.isModified()
##### Parameters
* [path] «String» optional
##### Returns:
* «Boolean»
Returns true if this document was modified, else false.
If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.
#### Example
```
doc.set('documents.0.title', 'changed');
doc.isModified() // true
doc.isModified('documents') // true
doc.isModified('documents.0.title') // true
doc.isModified('documents otherProp') // true
doc.isDirectModified('documents') // false
```
### Document.prototype.isNew
##### Type:
* «property»
Boolean flag specifying if the document is new.
### Document.prototype.isSelected()
##### Parameters
* path «String»
##### Returns:
* «Boolean»
Checks if `path` was selected in the source query which initialized this document.
#### Example
```
Thing.findOne().select('name').exec(function (err, doc) {
doc.isSelected('name') // true
doc.isSelected('age') // false
})
```
### Document.prototype.markModified()
##### Parameters
* path «String» the path to mark modified
* [scope] «Document» the scope to run validators with
Marks the path as having pending changes to write to the db.
*Very helpful when using [Mixed](schematypes#mixed) types.*
#### Example:
```
doc.mixed.type = 'changed';
doc.markModified('mixed.type');
doc.save() // changes to mixed.type are now persisted
```
### Document.prototype.modifiedPaths()
##### Parameters
* [options] «Object»
+ [options.includeChildren=false] «Boolean» if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`.
##### Returns:
* «Array»
Returns the list of paths that have been modified.
### Document.prototype.overwrite()
##### Parameters
* obj «Object» the object to overwrite this document with
Overwrite all values in this document with the values of `obj`, except for immutable properties. Behaves similarly to `set()`, except for it unsets all properties that aren't in `obj`.
### Document.prototype.populate()
##### Parameters
* [path] «String|Object» The path to populate or an options object
* [callback] «Function» When passed, population is invoked
##### Returns:
* «Document» this
Populates document references, executing the `callback` when complete. If you want to use promises instead, use this function with [`execPopulate()`](#document_Document-execPopulate)
#### Example:
```
doc
.populate('company')
.populate({
path: 'notes',
match: /airline/,
select: 'text',
model: 'modelName'
options: opts
}, function (err, user) {
assert(doc._id === user._id) // the document itself is passed
})
// summary
doc.populate(path) // not executed
doc.populate(options); // not executed
doc.populate(path, callback) // executed
doc.populate(options, callback); // executed
doc.populate(callback); // executed
doc.populate(options).execPopulate() // executed, returns promise
```
#### NOTE:
Population does not occur unless a `callback` is passed *or* you explicitly call `execPopulate()`. Passing the same path a second time will overwrite the previous path options. See [Model.populate()](#model_Model.populate) for explaination of options.
### Document.prototype.populated()
##### Parameters
* path «String»
##### Returns:
* «Array,ObjectId,Number,Buffer,String,undefined»
Gets \_id(s) used during population of the given `path`.
#### Example:
```
Model.findOne().populate('author').exec(function (err, doc) {
console.log(doc.author.name) // Dr.Seuss
console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
})
```
If the path was not populated, undefined is returned.
### Document.prototype.replaceOne()
##### Parameters
* doc «Object»
* options «Object»
* callback «Function»
##### Returns:
* «Query»
Sends a replaceOne command with this document `_id` as the query selector.
#### Valid options:
* same as in [Model.replaceOne](#model_Model.replaceOne)
### Document.prototype.save()
##### Parameters
* [options] «Object» options optional options
+ [options.safe] «Object» (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe)
+ [options.validateBeforeSave] «Boolean» set to false to save without validating.
* [fn] «Function» optional callback
##### Returns:
* «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.
Saves this document.
#### Example:
```
product.sold = Date.now();
product.save(function (err, product) {
if (err) ..
})
```
The callback will receive two parameters
1. `err` if an error occurred
2. `product` which is the saved `product`
As an extra measure of flow control, save will return a Promise.
#### Example:
```
product.save().then(function(product) {
...
});
```
### Document.prototype.schema
##### Type:
* «property»
The documents schema.
### Document.prototype.set()
##### Parameters
* path «String|Object» path or object of key/vals to set
* val «Any» the value to set
* [type] «Schema|String|Number|Buffer|\*» optionally specify a type for "on-the-fly" attributes
* [options] «Object» optionally specify options that modify the behavior of the set
Sets the value of a path, or many paths.
#### Example:
```
// path, value
doc.set(path, value)
// object
doc.set({
path : value
, path2 : {
path : value
}
})
// on-the-fly cast to number
doc.set(path, value, Number)
// on-the-fly cast to string
doc.set(path, value, String)
// changing strict mode behavior
doc.set(path, value, { strict: false });
```
### Document.prototype.toJSON()
##### Parameters
* options «Object»
##### Returns:
* «Object»
The return value of this method is used in calls to JSON.stringify(doc).
This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument.
```
schema.set('toJSON', { virtuals: true })
```
See [schema options](../guide#toJSON) for details.
### Document.prototype.toObject()
##### Parameters
* [options] «Object»
+ [options.getters=false] «Boolean» if true, apply all getters, including virtuals
+ [options.virtuals=false] «Boolean» if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals
+ [options.aliases=true] «Boolean» if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`.
+ [options.minimize=true] «Boolean» if true, omit any empty objects from the output
+ [options.transform=null] «Function|null» if set, mongoose will call this function to allow you to transform the returned object
+ [options.depopulate=false] «Boolean» if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths.
+ [options.versionKey=true] «Boolean» if false, exclude the version key (`__v` by default) from the output
+ [options.flattenMaps=false] «Boolean» if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`.
##### Returns:
* «Object» js object
Converts this document into a plain javascript object, ready for storage in MongoDB.
Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage.
#### Options:
* `getters` apply all getters (path and virtual getters), defaults to false
* `virtuals` apply virtual getters (can override `getters` option), defaults to false
* `minimize` remove empty objects (defaults to true)
* `transform` a transform function to apply to the resulting document before returning
* `depopulate` depopulate any populated paths, replacing them with their original refs (defaults to false)
* `versionKey` whether to include the version key (defaults to true)
#### Getters/Virtuals
Example of only applying path getters
```
doc.toObject({ getters: true, virtuals: false })
```
Example of only applying virtual getters
```
doc.toObject({ virtuals: true })
```
Example of applying both path and virtual getters
```
doc.toObject({ getters: true })
```
To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument.
```
schema.set('toObject', { virtuals: true })
```
#### Transform
We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function.
Transform functions receive three arguments
```
function (doc, ret, options) {}
```
* `doc` The mongoose document which is being converted
* `ret` The plain object representation which has been converted
* `options` The options in use (either schema options or the options passed inline)
#### Example
```
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// remove the \_id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { \_id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
doc.toObject(); // { name: 'Wreck-it Ralph' }
```
With transformations we can do a lot more than remove properties. We can even return completely new customized objects:
```
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
return { movie: ret.name }
}
// without the transformation in the schema
doc.toObject(); // { \_id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
doc.toObject(); // { movie: 'Wreck-it Ralph' }
```
*Note: if a transform function returns `undefined`, the return value will be ignored.*
Transformations may also be applied inline, overridding any transform set in the options:
```
function xform (doc, ret, options) {
return { inline: ret.name, custom: true }
}
// pass the transform as an inline option
doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
```
If you want to skip transformations, use `transform: false`:
```
schema.options.toObject.hide = '\_id';
schema.options.toObject.transform = function (doc, ret, options) {
if (options.hide) {
options.hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret \_id', transform: false });// { \_id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret \_id', transform: true }); // { name: 'Wreck-it Ralph' }
```
If you pass a transform in `toObject()` options, Mongoose will apply the transform to [subdocuments](../subdocs) in addition to the top-level document. Similarly, `transform: false` skips transforms for all subdocuments.
Note that this is behavior is different for transforms defined in the schema
----------------------------------------------------------------------------
if you define a transform in `schema.options.toObject.transform`, that transform will **not** apply to subdocuments.
```
const memberSchema = new Schema({ name: String, email: String });
const groupSchema = new Schema({ members: [memberSchema], name: String, email });
const Group = mongoose.model('Group', groupSchema);
const doc = new Group({
name: 'Engineering',
email: '[[email protected]](mailto:[email protected])',
members: [{ name: 'Val', email: '[[email protected]](mailto:[email protected])' }]
});
// Removes `email` from both top-level document **and** array elements
// { name: 'Engineering', members: [{ name: 'Val' }] }
doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });
```
Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions.
See [schema options](../guide#toObject) for some more details.
*During save, no custom options are applied to the document before being sent to the database.*
### Document.prototype.toString()
Helper for console.log
### Document.prototype.unmarkModified()
##### Parameters
* path «String» the path to unmark modified
Clears the modified state on the specified path.
#### Example:
```
doc.foo = 'bar';
doc.unmarkModified('foo');
doc.save(); // changes to foo will not be persisted
```
### Document.prototype.update()
##### Parameters
* doc «Object»
* options «Object»
* callback «Function»
##### Returns:
* «Query»
Sends an update command with this document `_id` as the query selector.
#### Example:
```
weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
```
#### Valid options:
* same as in [Model.update](#model_Model.update)
### Document.prototype.updateOne()
##### Parameters
* doc «Object»
* options «Object»
* callback «Function»
##### Returns:
* «Query»
Sends an updateOne command with this document `_id` as the query selector.
#### Example:
```
weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
```
#### Valid options:
* same as in [Model.updateOne](#model_Model.updateOne)
### Document.prototype.validate()
##### Parameters
* [pathsToValidate] «Array|String» list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.
* [options] «Object» internal options
* [callback] «Function» optional callback called after validation completes, passing an error if one occurred
##### Returns:
* «Promise» Promise
Executes registered validation rules for this document.
#### Note:
This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`.
#### Example:
```
doc.validate(function (err) {
if (err) handleError(err);
else // validation passed
});
```
### Document.prototype.validateSync()
##### Parameters
* pathsToValidate «Array|string» only validate the given paths
##### Returns:
* «ValidationError,undefined» ValidationError if there are errors during validation, or undefined if there is no error.
Executes registered validation rules (skipping asynchronous validators) for this document.
#### Note:
This method is useful if you need synchronous validation.
#### Example:
```
var err = doc.validateSync();
if (err) {
handleError(err);
} else {
// validation passed
}
```
| programming_docs |
mongoose Aggregate Aggregate
=========
### Aggregate()
##### Parameters
* [pipeline] «Array» aggregation pipeline as an array of objects
Aggregate constructor used for building aggregation pipelines. Do not instantiate this class directly, use [Model.aggregate()](https://mongoosejs.com/docs/api.html#model_Model.aggregate) instead.
#### Example:
```
const aggregate = Model.aggregate([
{ $project: { a: 1, b: 1 } },
{ $skip: 5 }
]);
Model.
aggregate([{ $match: { age: { $gte: 21 }}}]).
unwind('tags').
exec(callback);
```
#### Note:
* The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
* Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database
```
new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
// Do this instead to cast to an ObjectId
new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);
```
### Aggregate.prototype.Symbol.asyncIterator()
Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators) You do not need to call this function explicitly, the JavaScript runtime will call it for you.
#### Example
```
const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
console.log(doc.name);
}
```
Node.js 10.x supports async iterators natively without any flags. You can enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
**Note:** This function is not set if `Symbol.asyncIterator` is undefined. If `Symbol.asyncIterator` is undefined, that means your Node.js version does not support async iterators.
### Aggregate.prototype.addCursorFlag
##### Parameters
* flag «String»
* value «Boolean»
##### Returns:
* «Aggregate» this
##### Type:
* «property»
Sets an option on this aggregation. This function will be deprecated in a future release. Use the [`cursor()`](api#aggregate_Aggregate-cursor), [`collation()`](api#aggregate_Aggregate-collation), etc. helpers to set individual options, or access `agg.options` directly.
Note that MongoDB aggregations [do **not** support the `noCursorTimeout` flag](https://jira.mongodb.org/browse/SERVER-6036), if you try setting that flag with this function you will get a "unrecognized field 'noCursorTimeout'" error.
### Aggregate.prototype.addFields()
##### Parameters
* arg «Object» field specification
##### Returns:
* «Aggregate»
Appends a new $addFields operator to this aggregate pipeline. Requires MongoDB v3.4+ to work
#### Examples:
```
// adding new fields based on existing fields
aggregate.addFields({
newField: '$b.nested'
, plusTen: { $add: ['$val', 10]}
, sub: {
name: '$a'
}
})
// etc
aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });
```
### Aggregate.prototype.allowDiskUse()
##### Parameters
* value «Boolean» Should tell server it can use hard drive to store data during aggregation.
* [tags] «Array» optional tags for this query
Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
#### Example:
```
await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);
```
### Aggregate.prototype.append()
##### Parameters
* ops «Object» operator(s) to append
##### Returns:
* «Aggregate»
Appends new operators to this aggregate pipeline
#### Examples:
```
aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
// or pass an array
var pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
aggregate.append(pipeline);
```
### Aggregate.prototype.catch()
##### Parameters
* [reject] «Function»
##### Returns:
* «Promise»
Executes the query returning a `Promise` which will be resolved with either the doc(s) or rejected with the error. Like [`.then()`](#query_Query-then), but only takes a rejection handler.
### Aggregate.prototype.collation()
##### Parameters
* collation «Object» options
##### Returns:
* «Aggregate» this
Adds a collation
#### Example:
```
Model.aggregate(..).collation({ locale: 'en\_US', strength: 1 }).exec();
```
### Aggregate.prototype.count()
##### Parameters
* the «String» name of the count field
##### Returns:
* «Aggregate»
Appends a new $count operator to this aggregate pipeline.
#### Examples:
```
aggregate.count("userCount");
```
### Aggregate.prototype.cursor()
##### Parameters
* options «Object»
* options.batchSize «Number» set the cursor batch size
+ [options.useMongooseAggCursor] «Boolean» use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics)
##### Returns:
* «Aggregate» this
Sets the cursor option option for the aggregation query (ignored for < 2.6.0). Note the different syntax below: .exec() returns a cursor object, and no callback is necessary.
#### Example:
```
var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
cursor.eachAsync(function(error, doc) {
// use doc
});
```
### Aggregate.prototype.exec()
##### Parameters
* [callback] «Function»
##### Returns:
* «Promise»
Executes the aggregate pipeline on the currently bound Model.
#### Example:
```
aggregate.exec(callback);
// Because a promise is returned, the `callback` is optional.
var promise = aggregate.exec();
promise.then(..);
```
### Aggregate.prototype.explain()
##### Parameters
* callback «Function»
##### Returns:
* «Promise»
Execute the aggregation with explain
#### Example:
```
Model.aggregate(..).explain(callback)
```
### Aggregate.prototype.facet()
##### Parameters
* facet «Object» options
##### Returns:
* «Aggregate» this
Combines multiple aggregation pipelines.
#### Example:
```
Model.aggregate(...)
.facet({
books: [{ groupBy: '$author' }],
price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
})
.exec();
// Output: { books: [...], price: [{...}, {...}] }
```
### Aggregate.prototype.graphLookup()
##### Parameters
* options «Object» to $graphLookup as described in the above link
##### Returns:
* «Aggregate»
Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.
Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified.
#### Examples:
```
// Suppose we have a collection of courses, where a document might look like `{ \_id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ \_id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }`
aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites
```
### Aggregate.prototype.group()
##### Parameters
* arg «Object» $group operator contents
##### Returns:
* «Aggregate»
Appends a new custom $group operator to this aggregate pipeline.
#### Examples:
```
aggregate.group({ _id: "$department" });
```
### Aggregate.prototype.hint()
##### Parameters
* value «Object|String» a hint object or the index name
Sets the hint option for the aggregation query (ignored for < 3.6.0)
#### Example:
```
Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback)
```
### Aggregate.prototype.limit()
##### Parameters
* num «Number» maximum number of records to pass to the next stage
##### Returns:
* «Aggregate»
Appends a new $limit operator to this aggregate pipeline.
#### Examples:
```
aggregate.limit(10);
```
### Aggregate.prototype.lookup()
##### Parameters
* options «Object» to $lookup as described in the above link
##### Returns:
* «Aggregate»
Appends new custom $lookup operator(s) to this aggregate pipeline.
#### Examples:
```
aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '\_id', as: 'users' });
```
### Aggregate.prototype.match()
##### Parameters
* arg «Object» $match operator contents
##### Returns:
* «Aggregate»
Appends a new custom $match operator to this aggregate pipeline.
#### Examples:
```
aggregate.match({ department: { $in: [ "sales", "engineering" ] } });
```
### Aggregate.prototype.model()
##### Parameters
* [model] «Model» the model to which the aggregate is to be bound
##### Returns:
* «Aggregate,Model» if model is passed, will return `this`, otherwise will return the model
Get/set the model that this aggregation will execute on.
#### Example:
```
const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]);
aggregate.model() === MyModel; // true
// Change the model. There's rarely any reason to do this.
aggregate.model(SomeOtherModel);
aggregate.model() === SomeOtherModel; // true
```
### Aggregate.prototype.near()
##### Parameters
* arg «Object»
##### Returns:
* «Aggregate»
Appends a new $geoNear operator to this aggregate pipeline.
#### NOTE:
**MUST** be used as the first operator in the pipeline.
#### Examples:
```
aggregate.near({
near: [40.724, -73.997],
distanceField: "dist.calculated", // required
maxDistance: 0.008,
query: { type: "public" },
includeLocs: "dist.location",
uniqueDocs: true,
num: 5
});
```
### Aggregate.prototype.option()
##### Parameters
* options «Object» keys to merge into current options
* number «[options.maxTimeMS]» limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/)
* boolean «[options.allowDiskUse]» if true, the MongoDB server will use the hard drive to store data during this aggregation
* object «[options.collation]» see [`Aggregate.prototype.collation()`](docs/api#aggregate_Aggregate-collation)
* ClientSession «[options.session]» see [`Aggregate.prototype.session()`](docs/api#aggregate_Aggregate-session)
##### Returns:
* «Aggregate» this
Lets you set arbitrary options, for middleware or plugins.
#### Example:
```
var agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
agg.options; // `{ allowDiskUse: true }`
```
### Aggregate.prototype.options
##### Type:
* «property»
Contains options passed down to the [aggregate command](https://docs.mongodb.com/manual/reference/command/aggregate/).
Supported options are
---------------------
* `readPreference`
* [`cursor`](api#aggregate_Aggregate-cursor)
* [`explain`](api#aggregate_Aggregate-explain)
* [`allowDiskUse`](api#aggregate_Aggregate-allowDiskUse)
* `maxTimeMS`
* `bypassDocumentValidation`
* `raw`
* `promoteLongs`
* `promoteValues`
* `promoteBuffers`
* [`collation`](api#aggregate_Aggregate-collation)
* `comment`
* [`session`](api#aggregate_Aggregate-session)
### Aggregate.prototype.pipeline()
##### Returns:
* «Array»
Returns the current pipeline
#### Example:
```
MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]
```
### Aggregate.prototype.project()
##### Parameters
* arg «Object|String» field specification
##### Returns:
* «Aggregate»
Appends a new $project operator to this aggregate pipeline.
Mongoose query [selection syntax](#query_Query-select) is also supported.
#### Examples:
```
// include a, include b, exclude \_id
aggregate.project("a b -\_id");
// or you may use object notation, useful when
// you have keys already prefixed with a "-"
aggregate.project({a: 1, b: 1, _id: 0});
// reshaping documents
aggregate.project({
newField: '$b.nested'
, plusTen: { $add: ['$val', 10]}
, sub: {
name: '$a'
}
})
// etc
aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
```
### Aggregate.prototype.read()
##### Parameters
* pref «String» one of the listed preference options or their aliases
* [tags] «Array» optional tags for this query
##### Returns:
* «Aggregate» this
Sets the readPreference option for the aggregation query.
#### Example:
```
Model.aggregate(..).read('primaryPreferred').exec(callback)
```
### Aggregate.prototype.readConcern()
##### Parameters
* level «String» one of the listed read concern level or their aliases
##### Returns:
* «Aggregate» this
Sets the readConcern level for the aggregation query.
#### Example:
```
Model.aggregate(..).readConcern('majority').exec(callback)
```
### Aggregate.prototype.redact()
##### Parameters
* expression «Object» redact options or conditional expression
* [thenExpr] «String|Object» true case for the condition
* [elseExpr] «String|Object» false case for the condition
##### Returns:
* «Aggregate» this
Appends a new $redact operator to this aggregate pipeline.
If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`.
#### Example:
```
Model.aggregate(...)
.redact({
$cond: {
if: { $eq: [ '$level', 5 ] },
then: '$$PRUNE',
else: '$$DESCEND'
}
})
.exec();
// $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
Model.aggregate(...)
.redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND')
.exec();
```
### Aggregate.prototype.replaceRoot()
##### Parameters
* the «String|Object» field or document which will become the new root document
##### Returns:
* «Aggregate»
Appends a new $replaceRoot operator to this aggregate pipeline.
Note that the `$replaceRoot` operator requires field strings to start with '$'. If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'. If you are passing in an object the strings in your expression will not be altered.
#### Examples:
```
aggregate.replaceRoot("user");
aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });
```
### Aggregate.prototype.sample()
##### Parameters
* size «Number» number of random documents to pick
##### Returns:
* «Aggregate»
Appends new custom $sample operator(s) to this aggregate pipeline.
#### Examples:
```
aggregate.sample(3); // Add a pipeline that picks 3 random documents
```
### Aggregate.prototype.session()
##### Parameters
* session «ClientSession»
Sets the session for this aggregation. Useful for [transactions](../transactions).
#### Example:
```
const session = await Model.startSession();
await Model.aggregate(..).session(session);
```
### Aggregate.prototype.skip()
##### Parameters
* num «Number» number of records to skip before next stage
##### Returns:
* «Aggregate»
Appends a new $skip operator to this aggregate pipeline.
#### Examples:
```
aggregate.skip(10);
```
### Aggregate.prototype.sort()
##### Parameters
* arg «Object|String»
##### Returns:
* «Aggregate» this
Appends a new $sort operator to this aggregate pipeline.
If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
#### Examples:
```
// these are equivalent
aggregate.sort({ field: 'asc', test: -1 });
aggregate.sort('field -test');
```
### Aggregate.prototype.sortByCount()
##### Parameters
* arg «Object|String»
##### Returns:
* «Aggregate» this
Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name or a pipeline object.
Note that the `$sortByCount` operator requires the new root to start with '$'. Mongoose will prepend '$' if the specified field name doesn't start with '$'.
#### Examples:
```
aggregate.sortByCount('users');
aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })
```
### Aggregate.prototype.then()
##### Parameters
* [resolve] «Function» successCallback
* [reject] «Function» errorCallback
##### Returns:
* «Promise»
Provides promise for aggregate.
#### Example:
```
Model.aggregate(..).then(successCallback, errorCallback);
```
### Aggregate.prototype.unwind()
##### Parameters
* fields «String» the field(s) to unwind
##### Returns:
* «Aggregate»
Appends new custom $unwind operator(s) to this aggregate pipeline.
Note that the `$unwind` operator requires the path name to start with '$'. Mongoose will prepend '$' if the specified field doesn't start '$'.
#### Examples:
```
aggregate.unwind("tags");
aggregate.unwind("a", "b", "c");
```
mongoose SchemaTypeOptions SchemaTypeOptions
=================
### SchemaTypeOptions()
The options defined on a schematype.
#### Example:
```
const schema = new Schema({ name: String });
schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true
```
### SchemaTypeOptions.prototype.cast
##### Type:
* «String»
Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message.
#### Example:
```
const schema = new Schema({
num: {
type: Number,
cast: '{VALUE} is not a valid number'
}
});
// Throws 'CastError: "bad" is not a valid number'
schema.path('num').cast('bad');
const Model = mongoose.model('Test', schema);
const doc = new Model({ num: 'fail' });
const err = doc.validateSync();
err.errors['num']; // 'CastError: "fail" is not a valid number'
```
### SchemaTypeOptions.prototype.default
##### Type:
* «Function|Any»
The default value for this path. If a function, Mongoose executes the function and uses the return value as the default.
### SchemaTypeOptions.prototype.immutable
##### Type:
* «Function|Boolean»
If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will disallow changes to this path once the document is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html).
### SchemaTypeOptions.prototype.index
##### Type:
* «Boolean|Number|Object»
If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will build an index on this path when the model is compiled.
### SchemaTypeOptions.prototype.ref
##### Type:
* «Function|String»
The model that `populate()` should use if populating this path.
### SchemaTypeOptions.prototype.required
##### Type:
* «Function|Boolean»
If true, attach a required validator to this path, which ensures this path path cannot be set to a nullish value. If a function, Mongoose calls the function and only checks for nullish values if the function returns a truthy value.
### SchemaTypeOptions.prototype.select
##### Type:
* «Boolean|Number»
Whether to include or exclude this path by default when loading documents using `find()`, `findOne()`, etc.
### SchemaTypeOptions.prototype.sparse
##### Type:
* «Boolean|Number»
If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will build a sparse index on this path.
### SchemaTypeOptions.prototype.text
##### Type:
* «Boolean|Number|Object»
If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will build a text index on this path.
### SchemaTypeOptions.prototype.type
##### Type:
* «Function|String|Object»
The type to cast this path to.
### SchemaTypeOptions.prototype.unique
##### Type:
* «Boolean|Number»
If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will build a unique index on this path when the model is compiled. [The `unique` option is **not** a validator](../validation#the-unique-option-is-not-a-validator).
### SchemaTypeOptions.prototype.validate
##### Type:
* «Function|Object»
Function or object describing how to validate this schematype.
| programming_docs |
mongoose DocumentArrayPath DocumentArrayPath
=================
### DocumentArrayPath()
##### Parameters
* key «String»
* schema «Schema»
* options «Object»
##### Inherits:
* «SchemaArray»
SubdocsArray SchemaType constructor
### DocumentArrayPath.options
##### Type:
* «property»
Options for all document arrays.
* `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting.
### DocumentArrayPath.prototype.discriminator()
##### Parameters
* name «String»
* schema «Schema» fields to add to the schema for instances of this sub-class
* [value] «String» the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
##### Returns:
* «Function» the constructor Mongoose will use for creating instances of this discriminator model
Adds a discriminator to this document array.
#### Example:
```
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shapes: [shapeSchema] });
const docArrayPath = parentSchema.path('shapes');
docArrayPath.discriminator('Circle', Schema({ radius: Number }));
```
### DocumentArrayPath.schemaName
##### Type:
* «property»
This schema type's name, to defend against minifiers that mangle function names.
mongoose Virtualtype Virtualtype
===========
### VirtualType()
##### Parameters
* options «Object»
+ [options.ref] «string|function» if `ref` is not nullish, this becomes a [populated virtual](../populate#populate-virtuals)
+ [options.localField] «string|function» the local field to populate on if this is a populated virtual.
+ [options.foreignField] «string|function» the foreign field to populate on if this is a populated virtual.
+ [options.justOne=false] «boolean» by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`.
+ [options.getters=false] «boolean» if you set this to `true`, Mongoose will call any custom getters you defined on this virtual
+ [options.count=false] «boolean» if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](api#query_Query-countDocuments)
VirtualType constructor
This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`.
#### Example:
```
const fullname = schema.virtual('fullname');
fullname instanceof mongoose.VirtualType // true
```
### VirtualType.prototype.applyGetters()
##### Parameters
* value «Object»
* doc «Document» The document this virtual is attached to
##### Returns:
* «any» the value after applying all getters
Applies getters to `value`.
### VirtualType.prototype.applySetters()
##### Parameters
* value «Object»
* doc «Document»
##### Returns:
* «any» the value after applying all setters
Applies setters to `value`.
### VirtualType.prototype.get()
##### Parameters
* VirtualType, «Function(Any|» Document)} fn
##### Returns:
* «VirtualType» this
Adds a custom getter to this virtual.
Mongoose calls the getter function with 3 parameters
----------------------------------------------------
* `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`.
* `virtual`: the virtual object you called `.get()` on
* `doc`: the document this virtual is attached to. Equivalent to `this`.
#### Example:
```
var virtual = schema.virtual('fullname');
virtual.get(function(value, virtual, doc) {
return this.name.first + ' ' + this.name.last;
});
```
### VirtualType.prototype.set()
##### Parameters
* VirtualType, «Function(Any|» Document)} fn
##### Returns:
* «VirtualType» this
Adds a custom setter to this virtual.
Mongoose calls the setter function with 3 parameters
----------------------------------------------------
* `value`: the value being set
* `virtual`: the virtual object you're calling `.set()` on
* `doc`: the document this virtual is attached to. Equivalent to `this`.
#### Example:
```
const virtual = schema.virtual('fullname');
virtual.set(function(value, virtual, doc) {
var parts = value.split(' ');
this.name.first = parts[0];
this.name.last = parts[1];
});
const Model = mongoose.model('Test', schema);
const doc = new Model();
// Calls the setter with `value = 'Jean-Luc Picard'`
doc.fullname = 'Jean-Luc Picard';
doc.name.first; // 'Jean-Luc'
doc.name.last; // 'Picard'
```
mongoose Query Query
=====
### Query()
##### Parameters
* [options] «Object»
* [model] «Object»
* [conditions] «Object»
* [collection] «Object» Mongoose collection
Query constructor used for building queries. You do not need to instantiate a `Query` directly. Instead use Model functions like [`Model.find()`](https://mongoosejs.com/docs/api.html#find_find).
#### Example:
```
const query = MyModel.find(); // `query` is an instance of `Query`
query.setOptions({ lean : true });
query.collection(MyModel.collection);
query.where('age').gte(21).exec(callback);
// You can instantiate a query directly. There is no need to do
// this unless you're an advanced user with a very good reason to.
const query = new mongoose.Query();
```
### Query.prototype.$where()
##### Parameters
* js «String|Function» javascript string or function
##### Returns:
* «Query» this
Specifies a javascript function or expression to pass to MongoDBs query system.
#### Example
```
query.$where('this.comments.length === 10 || this.name.length === 5')
// or
query.$where(function () {
return this.comments.length === 10 || this.name.length === 5;
})
```
#### NOTE:
Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
### Query.prototype.Symbol.asyncIterator()
Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators) This function *only* works for `find()` queries. You do not need to call this function explicitly, the JavaScript runtime will call it for you.
#### Example
```
for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
console.log(doc.name);
}
```
Node.js 10.x supports async iterators natively without any flags. You can enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
**Note:** This function is not if `Symbol.asyncIterator` is undefined. If `Symbol.asyncIterator` is undefined, that means your Node.js version does not support async iterators.
### Query.prototype.all()
##### Parameters
* [path] «String»
* val «Array»
Specifies an `$all` query condition.
When called with one argument, the most recent path passed to `where()` is used.
#### Example:
```
MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
// Equivalent:
MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
```
### Query.prototype.and()
##### Parameters
* array «Array» array of conditions
##### Returns:
* «Query» this
Specifies arguments for a `$and` condition.
#### Example
```
query.and([{ color: 'green' }, { status: 'ok' }])
```
### Query.prototype.batchSize()
##### Parameters
* val «Number»
Specifies the batchSize option.
#### Example
```
query.batchSize(100)
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.box()
##### Parameters
* val «Object»
* Upper «[Array]» Right Coords
##### Returns:
* «Query» this
Specifies a `$box` condition
#### Example
```
var lowerLeft = [40.73083, -73.99756]
var upperRight= [40.741404, -73.988135]
query.where('loc').within().box(lowerLeft, upperRight)
query.box({ ll : lowerLeft, ur : upperRight })
```
### Query.prototype.cast()
##### Parameters
* [model] «Model» the model to cast to. If not set, defaults to `this.model`
* [obj] «Object»
##### Returns:
* «Object»
Casts this query to the schema of `model`
#### Note
If `obj` is present, it is cast instead of this query.
### Query.prototype.catch()
##### Parameters
* [reject] «Function»
##### Returns:
* «Promise»
Executes the query returning a `Promise` which will be resolved with either the doc(s) or rejected with the error. Like `.then()`, but only takes a rejection handler.
### Query.prototype.center()
*DEPRECATED* Alias for [circle](#query_Query-circle)
**Deprecated.** Use [circle](#query_Query-circle) instead.
### Query.prototype.centerSphere()
##### Parameters
* [path] «String»
* val «Object»
##### Returns:
* «Query» this
*DEPRECATED* Specifies a `$centerSphere` condition
**Deprecated.** Use [circle](#query_Query-circle) instead.
#### Example
```
var area = { center: [50, 50], radius: 10 };
query.where('loc').within().centerSphere(area);
```
### Query.prototype.circle()
##### Parameters
* [path] «String»
* area «Object»
##### Returns:
* «Query» this
Specifies a `$center` or `$centerSphere` condition.
#### Example
```
var area = { center: [50, 50], radius: 10, unique: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);
// spherical calculations
var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);
```
### Query.prototype.collation()
##### Parameters
* value «Object»
##### Returns:
* «Query» this
Adds a collation to this op (MongoDB 3.4 and up)
### Query.prototype.comment()
##### Parameters
* val «String»
Specifies the `comment` option.
#### Example
```
query.comment('login query')
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.count()
##### Parameters
* [filter] «Object» count documents that match this object
* [callback] «Function» optional params are (error, count)
##### Returns:
* «Query» this
Specifies this query as a `count` query.
This method is deprecated. If you want to count the number of documents in a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](https://mongoosejs.com/docs/api.html#query_Query-estimatedDocumentCount) instead. Otherwise, use the [`countDocuments()`](https://mongoosejs.com/docs/api.html#query_Query-countDocuments) function instead.
Passing a `callback` executes the query.
This function triggers the following middleware.
* `count()`
#### Example:
```
var countQuery = model.where({ 'color': 'black' }).count();
query.count({ color: 'black' }).count(callback)
query.count({ color: 'black' }, callback)
query.where('color', 'black').count(function (err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
})
```
### Query.prototype.countDocuments()
##### Parameters
* [filter] «Object» mongodb selector
* [callback] «Function» optional params are (error, count)
##### Returns:
* «Query» this
Specifies this query as a `countDocuments()` query. Behaves like `count()`, except it always does a full collection scan when passed an empty filter `{}`.
There are also minor differences in how `countDocuments()` handles [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). versus `count()`.
Passing a `callback` executes the query.
This function triggers the following middleware.
* `countDocuments()`
#### Example:
```
const countQuery = model.where({ 'color': 'black' }).countDocuments();
query.countDocuments({ color: 'black' }).count(callback);
query.countDocuments({ color: 'black' }, callback);
query.where('color', 'black').countDocuments(function(err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
});
```
The `countDocuments()` function is similar to `count()`, but there are a [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). Below are the operators that `count()` supports but `countDocuments()` does not, and the suggested replacement:
* `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
* `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center)
* `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)
### Query.prototype.cursor()
##### Parameters
* [options] «Object»
##### Returns:
* «QueryCursor»
Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
The `.cursor()` function triggers pre find hooks, but **not** post find hooks.
#### Example
```
// There are 2 ways to use a cursor. First, as a stream:
Thing.
find({ name: /^hello/ }).
cursor().
on('data', function(doc) { console.log(doc); }).
on('end', function() { console.log('Done!'); });
// Or you can use `.next()` to manually get the next doc in the stream.
// `.next()` returns a promise, so you can use promises or callbacks.
var cursor = Thing.find({ name: /^hello/ }).cursor();
cursor.next(function(error, doc) {
console.log(doc);
});
// Because `.next()` returns a promise, you can use co
// to easily iterate through all documents without loading them
// all into memory.
co(function\*() {
const cursor = Thing.find({ name: /^hello/ }).cursor();
for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
console.log(doc);
}
});
```
#### Valid options
* `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
### Query.prototype.deleteMany()
##### Parameters
* [filter] «Object|Query» mongodb selector
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function» optional params are (error, mongooseDeleteResult)
##### Returns:
* «Query» this
Declare and/or execute this query as a `deleteMany()` operation. Works like remove, except it deletes *every* document that matches `filter` in the collection, regardless of the value of `single`.
This function does not trigger any middleware
#### Example
```
Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback)
Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next)
```
This function calls the MongoDB driver's [`Collection#deleteMany()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). The returned [promise](../queries) resolves to an object that contains 3 properties:
* `ok`: `1` if no errors occurred
* `deletedCount`: the number of documents deleted
* `n`: the number of documents deleted. Equal to `deletedCount`.
#### Example
```
const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
// `0` if no docs matched the filter, number of docs deleted otherwise
res.deletedCount;
```
### Query.prototype.deleteOne()
##### Parameters
* [filter] «Object|Query» mongodb selector
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function» optional params are (error, mongooseDeleteResult)
##### Returns:
* «Query» this
Declare and/or execute this query as a `deleteOne()` operation. Works like remove, except it deletes at most one document regardless of the `single` option.
This function does not trigger any middleware.
#### Example
```
Character.deleteOne({ name: 'Eddard Stark' }, callback);
Character.deleteOne({ name: 'Eddard Stark' }).then(next);
```
This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). The returned [promise](../queries) resolves to an object that contains 3 properties:
* `ok`: `1` if no errors occurred
* `deletedCount`: the number of documents deleted
* `n`: the number of documents deleted. Equal to `deletedCount`.
#### Example
```
const res = await Character.deleteOne({ name: 'Eddard Stark' });
// `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }`
res.deletedCount;
```
### Query.prototype.distinct()
##### Parameters
* [field] «String»
* [filter] «Object|Query»
* [callback] «Function» optional params are (error, arr)
##### Returns:
* «Query» this
Declares or executes a distinct() operation.
Passing a `callback` executes the query.
This function does not trigger any middleware.
#### Example
```
distinct(field, conditions, callback)
distinct(field, conditions)
distinct(field, callback)
distinct(field)
distinct(callback)
distinct()
```
### Query.prototype.elemMatch()
##### Parameters
* path «String|Object|Function»
* filter «Object|Function»
##### Returns:
* «Query» this
Specifies an `$elemMatch` condition
#### Example
```
query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
query.elemMatch('comment', function (elem) {
elem.where('author').equals('autobot');
elem.where('votes').gte(5);
})
query.where('comment').elemMatch(function (elem) {
elem.where({ author: 'autobot' });
elem.where('votes').gte(5);
})
```
### Query.prototype.equals()
##### Parameters
* val «Object»
##### Returns:
* «Query» this
Specifies the complementary comparison value for paths specified with `where()`
#### Example
```
User.where('age').equals(49);
// is the same as
User.where('age', 49);
```
### Query.prototype.error()
##### Parameters
* err «Error|null» if set, `exec()` will fail fast before sending the query to MongoDB
##### Returns:
* «Query» this
Gets/sets the error flag on this query. If this flag is not null or undefined, the `exec()` promise will reject without executing.
#### Example:
```
Query().error(); // Get current error value
Query().error(null); // Unset the current error
Query().error(new Error('test')); // `exec()` will resolve with test
Schema.pre('find', function() {
if (!this.getQuery().userId) {
this.error(new Error('Not allowed to query without setting userId'));
}
});
```
Note that query casting runs **after** hooks, so cast errors will override custom errors.
#### Example:
```
var TestSchema = new Schema({ num: Number });
var TestModel = db.model('Test', TestSchema);
TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
// `error` will be a cast error because `num` failed to cast
});
```
### Query.prototype.estimatedDocumentCount()
##### Parameters
* [options] «Object» passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount)
* [callback] «Function» optional params are (error, count)
##### Returns:
* «Query» this
Specifies this query as a `estimatedDocumentCount()` query. Faster than using `countDocuments()` for large collections because `estimatedDocumentCount()` uses collection metadata rather than scanning the entire collection.
`estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()` is equivalent to `Model.find().estimatedDocumentCount()`
This function triggers the following middleware.
* `estimatedDocumentCount()`
#### Example:
```
await Model.find().estimatedDocumentCount();
```
### Query.prototype.exec()
##### Parameters
* [operation] «String|Function»
* [callback] «Function» optional params depend on the function being called
##### Returns:
* «Promise»
Executes the query
#### Examples:
```
var promise = query.exec();
var promise = query.exec('update');
query.exec(callback);
query.exec('find', callback);
```
### Query.prototype.exists()
##### Parameters
* [path] «String»
* val «Number»
##### Returns:
* «Query» this
Specifies an `$exists` condition
#### Example
```
// { name: { $exists: true }}
Thing.where('name').exists()
Thing.where('name').exists(true)
Thing.find().exists('name')
// { name: { $exists: false }}
Thing.where('name').exists(false);
Thing.find().exists('name', false);
```
### Query.prototype.explain()
##### Parameters
* [verbose] «String» The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner'
##### Returns:
* «Query» this
Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), which makes this query return detailed execution stats instead of the actual query result. This method is useful for determining what index your queries use.
Calling `query.explain(v)` is equivalent to `query.setOption({ explain: v })`
#### Example:
```
const query = new Query();
const res = await query.find({ a: 1 }).explain('queryPlanner');
console.log(res);
```
### Query.prototype.find()
##### Parameters
* [filter] «Object|ObjectId» mongodb selector. If not specified, returns all documents.
* [callback] «Function»
##### Returns:
* «Query» this
Find all documents that match `selector`. The result will be an array of documents.
If there are too many documents in the result to fit in memory, use [`Query.prototype.cursor()`](api#query_Query-cursor)
#### Example
```
// Using async/await
const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
// Using callbacks
Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});
```
### Query.prototype.findOne()
##### Parameters
* [filter] «Object» mongodb selector
* [projection] «Object» optional fields to return
* [options] «Object» see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function» optional params are (error, document)
##### Returns:
* «Query» this
Declares the query a findOne operation. When executed, the first found document is passed to the callback.
Passing a `callback` executes the query. The result of the query is a single document.
* *Note:* `conditions` is optional, and if `conditions` is null or undefined, mongoose will send an empty `findOne` command to MongoDB, which will return an arbitrary document. If you're querying by `_id`, use `Model.findById()` instead.
This function triggers the following middleware.
* `findOne()`
#### Example
```
var query = Kitten.where({ color: 'white' });
query.findOne(function (err, kitten) {
if (err) return handleError(err);
if (kitten) {
// doc may be null if no document matched
}
});
```
### Query.prototype.findOneAndDelete()
##### Parameters
* [conditions] «Object»
* [options] «Object»
+ [options.rawResult] «Boolean» if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
* [callback] «Function» optional params are (error, document)
##### Returns:
* «Query» this
Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command.
Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes if `callback` is passed.
This function triggers the following middleware.
* `findOneAndDelete()`
This function differs slightly from `Model.findOneAndRemove()` in that `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), as opposed to a `findOneAndDelete()` command. For most mongoose use cases, this distinction is purely pedantic. You should use `findOneAndDelete()` unless you have a good reason not to.
#### Available options
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
#### Callback Signature
```
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
```
#### Examples
```
A.where().findOneAndDelete(conditions, options, callback) // executes
A.where().findOneAndDelete(conditions, options) // return Query
A.where().findOneAndDelete(conditions, callback) // executes
A.where().findOneAndDelete(conditions) // returns Query
A.where().findOneAndDelete(callback) // executes
A.where().findOneAndDelete() // returns Query
```
### Query.prototype.findOneAndRemove()
##### Parameters
* [conditions] «Object»
* [options] «Object»
+ [options.rawResult] «Boolean» if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
* [callback] «Function» optional params are (error, document)
##### Returns:
* «Query» this
Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
Finds a matching document, removes it, passing the found document (if any) to the callback. Executes if `callback` is passed.
This function triggers the following middleware.
* `findOneAndRemove()`
#### Available options
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
#### Callback Signature
```
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
```
#### Examples
```
A.where().findOneAndRemove(conditions, options, callback) // executes
A.where().findOneAndRemove(conditions, options) // return Query
A.where().findOneAndRemove(conditions, callback) // executes
A.where().findOneAndRemove(conditions) // returns Query
A.where().findOneAndRemove(callback) // executes
A.where().findOneAndRemove() // returns Query
```
### Query.prototype.findOneAndReplace()
##### Parameters
* [filter] «Object»
* [replacement] «Object»
* [options] «Object»
+ [options.rawResult] «Boolean» if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* [callback] «Function» optional params are (error, document)
##### Returns:
* «Query» this
Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command.
Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes if `callback` is passed.
This function triggers the following middleware.
* `findOneAndReplace()`
#### Available options
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
#### Callback Signature
```
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
```
#### Examples
```
A.where().findOneAndReplace(filter, replacement, options, callback); // executes
A.where().findOneAndReplace(filter, replacement, options); // return Query
A.where().findOneAndReplace(filter, replacement, callback); // executes
A.where().findOneAndReplace(filter); // returns Query
A.where().findOneAndReplace(callback); // executes
A.where().findOneAndReplace(); // returns Query
```
### Query.prototype.findOneAndUpdate()
##### Parameters
* [filter] «Object|Query»
* [doc] «Object»
* [options] «Object»
+ [options.rawResult] «Boolean» if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
+ [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* [callback] «Function» optional params are (error, doc), *unless* `rawResult` is used, in which case params are (error, writeOpResult)
##### Returns:
* «Query» this
Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed.
This function triggers the following middleware.
* `findOneAndUpdate()`
#### Available options
* `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
* `upsert`: bool - creates the object if it doesn't exist. defaults to false.
* `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `runValidators`: if true, runs [update validators](../validation#update-validators) on this command. Update validators validate the update operation against the model's schema.
* `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
#### Callback Signature
```
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
```
#### Examples
```
query.findOneAndUpdate(conditions, update, options, callback) // executes
query.findOneAndUpdate(conditions, update, options) // returns Query
query.findOneAndUpdate(conditions, update, callback) // executes
query.findOneAndUpdate(conditions, update) // returns Query
query.findOneAndUpdate(update, callback) // returns Query
query.findOneAndUpdate(update) // returns Query
query.findOneAndUpdate(callback) // executes
query.findOneAndUpdate() // returns Query
```
### Query.prototype.geometry()
##### Parameters
* object «Object» Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
##### Returns:
* «Query» this
Specifies a `$geometry` condition
#### Example
```
var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
// or
var polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
// or
var polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
// or
query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
```
The argument is assigned to the most recent path passed to `where()`.
#### NOTE:
`geometry()` **must** come after either `intersects()` or `within()`.
The `object` argument must contain `type` and `coordinates` properties. - type {String} - coordinates {Array}
### Query.prototype.get()
##### Parameters
* path «String|Object» path or object of key/value pairs to set
* [val] «Any» the value to set
##### Returns:
* «Query» this
For update operations, returns the value of a path in the update's `$set`. Useful for writing getters/setters that can work with both update operations and `save()`.
#### Example:
```
const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } });
query.get('name'); // 'Jean-Luc Picard'
```
### Query.prototype.getFilter()
##### Returns:
* «Object» current query filter
Returns the current query filter (also known as conditions) as a POJO.
#### Example:
```
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getFilter(); // { a: 1, b: { $gt: 2 } }
```
### Query.prototype.getOptions()
##### Returns:
* «Object» the options
Gets query options.
#### Example:
```
var query = new Query();
query.limit(10);
query.setOptions({ maxTimeMS: 1000 })
query.getOptions(); // { limit: 10, maxTimeMS: 1000 }
```
### Query.prototype.getPopulatedPaths()
##### Returns:
* «Array» an array of strings representing populated paths
Gets a list of paths to be populated by this query
#### Example:
```
bookSchema.pre('findOne', function() {
let keys = this.getPopulatedPaths(); // ['author']
});
...
Book.findOne({}).populate('author');
```
#### Example:
```
// Deep populate
const q = L1.find().populate({
path: 'level2',
populate: { path: 'level3' }
});
q.getPopulatedPaths(); // ['level2', 'level2.level3']
```
### Query.prototype.getQuery()
##### Returns:
* «Object» current query filter
Returns the current query filter. Equivalent to `getFilter()`.
You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()` will likely be deprecated in a future release.
#### Example:
```
var query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getQuery(); // { a: 1, b: { $gt: 2 } }
```
### Query.prototype.getUpdate()
##### Returns:
* «Object» current update operations
Returns the current update operations as a JSON object.
#### Example:
```
var query = new Query();
query.update({}, { $set: { a: 5 } });
query.getUpdate(); // { $set: { a: 5 } }
```
### Query.prototype.gt()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `$gt` query condition.
When called with one argument, the most recent path passed to `where()` is used.
#### Example
```
Thing.find().where('age').gt(21)
// or
Thing.find().gt('age', 21)
```
### Query.prototype.gte()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `$gte` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.hint()
##### Parameters
* val «Object» a hint object
##### Returns:
* «Query» this
Sets query hints.
#### Example
```
query.hint({ indexA: 1, indexB: -1})
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.in()
##### Parameters
* [path] «String»
* val «Number»
Specifies an `$in` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.intersects()
##### Parameters
* [arg] «Object»
##### Returns:
* «Query» this
Declares an intersects query for `geometry()`.
#### Example
```
query.where('path').intersects().geometry({
type: 'LineString'
, coordinates: [[180.0, 11.0], [180, 9.0]]
})
query.where('path').intersects({
type: 'LineString'
, coordinates: [[180.0, 11.0], [180, 9.0]]
})
```
#### NOTE:
**MUST** be used after `where()`.
#### NOTE:
In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
### Query.prototype.j()
##### Parameters
* val «boolean»
##### Returns:
* «Query» this
Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal.
This option is only valid for operations that write to the database
-------------------------------------------------------------------
* `deleteOne()`
* `deleteMany()`
* `findOneAndDelete()`
* `findOneAndReplace()`
* `findOneAndUpdate()`
* `remove()`
* `update()`
* `updateOne()`
* `updateMany()`
Defaults to the schema's [`writeConcern.j` option](../guide#writeConcern)
#### Example:
```
await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);
```
### Query.prototype.lean()
##### Parameters
* bool «Boolean|Object» defaults to true
##### Returns:
* «Query» this
Sets the lean option.
Documents returned from queries with the `lean` option enabled are plain javascript objects, not [Mongoose Documents](#document-js). They have no `save` method, getters/setters, virtuals, or other Mongoose features.
#### Example:
```
new Query().lean() // true
new Query().lean(true)
new Query().lean(false)
const docs = await Model.find().lean();
docs[0] instanceof mongoose.Document; // false
```
[Lean is great for high-performance, read-only cases](../tutorials/lean), especially when combined with [cursors](../queries#streaming).
If you need virtuals, getters/setters, or defaults with `lean()`, you need to use a plugin. See:
* [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals)
* [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters)
* [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults)
### Query.prototype.limit()
##### Parameters
* val «Number»
Specifies the maximum number of documents the query will return.
#### Example
```
query.limit(20)
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.lt()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `$lt` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.lte()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `$lte` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.map()
##### Parameters
* fn «Function» function to run to transform the query result
##### Returns:
* «Query» this
Runs a function `fn` and treats the return value of `fn` as the new value for the query to resolve to.
Any functions you pass to `map()` will run **after** any post hooks.
#### Example:
```
const res = await MyModel.findOne().map(res => {
// Sets a `loadedAt` property on the doc that tells you the time the
// document was loaded.
return res == null ?
res :
Object.assign(res, { loadedAt: new Date() });
});
```
### Query.prototype.maxDistance()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `maxDistance` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.maxScan()
##### Parameters
* val «Number»
Specifies the maxScan option.
#### Example
```
query.maxScan(100)
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.maxTimeMS()
##### Parameters
* [ms] «Number» The number of milliseconds
##### Returns:
* «Query» this
Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) option. This will tell the MongoDB server to abort if the query or write op has been running for more than `ms` milliseconds.
Calling `query.maxTimeMS(v)` is equivalent to `query.setOption({ maxTimeMS: v })`
#### Example:
```
const query = new Query();
// Throws an error 'operation exceeded time limit' as long as there's
// >= 1 doc in the queried collection
const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100);
```
### Query.prototype.maxscan()
*DEPRECATED* Alias of `maxScan`
### Query.prototype.merge()
##### Parameters
* source «Query|Object»
##### Returns:
* «Query» this
Merges another Query or conditions object into this one.
When a Query is passed, conditions, field selection and options are merged.
### Query.prototype.mod()
##### Parameters
* [path] «String»
* val «Array» must be of length 2, first element is `divisor`, 2nd element is `remainder`.
##### Returns:
* «Query» this
Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`.
#### Example
```
// All find products whose inventory is odd
Product.find().mod('inventory', [2, 1]);
Product.find().where('inventory').mod([2, 1]);
// This syntax is a little strange, but supported.
Product.find().where('inventory').mod(2, 1);
```
### Query.prototype.mongooseOptions()
##### Parameters
* options «Object» if specified, overwrites the current options
##### Returns:
* «Object» the options
Getter/setter around the current mongoose-specific options for this query Below are the current Mongoose-specific options.
* `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](https://mongoosejs.com/docs/api.html#query_Query-populate)
* `lean`: if truthy, Mongoose will not [hydrate](https://mongoosejs.com/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](https://mongoosejs.com/docs/api.html#query_Query-lean) for more information.
* `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](../guide#strict) for more information.
* `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](../guide#strictQuery) for more information.
* `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](../deprecations#-findandmodify-)
* `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](https://mongoosejs.com/docs/api.html#query_Query-nearSphere)
Mongoose maintains a separate object for internal options because Mongoose sends `Query.prototype.options` to the MongoDB server, and the above options are not relevant for the MongoDB server.
### Query.prototype.mongooseOptions()
##### Parameters
* «public»
##### Returns:
* «Object» Mongoose-specific options
Returns an object containing the Mongoose-specific options for this query, including `lean` and `populate`.
Mongoose-specific options are different from normal options (`sort`, `limit`, etc.) because they are **not** sent to the MongoDB server.
#### Example:
```
const q = new Query();
q.mongooseOptions().lean; // undefined
q.lean();
q.mongooseOptions().lean; // true
```
This function is useful for writing [query middleware](../middleware).
Below is a full list of properties the return value from this function may have
-------------------------------------------------------------------------------
* `populate`
* `lean`
* `omitUndefined`
* `strict`
* `nearSphere`
* `useFindAndModify`
### Query.prototype.ne()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `$ne` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.near()
##### Parameters
* [path] «String»
* val «Object»
##### Returns:
* «Query» this
Specifies a `$near` or `$nearSphere` condition
These operators return documents sorted by distance.
#### Example
```
query.where('loc').near({ center: [10, 10] });
query.where('loc').near({ center: [10, 10], maxDistance: 5 });
query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
query.near('loc', { center: [10, 10], maxDistance: 5 });
```
### Query.prototype.nearSphere()
*DEPRECATED* Specifies a `$nearSphere` condition
#### Example
```
query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
```
**Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
#### Example
```
query.where('loc').near({ center: [10, 10], spherical: true });
```
### Query.prototype.nin()
##### Parameters
* [path] «String»
* val «Number»
Specifies an `$nin` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.nor()
##### Parameters
* array «Array» array of conditions
##### Returns:
* «Query» this
Specifies arguments for a `$nor` condition.
#### Example
```
query.nor([{ color: 'green' }, { status: 'ok' }])
```
### Query.prototype.or()
##### Parameters
* array «Array» array of conditions
##### Returns:
* «Query» this
Specifies arguments for an `$or` condition.
#### Example
```
query.or([{ color: 'red' }, { status: 'emergency' }])
```
### Query.prototype.orFail()
##### Parameters
* [err] «Function|Error» optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError`
##### Returns:
* «Query» this
Make this query throw an error if no documents match the given `filter`. This is handy for integrating with async/await, because `orFail()` saves you an extra `if` statement to check if no document was found.
#### Example:
```
// Throws if no doc returned
await Model.findOne({ foo: 'bar' }).orFail();
// Throws if no document was updated
await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
// Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
// Throws "Not found" error if no document was found
await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
orFail(() => Error('Not found'));
```
### Query.prototype.polygon()
##### Parameters
* [path] «String|Array»
+ [coordinatePairs...] «Array|Object»
##### Returns:
* «Query» this
Specifies a `$polygon` condition
#### Example
```
query.where('loc').within().polygon([10,20], [13, 25], [7,15])
query.polygon('loc', [10,20], [13, 25], [7,15])
```
### Query.prototype.populate()
##### Parameters
* path «Object|String» either the path to populate or an object specifying all parameters
* [select] «Object|String» Field selection for the population query
* [model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field.
* [match] «Object» Conditions for the population query
* [options] «Object» Options for the population query (sort, etc)
+ [options.path=null] «String» The path to populate.
+ [options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries.
+ [options.getters=false] «boolean» if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](../schematypes#schematype-options).
+ [options.clone=false] «boolean» When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
+ [options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object.
+ [options.options=null] «Object» Additional options like `limit` and `lean`.
##### Returns:
* «Query» this
Specifies paths which should be populated with other documents.
#### Example:
```
Kitten.findOne().populate('owner').exec(function (err, kitten) {
console.log(kitten.owner.name) // Max
})
Kitten.find().populate({
path: 'owner',
select: 'name',
match: { color: 'black' },
options: { sort: { name: -1 } }
}).exec(function (err, kittens) {
console.log(kittens[0].owner.name) // Zoopa
})
// alternatively
Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
console.log(kittens[0].owner.name) // Zoopa
})
```
Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.
### Query.prototype.projection()
##### Parameters
* arg «Object|null»
##### Returns:
* «Object» the current projection
Get/set the current projection (AKA fields). Pass `null` to remove the current projection.
Unlike `projection()`, the `select()` function modifies the current projection in place. This function overwrites the existing projection.
#### Example:
```
const q = Model.find();
q.projection(); // null
q.select('a b');
q.projection(); // { a: 1, b: 1 }
q.projection({ c: 1 });
q.projection(); // { c: 1 }
q.projection(null);
q.projection(); // null
```
### Query.prototype.read()
##### Parameters
* pref «String» one of the listed preference options or aliases
* [tags] «Array» optional tags for this query
##### Returns:
* «Query» this
Determines the MongoDB nodes from which to read.
#### Preferences:
```
primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
secondary Read from secondary if available, otherwise error.
primaryPreferred Read from primary if available, otherwise a secondary.
secondaryPreferred Read from a secondary if available, otherwise read from the primary.
nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.
```
Aliases
```
p primary
pp primaryPreferred
s secondary
sp secondaryPreferred
n nearest
```
#### Example:
```
new Query().read('primary')
new Query().read('p') // same as primary
new Query().read('primaryPreferred')
new Query().read('pp') // same as primaryPreferred
new Query().read('secondary')
new Query().read('s') // same as secondary
new Query().read('secondaryPreferred')
new Query().read('sp') // same as secondaryPreferred
new Query().read('nearest')
new Query().read('n') // same as nearest
// read from secondaries with matching tags
new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
```
Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
### Query.prototype.readConcern()
##### Parameters
* level «String» one of the listed read concern level or their aliases
##### Returns:
* «Query» this
Sets the readConcern option for the query.
#### Example:
```
new Query().readConcern('local')
new Query().readConcern('l') // same as local
new Query().readConcern('available')
new Query().readConcern('a') // same as available
new Query().readConcern('majority')
new Query().readConcern('m') // same as majority
new Query().readConcern('linearizable')
new Query().readConcern('lz') // same as linearizable
new Query().readConcern('snapshot')
new Query().readConcern('s') // same as snapshot
```
#### Read Concern Level:
```
local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.
```
Aliases
```
l local
a available
m majority
lz linearizable
s snapshot
```
Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).
### Query.prototype.regex()
##### Parameters
* [path] «String»
* val «String|RegExp»
Specifies a `$regex` query condition.
When called with one argument, the most recent path passed to `where()` is used.
### Query.prototype.remove()
##### Parameters
* [filter] «Object|Query» mongodb selector
* [callback] «Function» optional params are (error, mongooseDeleteResult)
##### Returns:
* «Query» this
Declare and/or execute this query as a remove() operation. `remove()` is deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) or [`deleteMany()`](#query_Query-deleteMany) instead.
This function does not trigger any middleware
#### Example
```
Character.remove({ name: /Stark/ }, callback);
```
This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). The returned [promise](../queries) resolves to an object that contains 3 properties:
* `ok`: `1` if no errors occurred
* `deletedCount`: the number of documents deleted
* `n`: the number of documents deleted. Equal to `deletedCount`.
#### Example
```
const res = await Character.remove({ name: /Stark/ });
// Number of docs deleted
res.deletedCount;
```
#### Note
Calling `remove()` creates a [Mongoose query](queries), and a query does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), or call [`Query#exec()`](#query_Query-exec).
```
// not executed
const query = Character.remove({ name: /Stark/ });
// executed
Character.remove({ name: /Stark/ }, callback);
Character.remove({ name: /Stark/ }).remove(callback);
// executed without a callback
Character.exec();
```
### Query.prototype.replaceOne()
##### Parameters
* [filter] «Object»
* [doc] «Object» the update command
* [options] «Object»
+ [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» params are (error, writeOpResult)
##### Returns:
* «Query» this
Declare and/or execute this query as a replaceOne() operation. Same as `update()`, except MongoDB will replace the existing document and will not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
**Note** replaceOne will *not* fire update middleware. Use `pre('replaceOne')` and `post('replaceOne')` instead.
#### Example:
```
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
```
This function triggers the following middleware.
* `replaceOne()`
### Query.prototype.select()
##### Parameters
* arg «Object|String»
##### Returns:
* «Query» this
Specifies which document fields to include or exclude (also known as the query "projection")
When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](https://mongoosejs.com/docs/api.html#schematype_SchemaType-select).
A projection *must* be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field).
#### Example
```
// include a and b, exclude other fields
query.select('a b');
// exclude c and d, include other fields
query.select('-c -d');
// Use `+` to override schema-level `select: false` without making the
// projection inclusive.
const schema = new Schema({
foo: { type: String, select: false },
bar: String
});
// ...
query.select('+foo'); // Override foo's `select: false` without excluding `bar`
// or you may use object notation, useful when
// you have keys already prefixed with a "-"
query.select({ a: 1, b: 1 });
query.select({ c: 0, d: 0 });
```
### Query.prototype.selected()
##### Returns:
* «Boolean»
Determines if field selection has been made.
### Query.prototype.selectedExclusively()
##### Returns:
* «Boolean»
Determines if exclusive field selection has been made.
```
query.selectedExclusively() // false
query.select('-name')
query.selectedExclusively() // true
query.selectedInclusively() // false
```
### Query.prototype.selectedInclusively()
##### Returns:
* «Boolean»
Determines if inclusive field selection has been made.
```
query.selectedInclusively() // false
query.select('name')
query.selectedInclusively() // true
```
### Query.prototype.session()
##### Parameters
* [session] «ClientSession» from `await conn.startSession()`
##### Returns:
* «Query» this
Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this query. Sessions are how you mark a query as part of a [transaction](../transactions).
Calling `session(null)` removes the session from this query.
#### Example:
```
const s = await mongoose.startSession();
await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s);
```
### Query.prototype.set()
##### Parameters
* path «String|Object» path or object of key/value pairs to set
* [val] «Any» the value to set
##### Returns:
* «Query» this
Adds a `$set` to this query's update without changing the operation. This is useful for query middleware so you can add an update regardless of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
#### Example:
```
// Updates `{ $set: { updatedAt: new Date() } }`
new Query().updateOne({}, {}).set('updatedAt', new Date());
new Query().updateMany({}, {}).set({ updatedAt: new Date() });
```
### Query.prototype.setOptions()
##### Parameters
* options «Object»
##### Returns:
* «Query» this
Sets query options. Some options only make sense for certain operations.
#### Options:
The following options are only for `find()`:
* [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors)
* [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort()%7D%7D)
* [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D)
* [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D)
* [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan)
* [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D)
* [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment)
* [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D)
* [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference)
* [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint)
The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
* [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
* [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
* [timestamps](../guide#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options.
* omitUndefined: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
* [lean](api#query_Query-lean)
* [populate](../populate)
* [projection](query#query_Query-projection)
The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`:
* [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/)
The following options are for `findOneAndUpdate()` and `findOneAndRemove()`
* [useFindAndModify](../deprecations#findandmodify)
* rawResult
The following options are for all operations
--------------------------------------------
* [collation](https://docs.mongodb.com/manual/reference/collation/)
* [session](https://docs.mongodb.com/manual/reference/server-sessions/)
* [explain](https://docs.mongodb.com/manual/reference/method/cursor.explain/)
### Query.prototype.setQuery()
##### Parameters
* new «Object» query conditions
##### Returns:
* «undefined»
Sets the query conditions to the provided JSON object.
#### Example:
```
var query = new Query();
query.find({ a: 1 })
query.setQuery({ a: 2 });
query.getQuery(); // { a: 2 }
```
### Query.prototype.setUpdate()
##### Parameters
* new «Object» update operation
##### Returns:
* «undefined»
Sets the current update operation to new value.
#### Example:
```
var query = new Query();
query.update({}, { $set: { a: 5 } });
query.setUpdate({ $set: { b: 6 } });
query.getUpdate(); // { $set: { b: 6 } }
```
### Query.prototype.size()
##### Parameters
* [path] «String»
* val «Number»
Specifies a `$size` query condition.
When called with one argument, the most recent path passed to `where()` is used.
#### Example
```
MyModel.where('tags').size(0).exec(function (err, docs) {
if (err) return handleError(err);
assert(Array.isArray(docs));
console.log('documents with 0 tags', docs);
})
```
### Query.prototype.skip()
##### Parameters
* val «Number»
Specifies the number of documents to skip.
#### Example
```
query.skip(100).limit(20)
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.slaveOk()
##### Parameters
* v «Boolean» defaults to true
##### Returns:
* «Query» this
*DEPRECATED* Sets the slaveOk option.
**Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
#### Example:
```
query.slaveOk() // true
query.slaveOk(true)
query.slaveOk(false)
```
### Query.prototype.slice()
##### Parameters
* [path] «String»
* val «Number» number/range of elements to slice
##### Returns:
* «Query» this
Specifies a `$slice` projection for an array.
#### Example
```
query.slice('comments', 5)
query.slice('comments', -5)
query.slice('comments', [10, 5])
query.where('comments').slice(5)
query.where('comments').slice([-10, 5])
```
### Query.prototype.snapshot()
##### Returns:
* «Query» this
Specifies this query as a `snapshot` query.
#### Example
```
query.snapshot() // true
query.snapshot(true)
query.snapshot(false)
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.sort()
##### Parameters
* arg «Object|String»
##### Returns:
* «Query» this
Sets the sort order
If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
#### Example
```
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
// equivalent
query.sort('field -test');
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.tailable()
##### Parameters
* bool «Boolean» defaults to true
* [opts] «Object» options to set
+ [opts.numberOfRetries] «Number» if cursor is exhausted, retry this many times before giving up
+ [opts.tailableRetryInterval] «Number» if cursor is exhausted, wait this many milliseconds before retrying
Sets the tailable option (for use with capped collections).
#### Example
```
query.tailable() // true
query.tailable(true)
query.tailable(false)
```
#### Note
Cannot be used with `distinct()`
### Query.prototype.then()
##### Parameters
* [resolve] «Function»
* [reject] «Function»
##### Returns:
* «Promise»
Executes the query returning a `Promise` which will be resolved with either the doc(s) or rejected with the error.
### Query.prototype.toConstructor()
##### Returns:
* «Query» subclass-of-Query
Converts this query to a customized, reusable query constructor with all arguments and options retained.
#### Example
```
// Create a query for adventure movies and read from the primary
// node in the replica-set unless it is down, in which case we'll
// read from a secondary node.
var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
// create a custom Query constructor based off these settings
var Adventure = query.toConstructor();
// Adventure is now a subclass of mongoose.Query and works the same way but with the
// default query parameters and options set.
Adventure().exec(callback)
// further narrow down our query results while still using the previous settings
Adventure().where({ name: /^Life/ }).exec(callback);
// since Adventure is a stand-alone constructor we can also add our own
// helper methods and getters without impacting global queries
Adventure.prototype.startsWith = function (prefix) {
this.where({ name: new RegExp('^' + prefix) })
return this;
}
Object.defineProperty(Adventure.prototype, 'highlyRated', {
get: function () {
this.where({ rating: { $gt: 4.5 }});
return this;
}
})
Adventure().highlyRated.startsWith('Life').exec(callback)
```
### Query.prototype.update()
##### Parameters
* [filter] «Object»
* [doc] «Object» the update command
* [options] «Object»
+ [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» params are (error, writeOpResult)
##### Returns:
* «Query» this
Declare and/or execute this query as an update() operation.
*All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops.*
This function triggers the following middleware.
* `update()`
#### Example
```
Model.where({ _id: id }).update({ title: 'words' })
// becomes
Model.where({ _id: id }).update({ $set: { title: 'words' }})
```
#### Valid options:
* `upsert` (boolean) whether to create the doc if it doesn't match (false)
* `multi` (boolean) whether multiple documents should be updated (false)
* `runValidators`: if true, runs [update validators](../validation#update-validators) on this command. Update validators validate the update operation against the model's schema.
* `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
* `strict` (boolean) overrides the `strict` option for this update
* `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
* `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
* `read`
* `writeConcern`
#### Note
Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.
#### Note
The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method.
```
var q = Model.where({ _id: id });
q.update({ $set: { name: 'bob' }}).update(); // not executed
q.update({ $set: { name: 'bob' }}).exec(); // executed
// keys that are not [atomic](<https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern>) ops become `$set`.
// this executes the same command as the previous example.
q.update({ name: 'bob' }).exec();
// overwriting with empty docs
var q = Model.where({ _id: id }).setOptions({ overwrite: true })
q.update({ }, callback); // executes
// multi update with overwrite to empty doc
var q = Model.where({ _id: id });
q.setOptions({ multi: true, overwrite: true })
q.update({ });
q.update(callback); // executed
// multi updates
Model.where()
.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
// more multi updates
Model.where()
.setOptions({ multi: true })
.update({ $set: { arr: [] }}, callback)
// single update by default
Model.where({ email: '[[email protected]](mailto:[email protected])' })
.update({ $inc: { counter: 1 }}, callback)
```
API summary
```
update(filter, doc, options, cb) // executes
update(filter, doc, options)
update(filter, doc, cb) // executes
update(filter, doc)
update(doc, cb) // executes
update(doc)
update(cb) // executes
update(true) // executes
update()
```
### Query.prototype.updateMany()
##### Parameters
* [filter] «Object»
* [doc] «Object» the update command
* [options] «Object»
+ [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» params are (error, writeOpResult)
##### Returns:
* «Query» this
Declare and/or execute this query as an updateMany() operation. Same as `update()`, except MongoDB will update *all* documents that match `filter` (as opposed to just the first one) regardless of the value of the `multi` option.
**Note** updateMany will *not* fire update middleware. Use `pre('updateMany')` and `post('updateMany')` instead.
#### Example:
```
const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
```
This function triggers the following middleware.
* `updateMany()`
### Query.prototype.updateOne()
##### Parameters
* [filter] «Object»
* [doc] «Object» the update command
* [options] «Object»
+ [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» params are (error, writeOpResult)
##### Returns:
* «Query» this
Declare and/or execute this query as an updateOne() operation. Same as `update()`, except it does not support the `multi` or `overwrite` options.
* MongoDB will update *only* the first document that matches `filter` regardless of the value of the `multi` option.
* Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`.
**Note** updateOne will *not* fire update middleware. Use `pre('updateOne')` and `post('updateOne')` instead.
#### Example:
```
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
```
This function triggers the following middleware.
* `updateOne()`
### Query.prototype.use$geoWithin
##### Type:
* «property»
Flag to opt out of using `$geoWithin`.
```
mongoose.Query.use$geoWithin = false;
```
MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work.
### Query.prototype.w()
##### Parameters
* val «String|number» 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option).
##### Returns:
* «Query» this
Sets the specified number of `mongod` servers, or tag set of `mongod` servers, that must acknowledge this write before this write is considered successful.
This option is only valid for operations that write to the database
-------------------------------------------------------------------
* `deleteOne()`
* `deleteMany()`
* `findOneAndDelete()`
* `findOneAndReplace()`
* `findOneAndUpdate()`
* `remove()`
* `update()`
* `updateOne()`
* `updateMany()`
Defaults to the schema's [`writeConcern.w` option](../guide#writeConcern)
#### Example:
```
// The 'majority' option means the `deleteOne()` promise won't resolve
// until the `deleteOne()` has propagated to the majority of the replica set
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
w('majority');
```
### Query.prototype.where()
##### Parameters
* [path] «String|Object»
* [val] «any»
##### Returns:
* «Query» this
Specifies a `path` for use with chaining.
#### Example
```
// instead of writing:
User.find({age: {$gte: 21, $lte: 65}}, callback);
// we can instead write:
User.where('age').gte(21).lte(65);
// passing query conditions is permitted
User.find().where({ name: 'vonderful' })
// chaining
User
.where('age').gte(21).lte(65)
.where('name', /^vonderful/i)
.where('friends').slice(10)
.exec(callback)
```
### Query.prototype.within()
##### Returns:
* «Query» this
Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
#### Example
```
query.where(path).within().box()
query.where(path).within().circle()
query.where(path).within().geometry()
query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
query.where('loc').within({ polygon: [[],[],[],[]] });
query.where('loc').within([], [], []) // polygon
query.where('loc').within([], []) // box
query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
```
**MUST** be used after `where()`.
#### NOTE:
As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
#### NOTE:
In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
### Query.prototype.wtimeout()
##### Parameters
* ms «number» number of milliseconds to wait
##### Returns:
* «Query» this
If [`w > 1`](https://mongoosejs.com/docs/api.html#query_Query-w), the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout.
This option is only valid for operations that write to the database
-------------------------------------------------------------------
* `deleteOne()`
* `deleteMany()`
* `findOneAndDelete()`
* `findOneAndReplace()`
* `findOneAndUpdate()`
* `remove()`
* `update()`
* `updateOne()`
* `updateMany()`
Defaults to the schema's [`writeConcern.wtimeout` option](../guide#writeConcern)
#### Example:
```
// The `deleteOne()` promise won't resolve until this `deleteOne()` has
// propagated to at least `w = 2` members of the replica set. If it takes
// longer than 1 second, this `deleteOne()` will fail.
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
w(2).
wtimeout(1000);
```
| programming_docs |
mongoose Array Array
=====
### MongooseArray.prototype.$pop()
Pops the array atomically at most one time per document `save()`.
#### NOTE:
*Calling this mulitple times on an array before saving sends the same command as calling it once.* *This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction.*
```
doc.array = [1,2,3];
var popped = doc.array.$pop();
console.log(popped); // 3
console.log(doc.array); // [1,2]
// no affect
popped = doc.array.$pop();
console.log(doc.array); // [1,2]
doc.save(function (err) {
if (err) return handleError(err);
// we saved, now $pop works again
popped = doc.array.$pop();
console.log(popped); // 2
console.log(doc.array); // [1]
})
```
### MongooseArray.prototype.$shift()
Atomically shifts the array at most one time per document `save()`.
#### NOTE:
*Calling this multiple times on an array before saving sends the same command as calling it once.* *This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction.*
```
doc.array = [1,2,3];
var shifted = doc.array.$shift();
console.log(shifted); // 1
console.log(doc.array); // [2,3]
// no affect
shifted = doc.array.$shift();
console.log(doc.array); // [2,3]
doc.save(function (err) {
if (err) return handleError(err);
// we saved, now $shift works again
shifted = doc.array.$shift();
console.log(shifted ); // 2
console.log(doc.array); // [3]
})
```
### MongooseArray.prototype.addToSet()
##### Parameters
##### Returns:
* «Array» the values that were added
Adds values to the array if not already present.
#### Example:
```
console.log(doc.array) // [2,3,4]
var added = doc.array.addToSet(4,5);
console.log(doc.array) // [2,3,4,5]
console.log(added) // [5]
```
### MongooseArray.prototype.includes()
##### Parameters
* obj «Object» the item to check
##### Returns:
* «Boolean»
Return whether or not the `obj` is included in the array.
### MongooseArray.prototype.indexOf()
##### Parameters
* obj «Object» the item to look for
##### Returns:
* «Number»
Return the index of `obj` or `-1` if not found.
### MongooseArray.prototype.inspect()
Helper for console.log
### MongooseArray.prototype.nonAtomicPush()
##### Parameters
Pushes items to the array non-atomically.
#### NOTE:
*marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.*
### MongooseArray.prototype.pop()
Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
#### Note:
*marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it.*
### MongooseArray.prototype.pull()
##### Parameters
Pulls items from the array atomically. Equality is determined by casting the provided value to an embedded document and comparing using [the `Document.equals()` function.](api#document_Document-equals)
#### Examples:
```
doc.array.pull(ObjectId)
doc.array.pull({ _id: 'someId' })
doc.array.pull(36)
doc.array.pull('tag 1', 'tag 2')
```
To remove a document from a subdocument array we may pass an object with a matching `_id`.
```
doc.subdocs.push({ _id: 4815162342 })
doc.subdocs.pull({ _id: 4815162342 }) // removed
```
Or we may passing the \_id directly and let mongoose take care of it.
```
doc.subdocs.push({ _id: 4815162342 })
doc.subdocs.pull(4815162342); // works
```
The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.
### MongooseArray.prototype.push()
##### Parameters
Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
#### Example:
```
const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);
const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();
// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
$each: [1, 2],
$position: 0
});
doc.nums; // [1, 2, 3, 4, 5]
```
### MongooseArray.prototype.remove()
Alias of [pull](#types_array_MongooseArray-pull)
### MongooseArray.prototype.set()
##### Returns:
* «Array» this
Sets the casted `val` at index `i` and marks the array modified.
#### Example:
```
// given documents based on the following
var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
var doc = new Doc({ array: [2,3,4] })
console.log(doc.array) // [2,3,4]
doc.array.set(1,"5");
console.log(doc.array); // [2,5,4] // properly cast to number
doc.save() // the change is saved
// VS not using array#set
doc.array[1] = "5";
console.log(doc.array); // [2,"5",4] // no casting
doc.save() // change is not saved
```
### MongooseArray.prototype.shift()
Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
#### Example:
```
doc.array = [2,3];
var res = doc.array.shift();
console.log(res) // 2
console.log(doc.array) // [3]
```
#### Note:
*marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.*
### MongooseArray.prototype.sort()
Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
#### NOTE:
*marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.*
### MongooseArray.prototype.splice()
Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
#### Note:
*marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.*
### MongooseArray.prototype.toObject()
##### Parameters
* options «Object»
##### Returns:
* «Array»
Returns a native js Array.
### MongooseArray.prototype.unshift()
Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
#### Note:
*marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.*
mongoose Mongoose Mongoose
========
### Mongoose()
##### Parameters
* options «Object» see [`Mongoose#set()` docs](mongoose#mongoose_Mongoose-set)
Mongoose constructor.
The exports object of the `mongoose` module is an instance of this class. Most apps will only use this one instance.
#### Example:
```
const mongoose = require('mongoose');
mongoose instanceof mongoose.Mongoose; // true
// Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc.
const m = new mongoose.Mongoose();
```
### Mongoose.prototype.Aggregate()
The Mongoose Aggregate constructor
### Mongoose.prototype.CastError()
##### Parameters
* type «String» The name of the type
* value «Any» The value that failed to cast
* path «String» The path `a.b.c` in the doc where this cast error occurred
* [reason] «Error» The original error that was thrown
The Mongoose CastError constructor
### Mongoose.prototype.Collection()
The Mongoose Collection constructor
### Mongoose.prototype.Connection()
The Mongoose [Connection](#connection_Connection) constructor
### Mongoose.prototype.Decimal128
##### Type:
* «property»
The Mongoose Decimal128 [SchemaType](../schematypes). Used for declaring paths in your schema that should be [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` instead.
#### Example:
```
const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 });
```
### Mongoose.prototype.Document()
The Mongoose [Document](#document-js) constructor.
### Mongoose.prototype.DocumentProvider()
The Mongoose DocumentProvider constructor. Mongoose users should not have to use this directly
### Mongoose.prototype.Error()
The [MongooseError](#error_MongooseError) constructor.
### Mongoose.prototype.Mixed
##### Type:
* «property»
The Mongoose Mixed [SchemaType](../schematypes). Used for declaring paths in your schema that Mongoose's change tracking, casting, and validation should ignore.
#### Example:
```
const schema = new Schema({ arbitrary: mongoose.Mixed });
```
### Mongoose.prototype.Model()
The Mongoose [Model](#model_Model) constructor.
### Mongoose.prototype.Mongoose()
The Mongoose constructor
The exports of the mongoose module is an instance of this class.
#### Example:
```
var mongoose = require('mongoose');
var mongoose2 = new mongoose.Mongoose();
```
### Mongoose.prototype.Number
##### Type:
* «property»
The Mongoose Number [SchemaType](../schematypes). Used for declaring paths in your schema that Mongoose should cast to numbers.
#### Example:
```
const schema = new Schema({ num: mongoose.Number });
// Equivalent to:
const schema = new Schema({ num: 'number' });
```
### Mongoose.prototype.ObjectId
##### Type:
* «property»
The Mongoose ObjectId [SchemaType](../schematypes). Used for declaring paths in your schema that should be [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` instead.
#### Example:
```
const childSchema = new Schema({ parentId: mongoose.ObjectId });
```
### Mongoose.prototype.Promise
##### Type:
* «property»
The Mongoose [Promise](#promise_Promise) constructor.
### Mongoose.prototype.PromiseProvider()
Storage layer for mongoose promises
### Mongoose.prototype.Query()
The Mongoose [Query](#query_Query) constructor.
### Mongoose.prototype.STATES
##### Type:
* «property»
Expose connection states for user-land
### Mongoose.prototype.Schema()
The Mongoose [Schema](#schema_Schema) constructor
#### Example:
```
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CatSchema = new Schema(..);
```
### Mongoose.prototype.SchemaType()
The Mongoose [SchemaType](#schematype_SchemaType) constructor
### Mongoose.prototype.SchemaTypeOptions()
The constructor used for schematype options
### Mongoose.prototype.SchemaTypes
##### Type:
* «property»
The various Mongoose SchemaTypes.
#### Note:
*Alias of mongoose.Schema.Types for backwards compatibility.*
### Mongoose.prototype.Types
##### Type:
* «property»
The various Mongoose Types.
#### Example:
```
var mongoose = require('mongoose');
var array = mongoose.Types.Array;
```
#### Types:
* [ObjectId](#types-objectid-js)
* [Buffer](#types-buffer-js)
* [SubDocument](#types-embedded-js)
* [Array](#types-array-js)
* [DocumentArray](#types-documentarray-js)
Using this exposed access to the `ObjectId` type, we can construct ids on demand.
```
var ObjectId = mongoose.Types.ObjectId;
var id1 = new ObjectId;
```
### Mongoose.prototype.VirtualType()
The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
### Mongoose.prototype.connect()
##### Parameters
* uri(s) «String»
* [options] «Object» passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
+ [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
+ [options.dbName] «String» The name of the database we want to use. If not provided, use database name from connection string.
+ [options.user] «String» username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
+ [options.pass] «String» password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
+ [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
+ [options.useNewUrlParser=false] «Boolean» False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic.
+ [options.useUnifiedTopology=false] «Boolean» False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.
+ [options.useCreateIndex=true] «Boolean» Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](../deprecations#-ensureindex-) for automatic index builds via [`Model.init()`](https://mongoosejs.com/docs/api.html#model_Model.init).
+ [options.useFindAndModify=true] «Boolean» True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
+ [options.reconnectTries=30] «Number» If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
+ [options.reconnectInterval=1000] «Number» See `reconnectTries` option above.
+ [options.promiseLibrary] «Class» Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
+ [options.poolSize=5] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
+ [options.bufferMaxEntries] «Number» The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.
+ [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity *during initial connection*. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
+ [options.socketTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity *after initial connection*. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
+ [options.family=0] «Number» Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0,`4`, or`6`.`4`means use IPv4 only,`6`means use IPv6 only,`0` means try both.
* [callback] «Function»
##### Returns:
* «Promise» resolves to `this` if connection succeeded
Opens the default mongoose connection.
#### Example:
```
mongoose.connect('mongodb://user:pass@localhost:port/database');
// replica sets
var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase';
mongoose.connect(uri);
// with options
mongoose.connect(uri, options);
// optional callback that gets fired when initial connection completed
var uri = 'mongodb://nonexistent.domain:27000';
mongoose.connect(uri, function(error) {
// if error is truthy, the initial connection failed.
})
```
### Mongoose.prototype.connection
##### Type:
* «Connection»
The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections).
#### Example:
```
var mongoose = require('mongoose');
mongoose.connect(...);
mongoose.connection.on('error', cb);
```
This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model).
To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection).
### Mongoose.prototype.connections
##### Type:
* «Array»
An array containing all <connections> associated with this Mongoose instance. By default, there is 1 connection. Calling [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection to this array.
#### Example:
```
const mongoose = require('mongoose');
mongoose.connections.length; // 1, just the default connection
mongoose.connections[0] === mongoose.connection; // true
mongoose.createConnection('mongodb://localhost:27017/test');
mongoose.connections.length; // 2
```
### Mongoose.prototype.createConnection()
##### Parameters
* [uri] «String» a mongodb:// URI
* [options] «Object» passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
+ [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
+ [options.dbName] «String» The name of the database we want to use. If not provided, use database name from connection string.
+ [options.user] «String» username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
+ [options.pass] «String» password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
+ [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
+ [options.useNewUrlParser=false] «Boolean» False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default.
+ [options.useUnifiedTopology=false] «Boolean» False by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default.
+ [options.useCreateIndex=true] «Boolean» Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](../deprecations#-ensureindex-) for automatic index builds via [`Model.init()`](https://mongoosejs.com/docs/api.html#model_Model.init).
+ [options.useFindAndModify=true] «Boolean» True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
+ [options.reconnectTries=30] «Number» If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
+ [options.reconnectInterval=1000] «Number» See `reconnectTries` option above.
+ [options.promiseLibrary] «Class» Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
+ [options.poolSize=5] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
+ [options.bufferMaxEntries] «Number» The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.
+ [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity *during initial connection*. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
+ [options.socketTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity *after initial connection*. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
+ [options.family=0] «Number» Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0,`4`, or`6`.`4`means use IPv4 only,`6`means use IPv6 only,`0` means try both.
##### Returns:
* «Connection» the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()`
Creates a Connection instance.
Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections.
*Options passed take precedence over options included in connection strings.*
#### Example:
```
// with mongodb:// URI
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
// and options
var opts = { db: { native_parser: true }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
// replica sets
db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
// and options
var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
// and options
var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
db = mongoose.createConnection('localhost', 'database', port, opts)
// initialize now, connect later
db = mongoose.createConnection();
db.openUri('localhost', 'database', port, [opts]);
```
### Mongoose.prototype.deleteModel()
##### Parameters
* name «String|RegExp» if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
##### Returns:
* «Mongoose» this
Removes the model named `name` from the default connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.
Equivalent to `mongoose.connection.deleteModel(name)`.
#### Example:
```
mongoose.model('User', new Schema({ name: String }));
console.log(mongoose.model('User')); // Model object
mongoose.deleteModel('User');
console.log(mongoose.model('User')); // undefined
// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
mongoose.deleteModel(/.+/); // Delete every model
});
```
### Mongoose.prototype.disconnect()
##### Parameters
* [callback] «Function» called after all connection close, or when first error occurred.
##### Returns:
* «Promise» resolves when all connections are closed, or rejects with the first error that occurred.
Runs `.close()` on all connections in parallel.
### Mongoose.prototype.driver
##### Type:
* «property»
The underlying driver this Mongoose instance uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions like `find()`.
### Mongoose.prototype.get()
##### Parameters
* key «String»
Gets mongoose options
#### Example:
```
mongoose.get('test') // returns the 'test' value
```
### Mongoose.prototype.isValidObjectId()
Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.
#### Example:
```
mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
mongoose.isValidObjectId('0123456789ab'); // true
mongoose.isValidObjectId(6); // false
```
### Mongoose.prototype.model()
##### Parameters
* name «String|Function» model name or class extending Model
* [schema] «Schema» the schema to use.
* [collection] «String» name (optional, inferred from model name)
* [skipInit] «Boolean» whether to skip initialization (defaults to false)
##### Returns:
* «Model» The model associated with `name`. Mongoose will create the model if it doesn't already exist.
Defines a model or retrieves it.
Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance.
If you call `mongoose.model()` with twice the same name but a different schema, you will get an `OverwriteModelError`. If you call `mongoose.model()` with the same name and same schema, you'll get the same schema back.
#### Example:
```
var mongoose = require('mongoose');
// define an Actor model with this mongoose instance
const Schema = new Schema({ name: String });
mongoose.model('Actor', schema);
// create a new connection
var conn = mongoose.createConnection(..);
// create Actor model
var Actor = conn.model('Actor', schema);
conn.model('Actor') === Actor; // true
conn.model('Actor', schema) === Actor; // true, same schema
conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
// This throws an `OverwriteModelError` because the schema is different.
conn.model('Actor', new Schema({ name: String }));
```
*When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option.*
#### Example:
```
var schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)
```
### Mongoose.prototype.modelNames()
##### Returns:
* «Array»
Returns an array of model names created on this instance of Mongoose.
#### Note:
*Does not include names of models created using `connection.model()`.*
### Mongoose.prototype.mongo
##### Type:
* «property»
The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
### Mongoose.prototype.mquery
##### Type:
* «property»
The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
### Mongoose.prototype.now()
Mongoose uses this function to get the current time when setting [timestamps](../guide#timestamps). You may stub out this function using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
### Mongoose.prototype.plugin()
##### Parameters
* fn «Function» plugin callback
* [opts] «Object» optional options
##### Returns:
* «Mongoose» this
Declares a global plugin executed on all Schemas.
Equivalent to calling `.plugin(fn)` on each Schema you create.
### Mongoose.prototype.pluralize()
##### Parameters
* [fn] «Function|null» overwrites the function used to pluralize collection names
##### Returns:
* «Function,null» the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`.
Getter/setter around function for pluralizing collection names.
### Mongoose.prototype.set()
##### Parameters
* key «String»
* value «String|Function|Boolean»
Sets mongoose options
#### Example:
```
mongoose.set('test', value) // sets the 'test' option to `value`
mongoose.set('debug', true) // enable logging collection methods + arguments to the console
mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments
```
Currently supported options are
-------------------------------
* 'debug': prints the operations mongoose sends to MongoDB to the console
* 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models
* 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver.
* 'useFindAndModify': true by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
* 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default
* 'useUnifiedTopology': false by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default
* 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model.
* 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
* 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas
* 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter.
* 'runValidators': false by default. Set to true to enable [update validators](../validation#update-validators) for all validators by default.
* 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](https://mongoosejs.com/docs/api.html#document_Document-toObject)
* 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](https://mongoosejs.com/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()`
* 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas.
* 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
* 'typePojoToMixed': true by default, may be `false` or `true`. Sets the default typePojoToMixed for schemas.
* 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query
* 'autoIndex': true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance.
### Mongoose.prototype.startSession()
##### Parameters
* [options] «Object» see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
+ [options.causalConsistency=true] «Boolean» set to false to disable causal consistency
* [callback] «Function»
##### Returns:
* «Promise<ClientSession>» promise that resolves to a MongoDB driver `ClientSession`
*Requires MongoDB >= 3.6.0.* Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`. Sessions are scoped to a connection, so calling `mongoose.startSession()` starts a session on the [default mongoose connection](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-connection).
### Mongoose.prototype.version
##### Type:
* «property»
The Mongoose version
#### Example
```
console.log(mongoose.version); // '5.x.x'
```
| programming_docs |
mongoose Connection Connection
==========
### Connection()
##### Parameters
* base «Mongoose» a mongoose instance
##### Inherits:
* «NodeJS EventEmitter http://nodejs.org/api/events.html#events\_class\_events\_eventemitter»
Connection constructor
For practical reasons, a Connection equals a Db.
### Connection.prototype.close()
##### Parameters
* [force] «Boolean» optional
* [callback] «Function» optional
##### Returns:
* «Promise»
Closes the connection
### Connection.prototype.collection()
##### Parameters
* name «String» of the collection
* [options] «Object» optional collection options
##### Returns:
* «Collection» collection instance
Retrieves a collection, creating it if not cached.
Not typically needed by applications. Just talk to your collection through your model.
### Connection.prototype.collections
##### Type:
* «property»
A hash of the collections associated with this connection
### Connection.prototype.config
##### Type:
* «property»
A hash of the global options that are associated with this connection
### Connection.prototype.createCollection()
##### Parameters
* collection «string» The collection to create
* [options] «Object» see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection)
* [callback] «Function»
##### Returns:
* «Promise»
Helper for `createCollection()`. Will explicitly create the given collection with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection)
### Connection.prototype.db
##### Type:
* «property»
The mongodb.Db instance, set when the connection is opened
### Connection.prototype.deleteModel()
##### Parameters
* name «String|RegExp» if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
##### Returns:
* «Connection» this
Removes the model named `name` from this connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.
#### Example:
```
conn.model('User', new Schema({ name: String }));
console.log(conn.model('User')); // Model object
conn.deleteModel('User');
console.log(conn.model('User')); // undefined
// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
conn.deleteModel(/.+/); // Delete every model
});
```
### Connection.prototype.dropCollection()
##### Parameters
* collection «string» The collection to delete
* [callback] «Function»
##### Returns:
* «Promise»
Helper for `dropCollection()`. Will delete the given collection, including all documents and indexes.
### Connection.prototype.dropDatabase()
##### Parameters
* [callback] «Function»
##### Returns:
* «Promise»
Helper for `dropDatabase()`. Deletes the given database, including all collections, documents, and indexes.
#### Example:
```
const conn = mongoose.createConnection('mongodb://localhost:27017/mydb');
// Deletes the entire 'mydb' database
await conn.dropDatabase();
```
### Connection.prototype.get()
##### Parameters
* key «String»
Gets the value of the option `key`. Equivalent to `conn.options[key]`
#### Example:
```
conn.get('test'); // returns the 'test' value
```
### Connection.prototype.host
##### Type:
* «property»
The host name portion of the URI. If multiple hosts, such as a replica set, this will contain the first host name in the URI
#### Example
```
mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost"
```
### Connection.prototype.model()
##### Parameters
* name «String|Function» the model name or class extending Model
* [schema] «Schema» a schema. necessary when defining a model
* [collection] «String» name of mongodb collection (optional) if not given it will be induced from model name
##### Returns:
* «Model» The compiled model
Defines or retrieves a model.
```
var mongoose = require('mongoose');
var db = mongoose.createConnection(..);
db.model('Venue', new Schema(..));
var Ticket = db.model('Ticket', new Schema(..));
var Venue = db.model('Venue');
```
*When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.*
#### Example:
```
var schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = conn.model('Actor', schema, collectionName)
```
### Connection.prototype.modelNames()
##### Returns:
* «Array»
Returns an array of model names created on this connection.
### Connection.prototype.models
##### Type:
* «property»
A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing a map from model names to models. Contains all models that have been added to this connection using [`Connection#model()`](connection#connection_Connection-model).
#### Example
```
const conn = mongoose.createConnection();
const Test = conn.model('Test', mongoose.Schema({ name: String }));
Object.keys(conn.models).length; // 1
conn.models.Test === Test; // true
```
### Connection.prototype.name
##### Type:
* «property»
The name of the database this connection points to.
#### Example
```
mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb"
```
### Connection.prototype.openUri()
##### Parameters
* uri «String» The URI to connect with.
* [options] «Object» Passed on to <http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect>
+ [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
+ [options.dbName] «String» The name of the database we want to use. If not provided, use database name from connection string.
+ [options.user] «String» username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
+ [options.pass] «String» password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
+ [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
+ [options.useNewUrlParser=false] «Boolean» False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic.
+ [options.useUnifiedTopology=false] «Boolean» False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.
+ [options.useCreateIndex=true] «Boolean» Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](../deprecations#-ensureindex-) for automatic index builds via [`Model.init()`](https://mongoosejs.com/docs/api.html#model_Model.init).
+ [options.useFindAndModify=true] «Boolean» True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
+ [options.reconnectTries=30] «Number» If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
+ [options.reconnectInterval=1000] «Number» See `reconnectTries` option above.
+ [options.promiseLibrary] «Class» Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
+ [options.poolSize=5] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
+ [options.bufferMaxEntries] «Number» The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.
+ [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity *during initial connection*. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
+ [options.socketTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity *after initial connection*. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
+ [options.family=0] «Number» Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0,`4`, or`6`.`4`means use IPv4 only,`6`means use IPv6 only,`0` means try both.
* [callback] «Function»
Opens the connection with a URI using `MongoClient.connect()`.
### Connection.prototype.pass
##### Type:
* «property»
The password specified in the URI
#### Example
```
mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw"
```
### Connection.prototype.plugin()
##### Parameters
* fn «Function» plugin callback
* [opts] «Object» optional options
##### Returns:
* «Connection» this
Declares a plugin executed on all schemas you pass to `conn.model()`
Equivalent to calling `.plugin(fn)` on each schema you create.
#### Example:
```
const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
db.model('Test', new Schema({})); // Prints "Applied"
```
### Connection.prototype.plugins
##### Type:
* «property»
The plugins that will be applied to all models created on this connection.
#### Example:
```
const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
db.model('Test', new Schema({})); // Prints "Applied"
```
### Connection.prototype.port
##### Type:
* «property»
The port portion of the URI. If multiple hosts, such as a replica set, this will contain the port from the first host name in the URI.
#### Example
```
mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017
```
### Connection.prototype.readyState
##### Type:
* «property»
Connection ready state
* 0 = disconnected
* 1 = connected
* 2 = connecting
* 3 = disconnecting
Each state change emits its associated event name.
#### Example
```
conn.on('connected', callback);
conn.on('disconnected', callback);
```
### Connection.prototype.set()
##### Parameters
* key «String»
* val «Any»
Sets the value of the option `key`. Equivalent to `conn.options[key] = val`
Supported options include
-------------------------
* `maxTimeMS`: Set [`maxTimeMS`](https://mongoosejs.com/docs/api.html#query_Query-maxTimeMS) for all queries on this connection.
* `useFindAndModify`: Set to `false` to work around the [`findAndModify()` deprecation warning](../deprecations#-findandmodify-)
#### Example:
```
conn.set('test', 'foo');
conn.get('test'); // 'foo'
conn.options.test; // 'foo'
```
### Connection.prototype.startSession()
##### Parameters
* [options] «Object» see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
+ [options.causalConsistency=true] «Boolean» set to false to disable causal consistency
* [callback] «Function»
##### Returns:
* «Promise<ClientSession>» promise that resolves to a MongoDB driver `ClientSession`
*Requires MongoDB >= 3.6.0.* Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
#### Example:
```
const session = await conn.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `doc` will always be null, even if reading from a replica set
// secondary. Without causal consistency, it is possible to
// get a doc back from the below query if the query reads from a
// secondary that is experiencing replication lag.
doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
```
### Connection.prototype.useDb()
##### Parameters
* name «String» The database name
* [options] «Object»
+ [options.useCache=false] «Boolean» If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
##### Returns:
* «Connection» New Connection Object
Switches to a different database using the same connection pool.
Returns a new connection object, with the new db.
### Connection.prototype.user
##### Type:
* «property»
The username specified in the URI
#### Example
```
mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val"
```
mongoose Error Error
=====
### Error()
##### Parameters
* msg «String» Error message
##### Inherits:
* «Error https://developer.mozilla.org/en/JavaScript/Reference/Global\_Objects/Error»
MongooseError constructor. MongooseError is the base class for all Mongoose-specific errors.
#### Example:
```
const Model = mongoose.model('Test', new Schema({ answer: Number }));
const doc = new Model({ answer: 'not a number' });
const err = doc.validateSync();
err instanceof mongoose.Error; // true
```
### Error.CastError
##### Type:
* «property»
An instance of this error class will be returned when mongoose failed to cast a value.
### Error.DivergentArrayError
##### Type:
* «property»
An instance of this error will be returned if you used an array projection and then modified the array in an unsafe way.
### Error.DocumentNotFoundError
##### Type:
* «property»
An instance of this error class will be returned when `save()` fails because the underlying document was not found. The constructor takes one parameter, the conditions that mongoose passed to `update()` when trying to update the document.
### Error.MissingSchemaError
##### Type:
* «property»
Thrown when you try to access a model that has not been registered yet
### Error.OverwriteModelError
##### Type:
* «property»
Thrown when a model with the given name was already registered on the connection. See [the FAQ about `OverwriteModelError`](https://mongoosejs.com/docs/faq.html#overwrite-model-error).
### Error.ParallelSaveError
##### Type:
* «property»
An instance of this error class will be returned when you call `save()` multiple times on the same document in parallel. See the [FAQ](https://mongoosejs.com/docs/faq.html) for more information.
### Error.StrictModeError
##### Type:
* «property»
Thrown when your try to pass values to model contrtuctor that were not specified in schema or change immutable properties when `strict` mode is `"throw"`
### Error.ValidationError
##### Type:
* «property»
An instance of this error class will be returned when [validation](../validation) failed. The `errors` property contains an object whose keys are the paths that failed and whose values are instances of CastError or ValidationError.
### Error.ValidatorError
##### Type:
* «property»
A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances.
#### Example:
```
const schema = Schema({ name: { type: String, required: true } });
const Model = mongoose.model('Test', schema);
const doc = new Model({});
// Top-level error is a ValidationError, \*\*not\*\* a ValidatorError
const err = doc.validateSync();
err instanceof mongoose.Error.ValidationError; // true
// A ValidationError `err` has 0 or more ValidatorErrors keyed by the
// path in the `err.errors` property.
err.errors['name'] instanceof mongoose.Error.ValidatorError;
err.errors['name'].kind; // 'required'
err.errors['name'].path; // 'name'
err.errors['name'].value; // undefined
```
Instances of `ValidatorError` have the following properties:
* `kind`: The validator's `type`, like `'required'` or `'regexp'`
* `path`: The path that failed validation
* `value`: The value that failed validation
### Error.VersionError
##### Type:
* «property»
An instance of this error class will be returned when you call `save()` after the document in the database was changed in a potentially unsafe way. See the [`versionKey` option](../guide#versionKey) for more information.
### Error.messages
##### Type:
* «property»
The default built-in validator error messages.
### Error.prototype.name
##### Type:
* «String»
The name of the error. The name uniquely identifies this Mongoose error. The possible values are:
* `MongooseError`: general Mongoose error
* `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property.
* `DisconnectedError`: This [connection](connections) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect.
* `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection
* `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api#mongoose_Mongoose-model) that was not defined
* `DocumentNotFoundError`: The document you tried to [`save()`](api#document_Document-save) was not found
* `ValidatorError`: error from an individual schema path's validator
* `ValidationError`: error returned from [`validate()`](api#document_Document-validate) or [`validateSync()`](api#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property.
* `MissingSchemaError`: You called `mongoose.Document()` without a schema
* `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide#strict).
* `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter
* `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api#mongoose_Mongoose-model) to re-define a model that was already defined.
* `ParallelSaveError`: Thrown when you call [`save()`](api#model_Model-save) on a document when the same document instance is already saving.
* `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide#strict) is set to `throw`.
* `VersionError`: Thrown when the [document is out of sync](guide#versionKey)
| programming_docs |
mongoose Model Model
=====
### Model()
##### Parameters
* doc «Object» values for initial set
* optional «[fields]» object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](api#query_Query-select).
##### Inherits:
* «Document http://mongoosejs.com/docs/api.html#document-js»
A Model is a class that's your primary tool for interacting with MongoDB. An instance of a Model is called a [Document](api#Document).
In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` class. You should not use the `mongoose.Model` class directly. The [`mongoose.model()`](api#mongoose_Mongoose-model) and [`connection.model()`](api#connection_Connection-model) functions create subclasses of `mongoose.Model` as shown below.
#### Example:
```
// `UserModel` is a "Model", a subclass of `mongoose.Model`.
const UserModel = mongoose.model('User', new Schema({ name: String }));
// You can use a Model to create new documents using `new`:
const userDoc = new UserModel({ name: 'Foo' });
await userDoc.save();
// You also use a model to create queries:
const userFromDb = await UserModel.findOne({ name: 'Foo' });
```
### Model.aggregate()
##### Parameters
* [pipeline] «Array» aggregation pipeline as an array of objects
* [callback] «Function»
##### Returns:
* «Aggregate»
Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection.
If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned.
This function triggers the following middleware.
* `aggregate()`
#### Example:
```
// Find the max balance of all accounts
Users.aggregate([
{ $group: { _id: null, maxBalance: { $max: '$balance' }}},
{ $project: { _id: 0, maxBalance: 1 }}
]).
then(function (res) {
console.log(res); // [ { maxBalance: 98000 } ]
});
// Or use the aggregation pipeline builder.
Users.aggregate().
group({ _id: null, maxBalance: { $max: '$balance' } }).
project('-id maxBalance').
exec(function (err, res) {
if (err) return handleError(err);
console.log(res); // [ { maxBalance: 98 } ]
});
```
#### NOTE:
* Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines.
* The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
### Model.bulkWrite()
##### Parameters
* ops «Array»
+ [ops.insertOne.document] «Object» The document to insert
+ [opts.updateOne.filter] «Object» Update the first document that matches this filter
+ [opts.updateOne.update] «Object» An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
+ [opts.updateOne.upsert=false] «Boolean» If true, insert a doc if none match
+ [opts.updateOne.collation] «Object» The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
+ [opts.updateOne.arrayFilters] «Array» The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
+ [opts.updateMany.filter] «Object» Update all the documents that match this filter
+ [opts.updateMany.update] «Object» An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
+ [opts.updateMany.upsert=false] «Boolean» If true, insert a doc if no documents match `filter`
+ [opts.updateMany.collation] «Object» The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
+ [opts.updateMany.arrayFilters] «Array» The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
+ [opts.deleteOne.filter] «Object» Delete the first document that matches this filter
+ [opts.deleteMany.filter] «Object» Delete all documents that match this filter
+ [opts.replaceOne.filter] «Object» Replace the first document that matches this filter
+ [opts.replaceOne.replacement] «Object» The replacement document
+ [opts.replaceOne.upsert=false] «Boolean» If true, insert a doc if no documents match `filter`
* [options] «Object»
+ [options.ordered=true] «Boolean» If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
+ [options.session=null] «ClientSession» The session associated with this bulk write. See [transactions docs](../transactions).
+ [options.w=1] «String|number» The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](https://mongoosejs.com/docs/api.html#query_Query-w) for more information.
+ [options.wtimeout=null] «number» The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout).
+ [options.j=true] «Boolean» If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option)
+ [options.bypassDocumentValidation=false] «Boolean» If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk.
* [callback] «Function» callback `function(error, bulkWriteOpResult) {}`
##### Returns:
* «Promise» resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds
Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one command. This is faster than sending multiple independent operations (like) if you use `create()`) because with `bulkWrite()` there is only one round trip to MongoDB.
Mongoose will perform casting on all operations you provide.
This function does **not** trigger any middleware, not `save()` nor `update()`. If you need to trigger `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead.
#### Example:
```
Character.bulkWrite([
{
insertOne: {
document: {
name: 'Eddard Stark',
title: 'Warden of the North'
}
}
},
{
updateOne: {
filter: { name: 'Eddard Stark' },
// If you were using the MongoDB driver directly, you'd need to do
// `update: { $set: { title: ... } }` but mongoose adds $set for
// you.
update: { title: 'Hand of the King' }
}
},
{
deleteOne: {
{
filter: { name: 'Eddard Stark' }
}
}
}
]).then(res => {
// Prints "1 1 1"
console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
});
```
The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are:
* `insertOne`
* `updateOne`
* `updateMany`
* `deleteOne`
* `deleteMany`
* `replaceOne`
### Model.cleanIndexes()
##### Parameters
* [callback] «Function» optional callback
##### Returns:
* «Promise,undefined» Returns `undefined` if callback is specified, returns a promise if no callback.
Deletes all indexes that aren't defined in this model's schema. Used by `syncIndexes()`.
The returned promise resolves to a list of the dropped indexes' names as an array
### Model.count()
##### Parameters
* filter «Object»
* [callback] «Function»
##### Returns:
* «Query»
Counts number of documents that match `filter` in a database collection.
This method is deprecated. If you want to count the number of documents in a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](https://mongoosejs.com/docs/api.html#model_Model.estimatedDocumentCount) instead. Otherwise, use the [`countDocuments()`](https://mongoosejs.com/docs/api.html#model_Model.countDocuments) function instead.
#### Example:
```
Adventure.count({ type: 'jungle' }, function (err, count) {
if (err) ..
console.log('there are %d jungle adventures', count);
});
```
### Model.countDocuments()
##### Parameters
* filter «Object»
* [callback] «Function»
##### Returns:
* «Query»
Counts number of documents matching `filter` in a database collection.
#### Example:
```
Adventure.countDocuments({ type: 'jungle' }, function (err, count) {
console.log('there are %d jungle adventures', count);
});
```
If you want to count all documents in a large collection, use the [`estimatedDocumentCount()` function](https://mongoosejs.com/docs/api.html#model_Model.estimatedDocumentCount) instead. If you call `countDocuments({})`, MongoDB will always execute a full collection scan and **not** use any indexes.
The `countDocuments()` function is similar to `count()`, but there are a [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). Below are the operators that `count()` supports but `countDocuments()` does not, and the suggested replacement:
* `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
* `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center)
* `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)
### Model.create()
##### Parameters
* docs «Array|Object» Documents to insert, as a spread or array
* [options] «Object» Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread.
* [callback] «Function» callback
##### Returns:
* «Promise»
Shortcut for saving one or more documents to the database. `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in docs.
This function triggers the following middleware.
* `save()`
#### Example:
```
// pass a spread of docs and a callback
Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
if (err) // ...
});
// pass an array of docs
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, candies) {
if (err) // ...
var jellybean = candies[0];
var snickers = candies[1];
// ...
});
// callback is optional; use the returned promise if you like:
var promise = Candy.create({ type: 'jawbreaker' });
promise.then(function (jawbreaker) {
// ...
})
```
### Model.createCollection()
##### Parameters
* [options] «Object» see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection)
* [callback] «Function»
Create the collection for this model. By default, if no indexes are specified, mongoose will not create the collection for the model until any documents are created. Use this method to create the collection explicitly.
Note 1: You may need to call this before starting a transaction See <https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations>
Note 2: You don't have to call this if your schema contains index or unique field. In that case, just use `Model.init()`
#### Example:
```
var userSchema = new Schema({ name: String })
var User = mongoose.model('User', userSchema);
User.createCollection().then(function(collection) {
console.log('Collection is created!');
});
```
### Model.createIndexes()
##### Parameters
* [options] «Object» internal options
* [cb] «Function» optional callback
##### Returns:
* «Promise»
Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) function.
### Model.deleteMany()
##### Parameters
* conditions «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function»
##### Returns:
* «Query»
Deletes all of the documents that match `conditions` from the collection. Behaves like `remove()`, but deletes all documents that match `conditions` regardless of the `single` option.
#### Example:
```
Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});
```
#### Note:
Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks.
### Model.deleteOne()
##### Parameters
* conditions «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function»
##### Returns:
* «Query»
Deletes the first document that matches `conditions` from the collection. Behaves like `remove()`, but deletes at most one document regardless of the `single` option.
#### Example:
```
Character.deleteOne({ name: 'Eddard Stark' }, function (err) {});
```
#### Note:
Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks.
### Model.discriminator()
##### Parameters
* name «String» discriminator model name
* schema «Schema» discriminator model schema
* [value] «String» the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
##### Returns:
* «Model» The newly created discriminator model
Adds a discriminator type.
#### Example:
```
function BaseSchema() {
Schema.apply(this, arguments);
this.add({
name: String,
createdAt: Date
});
}
util.inherits(BaseSchema, Schema);
var PersonSchema = new BaseSchema();
var BossSchema = new BaseSchema({ department: String });
var Person = mongoose.model('Person', PersonSchema);
var Boss = Person.discriminator('Boss', BossSchema);
new Boss().__t; // "Boss". `\_\_t` is the default `discriminatorKey`
var employeeSchema = new Schema({ boss: ObjectId });
var Employee = Person.discriminator('Employee', employeeSchema, 'staff');
new Employee().__t; // "staff" because of 3rd argument above
```
### Model.distinct()
##### Parameters
* field «String»
* [conditions] «Object» optional
* [callback] «Function»
##### Returns:
* «Query»
Creates a Query for a `distinct` operation.
Passing a `callback` executes the query.
#### Example
```
Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
if (err) return handleError(err);
assert(Array.isArray(result));
console.log('unique urls with more than 100 clicks', result);
})
var query = Link.distinct('url');
query.exec(callback);
```
### Model.ensureIndexes()
##### Parameters
* [options] «Object» internal options
* [cb] «Function» optional callback
##### Returns:
* «Promise»
Sends `createIndex` commands to mongo for each index declared in the schema. The `createIndex` commands are sent in series.
#### Example:
```
Event.ensureIndexes(function (err) {
if (err) return handleError(err);
});
```
After completion, an `index` event is emitted on this `Model` passing an error if one occurred.
#### Example:
```
var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
var Event = mongoose.model('Event', eventSchema);
Event.on('index', function (err) {
if (err) console.error(err); // error occurred during index creation
})
```
*NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.*
### Model.estimatedDocumentCount()
##### Parameters
* [options] «Object»
* [callback] «Function»
##### Returns:
* «Query»
Estimates the number of documents in the MongoDB collection. Faster than using `countDocuments()` for large collections because `estimatedDocumentCount()` uses collection metadata rather than scanning the entire collection.
#### Example:
```
const numAdventures = Adventure.estimatedDocumentCount();
```
### Model.events
##### Type:
* «property»
Event emitter that reports any errors that occurred. Useful for global error handling.
#### Example:
```
MyModel.events.on('error', err => console.log(err.message));
// Prints a 'CastError' because of the above handler
await MyModel.findOne({ _id: 'notanid' }).catch(noop);
```
### Model.exists()
##### Parameters
* filter «Object»
* [callback] «Function» callback
##### Returns:
* «Promise»
Returns true if at least one document exists in the database that matches the given `filter`, and false otherwise.
Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)`
#### Example:
```
await Character.deleteMany({});
await Character.create({ name: 'Jean-Luc Picard' });
await Character.exists({ name: /picard/i }); // true
await Character.exists({ name: /riker/i }); // false
```
This function triggers the following middleware.
* `findOne()`
### Model.find()
##### Parameters
* filter «Object|ObjectId»
* [projection] «Object|String» optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select)
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function»
##### Returns:
* «Query»
Finds documents.
The `filter` are cast to their respective SchemaTypes before the command is sent. See our [query casting tutorial](../tutorials/query_casting) for more information on how Mongoose casts `filter`.
#### Examples:
```
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })
// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});
```
### Model.findById()
##### Parameters
* id «Any» value of `_id` to query by
* [projection] «Object|String» optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function»
##### Returns:
* «Query»
Finds a single document by its \_id field. `findById(id)` is almost\* equivalent to `findOne({ _id: id })`. If you want to query by a document's `_id`, use `findById()` instead of `findOne()`.
The `id` is cast based on the Schema before sending the command.
This function triggers the following middleware.
* `findOne()`
\* Except for how it treats `undefined`. If you use `findOne()`, you'll see that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent to `findOne({})` and return arbitrary documents. However, mongoose translates `findById(undefined)` into `findOne({ _id: null })`.
#### Example:
```
// find adventure by id and execute
Adventure.findById(id, function (err, adventure) {});
// same as above
Adventure.findById(id).exec(callback);
// select only the adventures name and length
Adventure.findById(id, 'name length', function (err, adventure) {});
// same as above
Adventure.findById(id, 'name length').exec(callback);
// include all properties except for `length`
Adventure.findById(id, '-length').exec(function (err, adventure) {});
// passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
// same as above
Adventure.findById(id, 'name').lean().exec(function (err, doc) {});
```
### Model.findByIdAndDelete()
##### Parameters
* id «Object|Number|String» value of `_id` to query by
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
* [callback] «Function»
##### Returns:
* «Query»
Issue a MongoDB `findOneAndDelete()` command by a document's \_id field. In other words, `findByIdAndDelete(id)` is a shorthand for `findOneAndDelete({ _id: id })`.
This function triggers the following middleware.
* `findOneAndDelete()`
### Model.findByIdAndRemove()
##### Parameters
* id «Object|Number|String» value of `_id` to query by
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
* [callback] «Function»
##### Returns:
* «Query»
Issue a mongodb findAndModify remove command by a document's \_id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`.
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if `callback` is passed.
This function triggers the following middleware.
* `findOneAndRemove()`
#### Options:
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `select`: sets the document fields to return
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
#### Examples:
```
A.findByIdAndRemove(id, options, callback) // executes
A.findByIdAndRemove(id, options) // return Query
A.findByIdAndRemove(id, callback) // executes
A.findByIdAndRemove(id) // returns Query
A.findByIdAndRemove() // returns Query
```
### Model.findByIdAndUpdate()
##### Parameters
* id «Object|Number|String» value of `_id` to query by
* [update] «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](https://mongoosejs.com/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](../tutorials/lean).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* [callback] «Function»
##### Returns:
* «Query»
Issues a mongodb findAndModify update command by a document's \_id field. `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed.
This function triggers the following middleware.
* `findOneAndUpdate()`
#### Options:
* `new`: bool - true to return the modified document rather than the original. defaults to false
* `upsert`: bool - creates the object if it doesn't exist. defaults to false.
* `runValidators`: if true, runs [update validators](../validation#update-validators) on this command. Update validators validate the update operation against the model's schema.
* `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `select`: sets the document fields to return
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
#### Examples:
```
A.findByIdAndUpdate(id, update, options, callback) // executes
A.findByIdAndUpdate(id, update, options) // returns Query
A.findByIdAndUpdate(id, update, callback) // executes
A.findByIdAndUpdate(id, update) // returns Query
A.findByIdAndUpdate() // returns Query
```
#### Note:
All top level update keys which are not `atomic` operation names are treated as set operations:
#### Example:
```
Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)
// is sent as
Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)
```
This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`.
#### Note:
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
* defaults. Use the `setDefaultsOnInsert` option to override.
`findAndModify` helpers support limited validation. You can enable these by setting the `runValidators` options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
```
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
```
### Model.findOne()
##### Parameters
* [conditions] «Object»
* [projection] «Object|String» optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
* [callback] «Function»
##### Returns:
* «Query»
Finds one document.
The `conditions` are cast to their respective SchemaTypes before the command is sent.
*Note:* `conditions` is optional, and if `conditions` is null or undefined, mongoose will send an empty `findOne` command to MongoDB, which will return an arbitrary document. If you're querying by `_id`, use `findById()` instead.
#### Example:
```
// find one iphone adventures - iphone adventures??
Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});
// same as above
Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});
// select only the adventures name
Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});
// same as above
Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});
// specify options, in this case lean
Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);
// same as above
Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);
// chaining findOne queries (same as above)
Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);
```
### Model.findOneAndDelete()
##### Parameters
* conditions «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
* [callback] «Function»
##### Returns:
* «Query»
Issue a MongoDB `findOneAndDelete()` command.
Finds a matching document, removes it, and passes the found document (if any) to the callback.
Executes the query if `callback` is passed.
This function triggers the following middleware.
* `findOneAndDelete()`
This function differs slightly from `Model.findOneAndRemove()` in that `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), as opposed to a `findOneAndDelete()` command. For most mongoose use cases, this distinction is purely pedantic. You should use `findOneAndDelete()` unless you have a good reason not to.
#### Options:
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `select`: sets the document fields to return
* `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
#### Examples:
```
A.findOneAndDelete(conditions, options, callback) // executes
A.findOneAndDelete(conditions, options) // return Query
A.findOneAndDelete(conditions, callback) // executes
A.findOneAndDelete(conditions) // returns Query
A.findOneAndDelete() // returns Query
```
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
* defaults. Use the `setDefaultsOnInsert` option to override.
`findAndModify` helpers support limited validation. You can enable these by setting the `runValidators` options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
```
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
```
### Model.findOneAndRemove()
##### Parameters
* conditions «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
* [callback] «Function»
##### Returns:
* «Query»
Issue a mongodb findAndModify remove command.
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if `callback` is passed.
This function triggers the following middleware.
* `findOneAndRemove()`
#### Options:
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `select`: sets the document fields to return
* `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
#### Examples:
```
A.findOneAndRemove(conditions, options, callback) // executes
A.findOneAndRemove(conditions, options) // return Query
A.findOneAndRemove(conditions, callback) // executes
A.findOneAndRemove(conditions) // returns Query
A.findOneAndRemove() // returns Query
```
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
* defaults. Use the `setDefaultsOnInsert` option to override.
`findAndModify` helpers support limited validation. You can enable these by setting the `runValidators` options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
```
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
```
### Model.findOneAndReplace()
##### Parameters
* filter «Object» Replace the first document that matches this filter
* [replacement] «Object» Replace with this document
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* [callback] «Function»
##### Returns:
* «Query»
Issue a MongoDB `findOneAndReplace()` command.
Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.
Executes the query if `callback` is passed.
This function triggers the following query middleware.
* `findOneAndReplace()`
#### Options:
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `select`: sets the document fields to return
* `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
#### Examples:
```
A.findOneAndReplace(conditions, options, callback) // executes
A.findOneAndReplace(conditions, options) // return Query
A.findOneAndReplace(conditions, callback) // executes
A.findOneAndReplace(conditions) // returns Query
A.findOneAndReplace() // returns Query
```
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
* defaults. Use the `setDefaultsOnInsert` option to override.
### Model.findOneAndUpdate()
##### Parameters
* [conditions] «Object»
* [update] «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](https://mongoosejs.com/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](../tutorials/lean).
+ [options.session=null] «ClientSession» The session associated with this query. See [transactions docs](../transactions).
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* [callback] «Function»
##### Returns:
* «Query»
Issues a mongodb findAndModify update command.
Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned.
#### Options:
* `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
* `upsert`: bool - creates the object if it doesn't exist. defaults to false.
* `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
* `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
* `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
* `runValidators`: if true, runs [update validators](../validation#update-validators) on this command. Update validators validate the update operation against the model's schema.
* `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
* `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
* `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
#### Examples:
```
A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options) // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update) // returns Query
A.findOneAndUpdate() // returns Query
```
#### Note:
All top level update keys which are not `atomic` operation names are treated as set operations:
#### Example:
```
var query = { name: 'borne' };
Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)
// is sent as
Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)
```
This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`.
#### Note:
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
* defaults. Use the `setDefaultsOnInsert` option to override.
`findAndModify` helpers support limited validation. You can enable these by setting the `runValidators` options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
```
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
```
### Model.geoSearch()
##### Parameters
* conditions «Object» an object that specifies the match condition (required)
* options «Object» for the geoSearch, some (near, maxDistance) are required
+ [options.lean] «Object|Boolean» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](https://mongoosejs.com/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](../tutorials/lean).
* [callback] «Function» optional callback
##### Returns:
* «Promise»
Implements `$geoSearch` functionality for Mongoose
This function does not trigger any middleware
#### Example:
```
var options = { near: [10, 10], maxDistance: 5 };
Locations.geoSearch({ type : "house" }, options, function(err, res) {
console.log(res);
});
```
#### Options:
* `near` {Array} x,y point to search for
* `maxDistance` {Number} the maximum distance from the point near that a result can be
* `limit` {Number} The maximum number of results to return
* `lean` {Object|Boolean} return the raw object instead of the Mongoose Model
### Model.hydrate()
##### Parameters
* obj «Object»
##### Returns:
* «Document» document instance
Shortcut for creating a new Document from existing raw data, pre-saved in the DB. The document returned has no paths marked as modified initially.
#### Example:
```
// hydrate previous data into a Mongoose document
var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
```
### Model.init()
##### Parameters
* [callback] «Function»
This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
Mongoose calls this function automatically when a model is created using [`mongoose.model()`](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-model) or [`connection.model()`](https://mongoosejs.com/docs/api.html#connection_Connection-model), so you don't need to call it. This function is also idempotent, so you may call it to get back a promise that will resolve when your indexes are finished building as an alternative to [`MyModel.on('index')`](../guide#indexes)
#### Example:
```
var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
// This calls `Event.init()` implicitly, so you don't need to call
// `Event.init()` on your own.
var Event = mongoose.model('Event', eventSchema);
Event.init().then(function(Event) {
// You can also use `Event.on('index')` if you prefer event emitters
// over promises.
console.log('Indexes are done building!');
});
```
### Model.insertMany()
##### Parameters
* doc(s) «Array|Object|\*»
* [options] «Object» see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany)
* [options.ordered «Boolean» = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`.
* [options.rawResult «Boolean» = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`.
* [callback] «Function» callback
##### Returns:
* «Promise»
Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than `.create()` because it only sends one operation to the server, rather than one for each document.
Mongoose always validates each document **before** sending `insertMany` to MongoDB. So if one document has a validation error, no documents will be saved, unless you set [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling).
This function does **not** trigger save middleware.
This function triggers the following middleware.
* `insertMany()`
#### Example:
```
var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
Movies.insertMany(arr, function(error, docs) {});
```
### Model.inspect()
Helper for console.log. Given a model named 'MyModel', returns the string `'Model { MyModel }'`.
#### Example:
```
const MyModel = mongoose.model('Test', Schema({ name: String }));
MyModel.inspect(); // 'Model { Test }'
console.log(MyModel); // Prints 'Model { Test }'
```
### Model.listIndexes()
##### Parameters
* [cb] «Function» optional callback
##### Returns:
* «Promise,undefined» Returns `undefined` if callback is specified, returns a promise if no callback.
Lists the indexes currently defined in MongoDB. This may or may not be the same as the indexes defined in your schema depending on whether you use the [`autoIndex` option](../guide#autoIndex) and if you build indexes manually.
### Model.mapReduce()
##### Parameters
* o «Object» an object specifying map-reduce options
* [callback] «Function» optional callback
##### Returns:
* «Promise»
Executes a mapReduce command.
`o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options.
This function does not trigger any middleware.
#### Example:
```
var o = {};
// `map()` and `reduce()` are run on the MongoDB server, not Node.js,
// these functions are converted to strings
o.map = function () { emit(this.name, 1) };
o.reduce = function (k, vals) { return vals.length };
User.mapReduce(o, function (err, results) {
console.log(results)
})
```
#### Other options:
* `query` {Object} query filter object.
* `sort` {Object} sort input objects using this key
* `limit` {Number} max number of documents
* `keeptemp` {Boolean, default:false} keep temporary data
* `finalize` {Function} finalize function
* `scope` {Object} scope variables exposed to map/reduce/finalize during execution
* `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
* `verbose` {Boolean, default:false} provide statistics on job execution time.
* `readPreference` {String}
* `out*` {Object, default: {inline:1}} sets the output target for the map reduce job.
#### \* out options:
* `{inline:1}` the results are returned in an array
* `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection
* `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions
* `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old
If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](../tutorials/lean); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).
#### Example:
```
var o = {};
// You can also define `map()` and `reduce()` as strings if your
// linter complains about `emit()` not being defined
o.map = 'function () { emit(this.name, 1) }';
o.reduce = 'function (k, vals) { return vals.length }';
o.out = { replace: 'createdCollectionNameForResults' }
o.verbose = true;
User.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime)
model.find().where('value').gt(10).exec(function (err, docs) {
console.log(docs);
});
})
// `mapReduce()` returns a promise. However, ES6 promises can only
// resolve to exactly one value,
o.resolveToObject = true;
var promise = User.mapReduce(o);
promise.then(function (res) {
var model = res.model;
var stats = res.stats;
console.log('map reduce took %d ms', stats.processtime)
return model.find().where('value').gt(10).exec();
}).then(function (docs) {
console.log(docs);
}).then(null, handleError).end()
```
### Model.populate()
##### Parameters
* docs «Document|Array» Either a single document or array of documents to populate.
* options «Object» A hash of key/val (path, options) used for population.
+ [options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries.
+ [options.getters=false] «boolean» if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](../schematypes#schematype-options).
+ [options.clone=false] «boolean» When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
+ [options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object.
+ [options.skipInvalidIds=false] «Boolean» By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type.
+ [options.options=null] «Object» Additional options like `limit` and `lean`.
* [callback(err,doc)] «Function» Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
##### Returns:
* «Promise»
Populates document references.
#### Available top-level options:
* path: space delimited path(s) to populate
* select: optional fields to select
* match: optional query conditions to match
* model: optional name of the model to use for population
* options: optional query options like sort, limit, etc
* justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default.
#### Examples:
```
// populates a single object
User.findById(id, function (err, user) {
var opts = [
{ path: 'company', match: { x: 1 }, select: 'name' },
{ path: 'notes', options: { limit: 10 }, model: 'override' }
];
User.populate(user, opts, function (err, user) {
console.log(user);
});
});
// populates an array of objects
User.find(match, function (err, users) {
var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];
var promise = User.populate(users, opts);
promise.then(console.log).end();
})
// imagine a Weapon model exists with two saved documents:
// { \_id: 389, name: 'whip' }
// { \_id: 8921, name: 'boomerang' }
// and this schema:
// new Schema({
// name: String,
// weapon: { type: ObjectId, ref: 'Weapon' }
// });
var user = { name: 'Indiana Jones', weapon: 389 };
Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
console.log(user.weapon.name); // whip
})
// populate many plain objects
var users = [{ name: 'Indiana Jones', weapon: 389 }]
users.push({ name: 'Batman', weapon: 8921 })
Weapon.populate(users, { path: 'weapon' }, function (err, users) {
users.forEach(function (user) {
console.log('%s uses a %s', users.name, user.weapon.name)
// Indiana Jones uses a whip
// Batman uses a boomerang
});
});
// Note that we didn't need to specify the Weapon model because
// it is in the schema's ref
```
### Model.prototype.$where
##### Type:
* «property»
Additional properties to attach to the query when calling `save()` and `isNew` is false.
### Model.prototype.$where()
##### Parameters
* argument «String|Function» is a javascript string or anonymous function
##### Returns:
* «Query»
Creates a `Query` and specifies a `$where` condition.
Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
```
Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
```
### Model.prototype.base
##### Type:
* «property»
Base Mongoose instance the model uses.
### Model.prototype.baseModelName
##### Type:
* «property»
If this is a discriminator model, `baseModelName` is the name of the base model.
### Model.prototype.collection
##### Type:
* «property»
Collection the model uses.
This property is read-only. Modifying this property is a no-op.
### Model.prototype.db
##### Type:
* «property»
Connection the model uses.
### Model.prototype.delete
##### Type:
* «property»
Alias for remove
### Model.prototype.deleteOne()
##### Parameters
* [fn] «function(err|product)» optional callback
##### Returns:
* «Promise» Promise
Removes this document from the db. Equivalent to `.remove()`.
#### Example:
```
product = await product.deleteOne();
await Product.findById(product._id); // null
```
### Model.prototype.discriminators
##### Type:
* «property»
Registered discriminators for this model.
### Model.prototype.increment()
Signal that we desire an increment of this documents version.
#### Example:
```
Model.findById(id, function (err, doc) {
doc.increment();
doc.save(function (err) { .. })
})
```
### Model.prototype.model()
##### Parameters
* name «String» model name
Returns another Model instance.
#### Example:
```
var doc = new Tank;
doc.model('User').findById(id, callback);
```
### Model.prototype.modelName
##### Type:
* «property»
The name of the model
### Model.prototype.remove()
##### Parameters
* [options] «Object»
+ [options.session=null] «Session» the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api#document_Document-%24session).
* [fn] «function(err|product)» optional callback
##### Returns:
* «Promise» Promise
Removes this document from the db.
#### Example:
```
product.remove(function (err, product) {
if (err) return handleError(err);
Product.findById(product._id, function (err, product) {
console.log(product) // null
})
})
```
As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors
#### Example:
```
product.remove().then(function (product) {
...
}).catch(function (err) {
assert.ok(err)
})
```
### Model.prototype.save()
##### Parameters
* [options] «Object» options optional options
+ [options.session=null] «Session» the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api#document_Document-%24session).
+ [options.safe] «Object» (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead.
+ [options.validateBeforeSave] «Boolean» set to false to save without validating.
+ [options.w] «Number|String» set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](../guide#writeConcern)
+ [options.j] «Boolean» set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](../guide#writeConcern)
+ [options.wtimeout] «Number» sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](../guide#writeConcern).
+ [options.checkKeys=true] «Boolean» the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names)
+ [options.timestamps=true] «Boolean» if `false` and [timestamps](guide#timestamps) are enabled, skip timestamps for this `save()`.
* [fn] «Function» optional callback
##### Returns:
* «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.
Saves this document.
#### Example:
```
product.sold = Date.now();
product = await product.save();
```
If save is successful, the returned promise will fulfill with the document saved.
#### Example:
```
const newProduct = await product.save();
newProduct === product; // true
```
### Model.prototype.schema
##### Type:
* «property»
Schema the model uses.
### Model.remove()
##### Parameters
* conditions «Object»
* [options] «Object»
+ [options.session=null] «Session» the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation.
* [callback] «Function»
##### Returns:
* «Query»
Removes all documents that match `conditions` from the collection. To remove just the first document that matches `conditions`, set the `single` option to true.
#### Example:
```
const res = await Character.remove({ name: 'Eddard Stark' });
res.deletedCount; // Number of documents removed
```
#### Note:
This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, Mongoose does not execute [document middleware](../middleware#types-of-middleware).
### Model.replaceOne()
##### Parameters
* filter «Object»
* doc «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`.
##### Returns:
* «Query»
Same as `update()`, except MongoDB replace the existing document with the given document (no atomic operators like `$set`).
#### Example:
```
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
```
This function triggers the following middleware.
* `replaceOne()`
### Model.startSession()
##### Parameters
* [options] «Object» see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
+ [options.causalConsistency=true] «Boolean» set to false to disable causal consistency
* [callback] «Function»
##### Returns:
* «Promise<ClientSession>» promise that resolves to a MongoDB driver `ClientSession`
*Requires MongoDB >= 3.6.0.* Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`.
This function does not trigger any middleware.
#### Example:
```
const session = await Person.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `doc` will always be null, even if reading from a replica set
// secondary. Without causal consistency, it is possible to
// get a doc back from the below query if the query reads from a
// secondary that is experiencing replication lag.
doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
```
### Model.syncIndexes()
##### Parameters
* [options] «Object» options to pass to `ensureIndexes()`
* [callback] «Function» optional callback
##### Returns:
* «Promise,undefined» Returns `undefined` if callback is specified, returns a promise if no callback.
Makes the indexes in MongoDB match the indexes defined in this model's schema. This function will drop any indexes that are not defined in the model's schema except the `_id` index, and build any indexes that are in your schema but not in MongoDB.
See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) for more information.
#### Example:
```
const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.createIndex({ age: 1 }); // Index is not in schema
// Will drop the 'age' index and create an index on `name`
await Customer.syncIndexes();
```
### Model.translateAliases()
##### Parameters
* raw «Object» fields/conditions that may contain aliased keys
##### Returns:
* «Object» the translated 'pure' fields/conditions
Translate any aliases fields/conditions so the final query or document object is pure
#### Example:
```
Character
.find(Character.translateAliases({
'名': 'Eddard Stark' // Alias for 'name'
})
.exec(function(err, characters) {})
```
#### Note:
Only translate arguments of object type anything else is returned raw
### Model.update()
##### Parameters
* filter «Object»
* doc «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.multi=false] «Boolean» whether multiple documents should be updated or just the first one that matches `filter`.
+ [options.runValidators=false] «Boolean» if true, runs [update validators](../validation#update-validators) on this command. Update validators validate the update operation against the model's schema.
+ [options.setDefaultsOnInsert=false] «Boolean» if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
+ [options.overwrite=false] «Boolean» By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`.
* [callback] «Function» params are (error, writeOpResult)
* [callback] «Function»
##### Returns:
* «Query»
Updates one document in the database without returning it.
This function triggers the following middleware.
* `update()`
#### Examples:
```
MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
const res = await MyModel.update({ name: 'Tobi' }, { ferret: true });
res.n; // Number of documents that matched `{ name: 'Tobi' }`
// Number of documents that were changed. If every doc matched already
// had `ferret` set to `true`, `nModified` will be 0.
res.nModified;
```
#### Valid options:
* `strict` (boolean): overrides the [schema-level `strict` option](../guide#strict) for this update
* `upsert` (boolean): whether to create the doc if it doesn't match (false)
* `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
* `omitUndefined` (boolean): If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
* `multi` (boolean): whether multiple documents should be updated (false)
* `runValidators`: if true, runs [update validators](../validation#update-validators) on this command. Update validators validate the update operation against the model's schema.
* `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
* `timestamps` (boolean): If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false)
All `update` values are cast to their appropriate SchemaTypes before being sent.
The `callback` function receives `(err, rawResponse)`.
* `err` is the error if any occurred
* `rawResponse` is the full response from Mongo
#### Note:
All top level keys which are not `atomic` operation names are treated as set operations:
#### Example:
```
var query = { name: 'borne' };
Model.update(query, { name: 'jason bourne' }, options, callback);
// is sent as
Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
// if overwrite option is false. If overwrite is true, sent without the $set wrapper.
```
This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`.
#### Note:
Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an \_id property, which causes Mongo to return a "Mod on \_id not allowed" error.
#### Note:
Mongoose casts values and runs setters when using update. The following features are **not** applied by default.
* [defaults](../defaults#the-setdefaultsoninsert-option)
* [validators](../validation#update-validators)
* middleware
If you need document middleware and fully-featured validation, load the document first and then use [`save()`](https://mongoosejs.com/docs/api.html#model_Model-save).
```
Model.findOne({ name: 'borne' }, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
})
```
### Model.updateMany()
##### Parameters
* filter «Object»
* doc «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`.
##### Returns:
* «Query»
Same as `update()`, except MongoDB will update *all* documents that match `filter` (as opposed to just the first one) regardless of the value of the `multi` option.
**Note** updateMany will *not* fire update middleware. Use `pre('updateMany')` and `post('updateMany')` instead.
#### Example:
```
const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
```
This function triggers the following middleware.
* `updateMany()`
### Model.updateOne()
##### Parameters
* filter «Object»
* doc «Object»
* [options] «Object» optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
+ [options.strict] «Boolean|String» overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
+ [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
+ [options.writeConcern=null] «Object» sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](../guide#writeConcern)
+ [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
+ [options.timestamps=null] «Boolean» If set to `false` and [schema-level timestamps](../guide#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
* [callback] «Function» params are (error, writeOpResult)
##### Returns:
* «Query»
Same as `update()`, except it does not support the `multi` or `overwrite` options.
* MongoDB will update *only* the first document that matches `filter` regardless of the value of the `multi` option.
* Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`.
#### Example:
```
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
```
This function triggers the following middleware.
* `updateOne()`
### Model.validate()
##### Parameters
* obj «Object»
* pathsToValidate «Array»
* [context] «Object»
* [callback] «Function»
##### Returns:
* «Promise,undefined»
Casts and validates the given object against this model's schema, passing the given `context` to custom validators.
#### Example:
```
const Model = mongoose.model('Test', Schema({
name: { type: String, required: true },
age: { type: Number, required: true }
});
try {
await Model.validate({ name: null }, ['name'])
} catch (err) {
err instanceof mongoose.Error.ValidationError; // true
Object.keys(err.errors); // ['name']
}
```
### Model.watch()
##### Parameters
* [pipeline] «Array»
* [options] «Object» see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch)
##### Returns:
* «ChangeStream» mongoose-specific change stream wrapper, inherits from EventEmitter
*Requires a replica set running MongoDB >= 3.6.0.* Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/).
This function does **not** trigger any middleware. In particular, it does **not** trigger aggregate middleware.
The ChangeStream object is an event emitter that emits the following events
---------------------------------------------------------------------------
* 'change': A change occurred, see below example
* 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates.
* 'end': Emitted if the underlying stream is closed
* 'close': Emitted if the underlying stream is closed
#### Example:
```
const doc = await Person.create({ name: 'Ned Stark' });
const changeStream = Person.watch().on('change', change => console.log(change));
// Will print from the above `console.log()`:
// { \_id: { \_data: ... },
// operationType: 'delete',
// ns: { db: 'mydb', coll: 'Person' },
// documentKey: { \_id: 5a51b125c5500f5aa094c7bd } }
await doc.remove();
```
### Model.where()
##### Parameters
* path «String»
* [val] «Object» optional value
##### Returns:
* «Query»
Creates a Query, applies the passed conditions, and returns the Query.
For example, instead of writing:
```
User.find({age: {$gte: 21, $lte: 65}}, callback);
```
we can instead write:
```
User.where('age').gte(21).lte(65).exec(callback);
```
Since the Query class also supports `where` you can continue chaining
```
User
.where('age').gte(21).lte(65)
.where('name', /^b/i)
... etc
```
| programming_docs |
mongoose Schematype Schematype
==========
### SchemaType()
##### Parameters
* path «String»
* [options] «SchemaTypeOptions» See [SchemaTypeOptions docs](schematypeoptions)
* [instance] «String»
SchemaType constructor. Do **not** instantiate `SchemaType` directly. Mongoose converts your schema paths into SchemaTypes automatically.
#### Example:
```
const schema = new Schema({ name: String });
schema.path('name') instanceof SchemaType; // true
```
### SchemaType.cast()
##### Parameters
* caster «Function|false» Function that casts arbitrary values to this type, or throws an error if casting failed
##### Returns:
* «Function»
Get/set the function used to cast arbitrary values to this type.
#### Example:
```
// Disallow `null` for numbers, and don't try to cast any values to
// numbers, so even strings like '123' will cause a CastError.
mongoose.Number.cast(function(v) {
assert.ok(v === undefined || typeof v === 'number');
return v;
});
```
### SchemaType.checkRequired()
##### Parameters
* fn «Function»
##### Returns:
* «Function»
Override the function the required validator uses to check whether a value passes the `required` check. Override this on the individual SchemaType.
#### Example:
```
// Use this to allow empty strings to pass the `required` validator
mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
```
### SchemaType.get()
##### Parameters
* getter «Function»
##### Returns:
* «this»
Attaches a getter for all instances of this schema type.
#### Example:
```
// Make all numbers round down
mongoose.Number.get(function(v) { return Math.floor(v); });
```
### SchemaType.prototype.default()
##### Parameters
* val «Function|any» the default value
##### Returns:
* «defaultValue»
Sets a default value for this SchemaType.
#### Example:
```
var schema = new Schema({ n: { type: Number, default: 10 })
var M = db.model('M', schema)
var m = new M;
console.log(m.n) // 10
```
Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.
#### Example:
```
// values are cast:
var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
var M = db.model('M', schema)
var m = new M;
console.log(m.aNumber) // 4.815162342
// default unique objects for Mixed types:
var schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default(function () {
return {};
});
// if we don't use a function to return object literals for Mixed defaults,
// each document will receive a reference to the same object literal creating
// a "shared" object instance:
var schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default({});
var M = db.model('M', schema);
var m1 = new M;
m1.mixed.added = 1;
console.log(m1.mixed); // { added: 1 }
var m2 = new M;
console.log(m2.mixed); // { added: 1 }
```
### SchemaType.prototype.get()
##### Parameters
* fn «Function»
##### Returns:
* «SchemaType» this
Adds a getter to this schematype.
#### Example:
```
function dob (val) {
if (!val) return val;
return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
}
// defining within the schema
var s = new Schema({ born: { type: Date, get: dob })
// or by retreiving its SchemaType
var s = new Schema({ born: Date })
s.path('born').get(dob)
```
Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.
Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:
```
function obfuscate (cc) {
return '\*\*\*\*-\*\*\*\*-\*\*\*\*-' + cc.slice(cc.length-4, cc.length);
}
var AccountSchema = new Schema({
creditCardNumber: { type: String, get: obfuscate }
});
var Account = db.model('Account', AccountSchema);
Account.findById(id, function (err, found) {
console.log(found.creditCardNumber); // '\*\*\*\*-\*\*\*\*-\*\*\*\*-1234'
});
```
Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.
```
function inspector (val, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return schematype.path + ' is not';
}
}
var VirusSchema = new Schema({
name: { type: String, required: true, get: inspector },
taxonomy: { type: String, get: inspector }
})
var Virus = db.model('Virus', VirusSchema);
Virus.findById(id, function (err, virus) {
console.log(virus.name); // name is required
console.log(virus.taxonomy); // taxonomy is not
})
```
### SchemaType.prototype.immutable()
##### Parameters
* bool «Boolean»
##### Returns:
* «SchemaType» this
Defines this path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has [`isNew: true`](https://mongoosejs.com/docs/api.html#document_Document-isNew).
#### Example:
```
const schema = new Schema({
name: { type: String, immutable: true },
age: Number
});
const Model = mongoose.model('Test', schema);
await Model.create({ name: 'test' });
const doc = await Model.findOne();
doc.isNew; // false
doc.name = 'new name';
doc.name; // 'test', because `name` is immutable
```
Mongoose also prevents changing immutable properties using `updateOne()` and `updateMany()` based on [strict mode](../guide#strict).
#### Example:
```
// Mongoose will strip out the `name` update, because `name` is immutable
Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
// If `strict` is set to 'throw', Mongoose will throw an error if you
// update `name`
const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
then(() => null, err => err);
err.name; // StrictModeError
// If `strict` is `false`, Mongoose allows updating `name` even though
// the property is immutable.
Model.updateOne({}, { name: 'test2' }, { strict: false });
```
### SchemaType.prototype.index()
##### Parameters
* options «Object|Boolean|String»
##### Returns:
* «SchemaType» this
Declares the index options for this schematype.
#### Example:
```
var s = new Schema({ name: { type: String, index: true })
var s = new Schema({ loc: { type: [Number], index: 'hashed' })
var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
s.path('my.path').index(true);
s.path('my.date').index({ expires: 60 });
s.path('my.path').index({ unique: true, sparse: true });
```
#### NOTE:
*Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) by default. If `background` is set to `false`, MongoDB will not execute any read/write operations you send until the index build. Specify `background: false` to override Mongoose's default.*
### SchemaType.prototype.ref()
##### Parameters
* ref «String|Model|Function» either a model name, a [Model](../models), or a function that returns a model name or model.
##### Returns:
* «SchemaType» this
Set the model that this path refers to. This is the option that [populate](../populate) looks at to determine the foreign collection it should query.
#### Example:
```
const userSchema = new Schema({ name: String });
const User = mongoose.model('User', userSchema);
const postSchema = new Schema({ user: mongoose.ObjectId });
postSchema.path('user').ref('User'); // By model name
postSchema.path('user').ref(User); // Can pass the model as well
// Or you can just declare the `ref` inline in your schema
const postSchema2 = new Schema({
user: { type: mongoose.ObjectId, ref: User }
});
```
### SchemaType.prototype.required()
##### Parameters
* required «Boolean|Function|Object» enable/disable the validator, or function that returns required boolean, or options object
+ [options.isRequired] «Boolean|Function» enable/disable the validator, or function that returns required boolean
+ [options.ErrorConstructor] «Function» custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.
* [message] «String» optional custom error message
##### Returns:
* «SchemaType» this
Adds a required validator to this SchemaType. The validator gets added to the front of this SchemaType's validators array using `unshift()`.
#### Example:
```
var s = new Schema({ born: { type: Date, required: true })
// or with custom error message
var s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
// or with a function
var s = new Schema({
userId: ObjectId,
username: {
type: String,
required: function() { return this.userId != null; }
}
})
// or with a function and a custom message
var s = new Schema({
userId: ObjectId,
username: {
type: String,
required: [
function() { return this.userId != null; },
'username is required if id is specified'
]
}
})
// or through the path API
s.path('name').required(true);
// with custom error messaging
s.path('name').required(true, 'grrr :( ');
// or make a path conditionally required based on a function
var isOver18 = function() { return this.age >= 18; };
s.path('voterRegistrationId').required(isOver18);
```
The required validator uses the SchemaType's `checkRequired` function to determine whether a given value satisfies the required validator. By default, a value satisfies the required validator if `val != null` (that is, if the value is not null nor undefined). However, most built-in mongoose schema types override the default `checkRequired` function:
### SchemaType.prototype.select()
##### Parameters
* val «Boolean»
##### Returns:
* «SchemaType» this
Sets default `select()` behavior for this path.
Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level.
#### Example:
```
T = db.model('T', new Schema({ x: { type: String, select: true }}));
T.find(..); // field x will always be selected ..
// .. unless overridden;
T.find().select('-x').exec(callback);
```
### SchemaType.prototype.set()
##### Parameters
* fn «Function»
##### Returns:
* «SchemaType» this
Adds a setter to this schematype.
#### Example:
```
function capitalize (val) {
if (typeof val !== 'string') val = '';
return val.charAt(0).toUpperCase() + val.substring(1);
}
// defining within the schema
var s = new Schema({ name: { type: String, set: capitalize }});
// or with the SchemaType
var s = new Schema({ name: String })
s.path('name').set(capitalize);
```
Setters allow you to transform the data before it gets to the raw mongodb document or query.
Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, [[email protected]](mailto:[email protected]) can be registered for 2 accounts via [[email protected]](mailto:[email protected]) and [[email protected]](mailto:[email protected]).
You can set up email lower case normalization easily via a Mongoose setter.
```
function toLower(v) {
return v.toLowerCase();
}
var UserSchema = new Schema({
email: { type: String, set: toLower }
});
var User = db.model('User', UserSchema);
var user = new User({email: '[[email protected]](mailto:[email protected])'});
console.log(user.email); // '[[email protected]](mailto:[email protected])'
// or
var user = new User();
user.email = '[[email protected]](mailto:[email protected])';
console.log(user.email); // '[[email protected]](mailto:[email protected])'
User.updateOne({ _id: _id }, { $set: { email: '[[email protected]](mailto:[email protected])' } }); // update to '[[email protected]](mailto:[email protected])'
```
As you can see above, setters allow you to transform the data before it stored in MongoDB, or before executing a query.
*NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function.*
```
new Schema({ email: { type: String, lowercase: true }})
```
Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.
```
function inspector (val, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return val;
}
}
var VirusSchema = new Schema({
name: { type: String, required: true, set: inspector },
taxonomy: { type: String, set: inspector }
})
var Virus = db.model('Virus', VirusSchema);
var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
console.log(v.name); // name is required
console.log(v.taxonomy); // Parvovirinae
```
You can also use setters to modify other properties on the document. If you're setting a property `name` on a document, the setter will run with `this` as the document. Be careful, in mongoose 5 setters will also run when querying by `name` with `this` as the query.
```
const nameSchema = new Schema({ name: String, keywords: [String] });
nameSchema.path('name').set(function(v) {
// Need to check if `this` is a document, because in mongoose 5
// setters will also run on queries, in which case `this` will be a
// mongoose query object.
if (this instanceof Document && v != null) {
this.keywords = v.split(' ');
}
return v;
});
```
### SchemaType.prototype.sparse()
##### Parameters
* bool «Boolean»
##### Returns:
* «SchemaType» this
Declares a sparse index.
#### Example:
```
var s = new Schema({ name: { type: String, sparse: true } });
s.path('name').index({ sparse: true });
```
### SchemaType.prototype.text()
##### Parameters
* bool «Boolean»
##### Returns:
* «SchemaType» this
Declares a full text index.
### Example:
```
var s = new Schema({name : {type: String, text : true })
s.path('name').index({text : true});
```
### SchemaType.prototype.unique()
##### Parameters
* bool «Boolean»
##### Returns:
* «SchemaType» this
Declares an unique index.
#### Example:
```
var s = new Schema({ name: { type: String, unique: true }});
s.path('name').index({ unique: true });
```
*NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error.*
### SchemaType.prototype.validate()
##### Parameters
* obj «RegExp|Function|Object» validator function, or hash describing options
+ [obj.validator] «Function» validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails.
+ [obj.message] «String|Function» optional error message. If function, should return the error message as a string
+ [obj.propsParameter=false] «Boolean» If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators.
* [errorMsg] «String|Function» optional error message. If function, should return the error message as a string
* [type] «String» optional validator type
##### Returns:
* «SchemaType» this
Adds validator(s) for this document path.
Validators always receive the value to validate as their first argument and must return `Boolean`. Returning `false` or throwing an error means validation failed.
The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used.
#### Examples:
```
// make sure every value is equal to "something"
function validator (val) {
return val == 'something';
}
new Schema({ name: { type: String, validate: validator }});
// with a custom error message
var custom = [validator, 'Uh oh, {PATH} does not equal "something".']
new Schema({ name: { type: String, validate: custom }});
// adding many validators at a time
var many = [
{ validator: validator, msg: 'uh oh' }
, { validator: anotherValidator, msg: 'failed' }
]
new Schema({ name: { type: String, validate: many }});
// or utilizing SchemaType methods directly:
var schema = new Schema({ name: 'string' });
schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');
```
#### Error message templates:
From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides `{PATH}` and `{VALUE}` too. To find out more, details are available [here](#error_messages_MongooseError.messages).
If Mongoose's built-in error message templating isn't enough, Mongoose supports setting the `message` property to a function.
```
schema.path('name').validate({
validator: function() { return v.length > 5; },
// `errors['name']` will be "name must have length 5, got 'foo'"
message: function(props) {
return `${props.path} must have length 5, got '${props.value}'`;
}
});
```
To bypass Mongoose's error messages and just copy the error message that the validator throws, do this:
```
schema.path('name').validate({
validator: function() { throw new Error('Oops!'); },
// `errors['name']` will be "Oops!"
message: function(props) { return props.reason.message; }
});
```
#### Asynchronous validation:
Mongoose supports validators that return a promise. A validator that returns a promise is called an *async validator*. Async validators run in parallel, and `validate()` will wait until all async validators have settled.
```
schema.path('name').validate({
validator: function (value) {
return new Promise(function (resolve, reject) {
resolve(false); // validation failed
});
}
});
```
You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.
Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate).
If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along.
```
var conn = mongoose.createConnection(..);
conn.on('error', handleError);
var Product = conn.model('Product', yourSchema);
var dvd = new Product(..);
dvd.save(); // emits error on the `conn` above
```
If you want to handle these errors at the Model level, add an `error` listener to your Model as shown below.
```
// registering an error listener on the Model lets us handle errors more locally
Product.on('error', handleError);
```
mongoose Query Casting Query Casting
=============
The first parameter to [`Model.find()`](https://mongoosejs.com/docs/api.html#model_Model.find), [`Query#find()`](https://mongoosejs.com/docs/api.html#query_Query-find), [`Model.findOne()`](https://mongoosejs.com/docs/api.html#model_Model.findOne), etc. is called `filter`. In older content this parameter is sometimes called `query` or `conditions`. For example:
```
const query = Character.find({ name: 'Jean-Luc Picard' });
query.getFilter(); // `{ name: 'Jean-Luc Picard' }`
// Subsequent chained calls merge new properties into the filter
query.find({ age: { $gt: 50 } });
query.getFilter(); // `{ name: 'Jean-Luc Picard', age: { $gt: 50 } }`
```
When you execute the query using [`Query#exec()`](https://mongoosejs.com/docs/api.html#query_Query-exec) or [`Query#then()`](https://mongoosejs.com/docs/api.html#query_Query-then), Mongoose *casts* the filter to match your schema.
```
// Note that `\_id` and `age` are strings. Mongoose will cast `\_id` to
// a MongoDB ObjectId and `age.$gt` to a number.
const query = Character.findOne({
_id: '5cdc267dd56b5662b7b7cc0c',
age: { $gt: '50' }
});
// `{ \_id: '5cdc267dd56b5662b7b7cc0c', age: { $gt: '50' } }`
// Query hasn't been executed yet, so Mongoose hasn't casted the filter.
query.getFilter();
const doc = await query.exec();
doc.name; // "Jean-Luc Picard"
// Mongoose casted the filter, so `\_id` became an ObjectId and `age.$gt`
// became a number.
query.getFilter()._id instanceof mongoose.Types.ObjectId; // true
typeof query.getFilter().age.$gt === 'number'; // true
```
If Mongoose fails to cast the filter to your schema, your query will throw a `CastError`.
```
const query = Character.findOne({ age: { $lt: 'not a number' } });
const err = await query.exec().then(() => null, err => err);
err instanceof mongoose.CastError; // true
// Cast to number failed for value "not a number" at path "age" for
// model "Character"
err.message;
```
The `strictQuery` Option
------------------------
By default, Mongoose does **not** cast filter properties that aren't in your schema.
```
const query = Character.findOne({ notInSchema: { $lt: 'not a number' } });
// No error because `notInSchema` is not defined in the schema
await query.exec();
```
You can configure this behavior using the [`strictQuery` option for schemas](../guide#strictQuery). This option is analagous to the [`strict` option](../guide#strict). Setting `strictQuery` to `true` removes non-schema properties from the filter:
```
mongoose.deleteModel('Character');
const schema = new mongoose.Schema({ name: String, age: Number }, {
strictQuery: true
});
Character = mongoose.model('Character', schema);
const query = Character.findOne({ notInSchema: { $lt: 'not a number' } });
await query.exec();
query.getFilter(); // Empty object `{}`, Mongoose removes `notInSchema`
```
To make Mongoose throw an error if your `filter` has a property that isn't in the schema, set `strictQuery` to `'throw'`:
```
mongoose.deleteModel('Character');
const schema = new mongoose.Schema({ name: String, age: Number }, {
strictQuery: 'throw'
});
Character = mongoose.model('Character', schema);
const query = Character.findOne({ notInSchema: { $lt: 'not a number' } });
const err = await query.exec().then(() => null, err => err);
err.name; // 'StrictModeError'
// Path "notInSchema" is not in schema and strictQuery is 'throw'.
err.message;
```
Implicit `$in`
--------------
Because of schemas, Mongoose knows what types fields should be, so it can provide some neat syntactic sugar. For example, if you forget to put [`$in`](https://docs.mongodb.com/manual/reference/operator/query/in/) on a non-array field, Mongoose will add `$in` for you.
```
// Normally wouldn't find anything because `name` is a string, but
// Mongoose automatically inserts `$in`
const query = Character.findOne({ name: ['Jean-Luc Picard', 'Will Riker'] });
const doc = await query.exec();
doc.name; // "Jean-Luc Picard"
// `{ name: { $in: ['Jean-Luc Picard', 'Will Riker'] } }`
query.getFilter();
```
| programming_docs |
mongoose Getters/Setters in Mongoose Getters/Setters in Mongoose
===========================
Mongoose getters and setters allow you to execute custom logic when getting or setting a property on a [Mongoose document](../documents). Getters let you transform data in MongoDB into a more user friendly form, and setters let you transform user data before it gets to MongoDB.
Getters
-------
Suppose you have a `User` collection and you want to obfuscate user emails to protect your users' privacy. Below is a basic `userSchema` that obfuscates the user's email address.
```
const userSchema = new Schema({
email: {
type: String,
get: obfuscate
}
});
// Mongoose passes the raw value in MongoDB `email` to the getter
function obfuscate(email) {
const separatorIndex = email.indexOf('@');
if (separatorIndex < 3) {
// '[email protected]' -> '\*\*@gmail.com'
return email.slice(0, separatorIndex).replace(/./g, '\*') +
email.slice(separatorIndex);
}
// '[email protected]' -> 'te\*\*\*\*@gmail.com'
return email.slice(0, 2) +
email.slice(2, separatorIndex).replace(/./g, '\*') +
email.slice(separatorIndex);
}
const User = mongoose.model('User', userSchema);
const user = new User({ email: '[email protected]' });
user.email; // \*\*@gmail.com
```
Keep in mind that getters do **not** impact the underlying data stored in MongoDB. If you save `user`, the `email` property will be '[email protected]' in the database.
By default, Mongoose executes getters when converting a document to JSON, including [Express' `res.json()` function](http://expressjs.com/en/4x/api.html#res.json).
```
app.get(function(req, res) {
return User.findOne().
// The `email` getter will run here
then(doc => res.json(doc)).
catch(err => res.status(500).json({ message: err.message }));
});
```
To disable running getters when converting a document to JSON, set the [`toJSON.getters` option to `false` in your schema](../guide#toJSON) as shown below.
```
const userSchema = new Schema({
email: {
type: String,
get: obfuscate
}
}, { toJSON: { getters: false } });
```
To skip getters on a one-off basis, use [`user.get()` with the `getters` option set to `false`](../api/document#document_Document-get) as shown below.
```
user.get('email', null, { getters: false }); // '[email protected]'
```
Setters
-------
Suppose you want to make sure all user emails in your database are lowercased to make it easy to search without worrying about case. Below is an example `userSchema` that ensures emails are lowercased.
```
const userSchema = new Schema({
email: {
type: String,
set: v => v.toLowerCase()
}
});
const User = mongoose.model('User', userSchema);
const user = new User({ email: '[email protected]' });
user.email; // '[email protected]'
// The raw value of `email` is lowercased
user.get('email', null, { getters: false }); // '[email protected]'
user.set({ email: '[email protected]' });
user.email; // '[email protected]'
```
Mongoose also runs setters on update operations, like [`updateOne()`](../api/query#query_Query-updateOne). Mongoose will [upsert a document](https://masteringjs.io/tutorials/mongoose/upsert) with a lowercased `email` in the below example.
```
await User.updateOne({}, { email: '[email protected]' }, { upsert: true });
const doc = await User.findOne();
doc.email; // '[email protected]'
```
In a setter function, `this` can be either the document being set or the query being run. If you don't want your setter to run when you call `updateOne()`, you add an if statement that checks if `this` is a Mongoose document as shown below.
```
const userSchema = new Schema({
email: {
type: String,
set: toLower
}
});
function toLower(email) {
// Don't transform `email` if using `updateOne()` or `updateMany()`
if (!(this instanceof mongoose.Document)) {
return email;
}
return email.toLowerCase();
}
const User = mongoose.model('User', userSchema);
await User.updateOne({}, { email: '[email protected]' }, { upsert: true });
const doc = await User.findOne();
doc.email; // '[email protected]'
```
Differences vs ES6 Getters/Setters
----------------------------------
Mongoose setters are different from [ES6 setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) because they allow you to transform the value being set. With ES6 setters, you would need to store an internal `_email` property to use a setter. With Mongoose, you do **not** need to define an internal `_email` property or define a corresponding getter for `email`.
```
class User {
// This won't convert the email to lowercase! That's because `email`
// is just a setter, the actual `email` property doesn't store any data.
set email(v) {
return v.toLowerCase();
}
}
const user = new User();
user.email = '[email protected]';
user.email; // undefined
```
mongoose Faster Mongoose Queries With Lean Faster Mongoose Queries With Lean
=================================
The [lean option](https://mongoosejs.com/docs/api.html#query_Query-lean) tells Mongoose to skip [hydrating](https://mongoosejs.com/docs/api.html#model_Model.hydrate) the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), **not** [Mongoose documents](../documents). In this tutorial, you'll learn more about the tradeoffs of using `lean()`.
* [Using Lean](#using-lean)
* [Lean and Populate](#lean-and-populate)
* [When to Use Lean](#when-to-use-lean)
* [Plugins](#plugins)
Using Lean
----------
By default, Mongoose queries return an instance of the [Mongoose `Document` class](https://mongoosejs.com/docs/api.html#Document). Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the `lean` option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.
```
const leanDoc = await MyModel.findOne().lean();
```
How much smaller are lean documents? Here's a comparison.
```
const schema = new mongoose.Schema({ name: String });
const MyModel = mongoose.model('Test', schema);
await MyModel.create({ name: 'test' });
// Module that estimates the size of an object in memory
const sizeof = require('object-sizeof');
const normalDoc = await MyModel.findOne();
// To enable the `lean` option for a query, use the `lean()` function.
const leanDoc = await MyModel.findOne().lean();
sizeof(normalDoc); // >= 1000
sizeof(leanDoc); // 86, 10x smaller!
// In case you were wondering, the JSON form of a Mongoose doc is the same
// as the POJO. This additional memory only affects how much memory your
// Node.js process uses, not how much data is sent over the network.
JSON.stringify(normalDoc).length === JSON.stringify(leanDoc.length); // true
```
Under the hood, after executing a query, Mongoose converts the query results from POJOs to Mongoose documents. If you turn on the `lean` option, Mongoose skips this step.
```
const normalDoc = await MyModel.findOne();
const leanDoc = await MyModel.findOne().lean();
normalDoc instanceof mongoose.Document; // true
normalDoc.constructor.name; // 'model'
leanDoc instanceof mongoose.Document; // false
leanDoc.constructor.name; // 'Object'
```
The downside of enabling `lean` is that lean docs don't have:
* Change tracking
* Casting and validation
* Getters and setters
* Virtuals
* `save()`
For example, the following code sample shows that the `Person` model's getters and virtuals don't run if you enable `lean`.
```
// Define a `Person` model. Schema has 2 custom getters and a `fullName`
// virtual. Neither the getters nor the virtuals will run if lean is enabled.
const personSchema = new mongoose.Schema({
firstName: {
type: String,
get: capitalizeFirstLetter
},
lastName: {
type: String,
get: capitalizeFirstLetter
}
});
personSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
function capitalizeFirstLetter(v) {
// Convert 'bob' -> 'Bob'
return v.charAt(0).toUpperCase() + v.substr(1);
}
const Person = mongoose.model('Person', personSchema);
// Create a doc and load it as a lean doc
await Person.create({ firstName: 'benjamin', lastName: 'sisko' });
const normalDoc = await Person.findOne();
const leanDoc = await Person.findOne().lean();
normalDoc.fullName; // 'Benjamin Sisko'
normalDoc.firstName; // 'Benjamin', because of `capitalizeFirstLetter()`
normalDoc.lastName; // 'Sisko', because of `capitalizeFirstLetter()`
leanDoc.fullName; // undefined
leanDoc.firstName; // 'benjamin', custom getter doesn't run
leanDoc.lastName; // 'sisko', custom getter doesn't run
```
Lean and Populate
-----------------
[Populate](../populate) works with `lean()`. If you use both `populate()` and `lean()`, the `lean` option propagates to the populated documents as well. In the below example, both the top-level 'Group' documents and the populated 'Person' documents will be lean.
```
// Create models
const Group = mongoose.model('Group', new mongoose.Schema({
name: String,
members: [{ type: mongoose.ObjectId, ref: 'Person' }]
}));
const Person = mongoose.model('Person', new mongoose.Schema({
name: String
}));
// Initialize data
const people = await Person.create([
{ name: 'Benjamin Sisko' },
{ name: 'Kira Nerys' }
]);
await Group.create({
name: 'Star Trek: Deep Space Nine Characters',
members: people.map(p => p._id)
});
// Execute a lean query
const group = await Group.findOne().lean().populate('members');
group.members[0].name; // 'Benjamin Sisko'
group.members[1].name; // 'Kira Nerys'
// Both the `group` and the populated `members` are lean.
group instanceof mongoose.Document; // false
group.members[0] instanceof mongoose.Document; // false
group.members[1] instanceof mongoose.Document; // false
```
[Virtual populate](../populate#populate-virtuals) also works with lean.
```
// Create models
const groupSchema = new mongoose.Schema({ name: String });
groupSchema.virtual('members', {
ref: 'Person',
localField: '\_id',
foreignField: 'groupId'
});
const Group = mongoose.model('Group', groupSchema);
const Person = mongoose.model('Person', new mongoose.Schema({
name: String,
groupId: mongoose.ObjectId
}));
// Initialize data
const g = await Group.create({ name: 'DS9 Characters' });
const people = await Person.create([
{ name: 'Benjamin Sisko', groupId: g._id },
{ name: 'Kira Nerys', groupId: g._id }
]);
// Execute a lean query
const group = await Group.findOne().lean().populate({
path: 'members',
options: { sort: { name: 1 } }
});
group.members[0].name; // 'Benjamin Sisko'
group.members[1].name; // 'Kira Nerys'
// Both the `group` and the populated `members` are lean.
group instanceof mongoose.Document; // false
group.members[0] instanceof mongoose.Document; // false
group.members[1] instanceof mongoose.Document; // false
```
When to Use Lean
----------------
If you're executing a query and sending the results without modification to, say, an [Express response](http://expressjs.com/en/4x/api.html#res), you should use lean. In general, if you do not modify the query results and do not use [custom getters](https://mongoosejs.com/docs/api.html#schematype_SchemaType-get), you should use `lean()`. If you modify the query results or rely on features like getters or [transforms](https://mongoosejs.com/docs/api.html#document_Document-toObject), you should not use `lean()`.
Below is an example of an [Express route](http://expressjs.com/en/guide/routing.html) that is a good candidate for `lean()`. This route does not modify the `person` doc and doesn't rely on any Mongoose-specific functionality.
```
// As long as you don't need any of the Person model's virtuals or getters,
// you can use `lean()`.
app.get('/person/:id', function(req, res) {
Person.findOne({ _id: req.params.id }).lean().
then(person => res.json({ person })).
catch(error => res.json({ error: error.message }));
});
```
Below is an example of an Express route that should **not** use `lean()`. As a general rule of thumb, `GET` routes are good candidates for `lean()` in a [RESTful API](https://en.wikipedia.org/wiki/Representational_state_transfer). On the other hand, `PUT`, `POST`, etc. routes generally should not use `lean()`.
```
// This route should \*\*not\*\* use `lean()`, because lean means no `save()`.
app.put('/person/:id', function(req, res) {
Person.findOne({ _id: req.params.id }).
then(person => {
assert.ok(person);
Object.assign(person, req.body);
return person.save();
}).
then(person => res.json({ person })).
catch(error => res.json({ error: error.message }));
});
```
Remember that virtuals do **not** end up in `lean()` query results. Use the [mongoose-lean-virtuals plugin](http://plugins.mongoosejs.io/plugins/lean-virtuals) to add virtuals to your lean query results.
Plugins
-------
Using `lean()` bypasses all Mongoose features, including <virtuals>, [getters/setters](getters-setters), and [defaults](https://mongoosejs.com/docs/api.html#schematype_SchemaType-default). If you want to use these features with `lean()`, you need to use the corresponding plugin:
* [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals)
* [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters)
* [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults)
However, you need to keep in mind that Mongoose does not hydrate lean documents, so `this` will be a POJO in virtuals, getters, and default functions.
```
const schema = new Schema({ name: String });
schema.plugin(require('mongoose-lean-virtuals'));
schema.virtual('lowercase', function() {
this instanceof mongoose.Document; // false
this.name; // Works
this.get('name'); // Crashes because `this` is not a Mongoose document.
});
```
mongoose Mongoose Virtuals Mongoose Virtuals
=================
In Mongoose, a virtual is a property that is **not** stored in MongoDB. Virtuals are typically used for computed properties on documents.
* [Your First Virtual](#your-first-virtual)
* [Virtual Setters](#virtual-setters)
* [Virtuals in JSON](#virtuals-in-json)
* [Virtuals with Lean](#virtuals-with-lean)
* [Limitations](#limitations)
* [Populate](#populate)
* [Further Reading](#further-reading)
Your First Virtual
------------------
Suppose you have a `User` model. Every user has an `email`, but you also want the email's domain. For example, the domain portion of '[email protected]' is 'gmail.com'.
Below is one way to implement the `domain` property using a virtual. You define virtuals on a schema using the [`Schema#virtual()` function](../api/schema#schema_Schema-virtual).
```
const userSchema = mongoose.Schema({
email: String
});
// Create a virtual property `domain` that's computed from `email`.
userSchema.virtual('domain').get(function() {
return this.email.slice(this.email.indexOf('@') + 1);
});
const User = mongoose.model('User', userSchema);
let doc = await User.create({ email: '[email protected]' });
// `domain` is now a property on User documents.
doc.domain; // 'gmail.com'
```
The `Schema#virtual()` function returns a [`VirtualType` object](../api/virtualtype). Unlike normal document properties, virtuals do not have any underlying value and Mongoose does not do any type coercion on virtuals. However, virtuals do have [getters and setters](getters-setters), which make them ideal for computed properties, like the `domain` example above.
Virtual Setters
---------------
You can also use virtuals to set multiple properties at once as an alternative to [custom setters on normal properties](getters-setters#setters). For example, suppose you have two string properties: `firstName` and `lastName`. You can create a virtual property `fullName` that lets you set both of these properties at once. The key detail is that, in virtual getters and setters, `this` refers to the document the virtual is attached to.
```
const userSchema = mongoose.Schema({
firstName: String,
lastName: String
});
// Create a virtual property `fullName` with a getter and setter.
userSchema.virtual('fullName').
get(function() { return `${this.firstName} ${this.lastName}`; }).
set(function(v) {
// `v` is the value being set, so use the value to set
// `firstName` and `lastName`.
const firstName = v.substring(0, v.indexOf(' '));
const lastName = v.substring(v.indexOf(' ') + 1);
this.set({ firstName, lastName });
});
const User = mongoose.model('User', userSchema);
const doc = new User();
// Vanilla JavaScript assignment triggers the setter
doc.fullName = 'Jean-Luc Picard';
doc.fullName; // 'Jean-Luc Picard'
doc.firstName; // 'Jean-Luc'
doc.lastName; // 'Picard'
```
Virtuals in JSON
----------------
By default, Mongoose does not include virtuals when you convert a document to JSON. For example, if you pass a document to [Express' `res.json()` function](http://expressjs.com/en/4x/api.html#res.json), virtuals will **not** be included by default.
To include virtuals in `res.json()`, you need to set the [`toJSON` schema option](../guide#toJSON) to `{ virtuals: true }`.
```
const opts = { toJSON: { virtuals: true } };
const userSchema = mongoose.Schema({
_id: Number,
email: String
}, opts);
// Create a virtual property `domain` that's computed from `email`.
userSchema.virtual('domain').get(function() {
return this.email.slice(this.email.indexOf('@') + 1);
});
const User = mongoose.model('User', userSchema);
const doc = new User({ _id: 1, email: '[email protected]' });
doc.toJSON().domain; // 'gmail.com'
// {"\_id":1,"email":"[email protected]","domain":"gmail.com","id":"1"}
JSON.stringify(doc);
// To skip applying virtuals, pass `virtuals: false` to `toJSON()`
doc.toJSON({ virtuals: false }).domain; // undefined
```
Virtuals with Lean
------------------
Virtuals are properties on Mongoose documents. If you use the [lean option](lean), that means your queries return POJOs rather than full Mongoose documents. That means no virtuals if you use [`lean()`](../api/query#query_Query-lean).
```
const fullDoc = await User.findOne();
fullDoc.domain; // 'gmail.com'
const leanDoc = await User.findOne().lean();
leanDoc.domain; // undefined
```
If you use `lean()` for performance, but still need virtuals, Mongoose has an [officially supported `mongoose-lean-virtuals` plugin](https://plugins.mongoosejs.io/plugins/lean-virtuals) that decorates lean documents with virtuals.
Limitations
-----------
Mongoose virtuals are **not** stored in MongoDB, which means you can't query based on Mongoose virtuals.
```
// Will \*\*not\*\* find any results, because `domain` is not stored in
// MongoDB.
const doc = await User.findOne({ domain: 'gmail.com' });
doc; // undefined
```
If you want to query by a computed property, you should set the property using a [custom setter](getters-setters) or [pre save middleware](../middleware).
Populate
--------
Mongoose also supports [populating virtuals](../populate). A populated virtual contains documents from another collection. To define a populated virtual, you need to specify:
* The `ref` option, which tells Mongoose which model to populate documents from.
* The `localField` and `foreignField` options. Mongoose will populate documents from the model in `ref` whose `foreignField` matches this document's `localField`.
```
const userSchema = mongoose.Schema({ _id: Number, email: String });
const blogPostSchema = mongoose.Schema({
title: String,
authorId: Number
});
// When you `populate()` the `author` virtual, Mongoose will find the
// first document in the User model whose `\_id` matches this document's
// `authorId` property.
blogPostSchema.virtual('author', {
ref: 'User',
localField: 'authorId',
foreignField: '\_id',
justOne: true
});
const User = mongoose.model('User', userSchema);
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
await BlogPost.create({ title: 'Introduction to Mongoose', authorId: 1 });
await User.create({ _id: 1, email: '[email protected]' });
const doc = await BlogPost.findOne().populate('author');
doc.author.email; // '[email protected]'
```
Further Reading
---------------
* [Virtuals in Mongoose Schemas](../guide#virtuals)
* [Populate Virtuals](../populate#populate-virtuals)
* [Mongoose Lean Virtuals plugin](https://plugins.mongoosejs.io/plugins/lean-virtuals)
* [Getting Started With Mongoose Virtuals](https://masteringjs.io/tutorials/mongoose/virtuals)
* [Understanding Virtuals in Mongoose](https://futurestud.io/tutorials/understanding-virtuals-in-mongoose)
| programming_docs |
julia Julia 1.8 Documentation Julia 1.8 Documentation
=======================
Welcome to the documentation for Julia 1.8.
Please read the [release notes](https://docs.julialang.org/en/v1.8/NEWS/) to see what has changed since the last release.
The documentation is also available in PDF format: [julia-1.8.5.pdf](https://raw.githubusercontent.com/JuliaLang/docs.julialang.org/assets/julia-1.8.5.pdf).
###
[Introduction](#man-introduction)
Scientific computing has traditionally required the highest performance, yet domain experts have largely moved to slower dynamic languages for daily work. We believe there are many good reasons to prefer dynamic languages for these applications, and we do not expect their use to diminish. Fortunately, modern language design and compiler techniques make it possible to mostly eliminate the performance trade-off and provide a single environment productive enough for prototyping and efficient enough for deploying performance-intensive applications. The Julia programming language fills this role: it is a flexible dynamic language, appropriate for scientific and numerical computing, with performance comparable to traditional statically-typed languages.
Because Julia's compiler is different from the interpreters used for languages like Python or R, you may find that Julia's performance is unintuitive at first. If you find that something is slow, we highly recommend reading through the [Performance Tips](manual/performance-tips/index#man-performance-tips) section before trying anything else. Once you understand how Julia works, it's easy to write code that's nearly as fast as C.
Julia features optional typing, multiple dispatch, and good performance, achieved using type inference and [just-in-time (JIT) compilation](https://en.wikipedia.org/wiki/Just-in-time_compilation), implemented using [LLVM](https://en.wikipedia.org/wiki/Low_Level_Virtual_Machine). It is multi-paradigm, combining features of imperative, functional, and object-oriented programming. Julia provides ease and expressiveness for high-level numerical computing, in the same way as languages such as R, MATLAB, and Python, but also supports general programming. To achieve this, Julia builds upon the lineage of mathematical programming languages, but also borrows much from popular dynamic languages, including [Lisp](https://en.wikipedia.org/wiki/Lisp_(programming_language)), [Perl](https://en.wikipedia.org/wiki/Perl_(programming_language)), [Python](https://en.wikipedia.org/wiki/Python_(programming_language)), [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)), and [Ruby](https://en.wikipedia.org/wiki/Ruby_(programming_language)).
The most significant departures of Julia from typical dynamic languages are:
* The core language imposes very little; Julia Base and the standard library are written in Julia itself, including primitive operations like integer arithmetic
* A rich language of types for constructing and describing objects, that can also optionally be used to make type declarations
* The ability to define function behavior across many combinations of argument types via [multiple dispatch](https://en.wikipedia.org/wiki/Multiple_dispatch)
* Automatic generation of efficient, specialized code for different argument types
* Good performance, approaching that of statically-compiled languages like C
Although one sometimes speaks of dynamic languages as being "typeless", they are definitely not: every object, whether primitive or user-defined, has a type. The lack of type declarations in most dynamic languages, however, means that one cannot instruct the compiler about the types of values, and often cannot explicitly talk about types at all. In static languages, on the other hand, while one can – and usually must – annotate types for the compiler, types exist only at compile time and cannot be manipulated or expressed at run time. In Julia, types are themselves run-time objects, and can also be used to convey information to the compiler.
While the casual programmer need not explicitly use types or multiple dispatch, they are the core unifying features of Julia: functions are defined on different combinations of argument types, and applied by dispatching to the most specific matching definition. This model is a good fit for mathematical programming, where it is unnatural for the first argument to "own" an operation as in traditional object-oriented dispatch. Operators are just functions with special notation – to extend addition to new user-defined data types, you define new methods for the `+` function. Existing code then seamlessly applies to the new data types.
Partly because of run-time type inference (augmented by optional type annotations), and partly because of a strong focus on performance from the inception of the project, Julia's computational efficiency exceeds that of other dynamic languages, and even rivals that of statically-compiled languages. For large scale numerical problems, speed always has been, continues to be, and probably always will be crucial: the amount of data being processed has easily kept pace with Moore's Law over the past decades.
Julia aims to create an unprecedented combination of ease-of-use, power, and efficiency in a single language. In addition to the above, some advantages of Julia over comparable systems include:
* Free and open source ([MIT licensed](https://github.com/JuliaLang/julia/blob/master/LICENSE.md))
* User-defined types are as fast and compact as built-ins
* No need to vectorize code for performance; devectorized code is fast
* Designed for parallelism and distributed computation
* Lightweight "green" threading ([coroutines](https://en.wikipedia.org/wiki/Coroutine))
* Unobtrusive yet powerful type system
* Elegant and extensible conversions and promotions for numeric and other types
* Efficient support for [Unicode](https://en.wikipedia.org/wiki/Unicode), including but not limited to [UTF-8](https://en.wikipedia.org/wiki/UTF-8)
* Call C functions directly (no wrappers or special APIs needed)
* Powerful shell-like capabilities for managing other processes
* Lisp-like macros and other metaprogramming facilities
julia Mathematical Operations and Elementary Functions Mathematical Operations and Elementary Functions
================================================
Julia provides a complete collection of basic arithmetic and bitwise operators across all of its numeric primitive types, as well as providing portable, efficient implementations of a comprehensive collection of standard mathematical functions.
[Arithmetic Operators](#Arithmetic-Operators)
----------------------------------------------
The following [arithmetic operators](https://en.wikipedia.org/wiki/Arithmetic#Arithmetic_operations) are supported on all primitive numeric types:
| Expression | Name | Description |
| --- | --- | --- |
| `+x` | unary plus | the identity operation |
| `-x` | unary minus | maps values to their additive inverses |
| `x + y` | binary plus | performs addition |
| `x - y` | binary minus | performs subtraction |
| `x * y` | times | performs multiplication |
| `x / y` | divide | performs division |
| `x ÷ y` | integer divide | x / y, truncated to an integer |
| `x \ y` | inverse divide | equivalent to `y / x` |
| `x ^ y` | power | raises `x` to the `y`th power |
| `x % y` | remainder | equivalent to `rem(x,y)` |
A numeric literal placed directly before an identifier or parentheses, e.g. `2x` or `2(x+y)`, is treated as a multiplication, except with higher precedence than other binary operations. See [Numeric Literal Coefficients](../integers-and-floating-point-numbers/index#man-numeric-literal-coefficients) for details.
Julia's promotion system makes arithmetic operations on mixtures of argument types "just work" naturally and automatically. See [Conversion and Promotion](../conversion-and-promotion/index#conversion-and-promotion) for details of the promotion system.
The ÷ sign can be conveniently typed by writing `\div<tab>` to the REPL or Julia IDE. See the [manual section on Unicode input](../unicode-input/index#Unicode-Input) for more information.
Here are some simple examples using arithmetic operators:
```
julia> 1 + 2 + 3
6
julia> 1 - 2
-1
julia> 3*2/12
0.5
```
(By convention, we tend to space operators more tightly if they get applied before other nearby operators. For instance, we would generally write `-x + 2` to reflect that first `x` gets negated, and then `2` is added to that result.)
When used in multiplication, `false` acts as a *strong zero*:
```
julia> NaN * false
0.0
julia> false * Inf
0.0
```
This is useful for preventing the propagation of `NaN` values in quantities that are known to be zero. See [Knuth (1992)](https://arxiv.org/abs/math/9205211) for motivation.
[Boolean Operators](#Boolean-Operators)
----------------------------------------
The following [Boolean operators](https://en.wikipedia.org/wiki/Boolean_algebra#Operations) are supported on [`Bool`](../../base/numbers/index#Core.Bool) types:
| Expression | Name |
| --- | --- |
| `!x` | negation |
| `x && y` | [short-circuiting and](../control-flow/index#man-conditional-evaluation) |
| `x || y` | [short-circuiting or](../control-flow/index#man-conditional-evaluation) |
Negation changes `true` to `false` and vice versa. The short-circuiting operations are explained on the linked page.
Note that `Bool` is an integer type and all the usual promotion rules and numeric operators are also defined on it.
[Bitwise Operators](#Bitwise-Operators)
----------------------------------------
The following [bitwise operators](https://en.wikipedia.org/wiki/Bitwise_operation#Bitwise_operators) are supported on all primitive integer types:
| Expression | Name |
| --- | --- |
| `~x` | bitwise not |
| `x & y` | bitwise and |
| `x | y` | bitwise or |
| `x ⊻ y` | bitwise xor (exclusive or) |
| `x ⊼ y` | bitwise nand (not and) |
| `x ⊽ y` | bitwise nor (not or) |
| `x >>> y` | [logical shift](https://en.wikipedia.org/wiki/Logical_shift) right |
| `x >> y` | [arithmetic shift](https://en.wikipedia.org/wiki/Arithmetic_shift) right |
| `x << y` | logical/arithmetic shift left |
Here are some examples with bitwise operators:
```
julia> ~123
-124
julia> 123 & 234
106
julia> 123 | 234
251
julia> 123 ⊻ 234
145
julia> xor(123, 234)
145
julia> nand(123, 123)
-124
julia> 123 ⊼ 123
-124
julia> nor(123, 124)
-128
julia> 123 ⊽ 124
-128
julia> ~UInt32(123)
0xffffff84
julia> ~UInt8(123)
0x84
```
[Updating operators](#Updating-operators)
------------------------------------------
Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back into its left operand. The updating version of the binary operator is formed by placing a `=` immediately after the operator. For example, writing `x += 3` is equivalent to writing `x = x + 3`:
```
julia> x = 1
1
julia> x += 3
4
julia> x
4
```
The updating versions of all the binary arithmetic and bitwise operators are:
```
+= -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<=
```
An updating operator rebinds the variable on the left-hand side. As a result, the type of the variable may change.
```
julia> x = 0x01; typeof(x)
UInt8
julia> x *= 2 # Same as x = x * 2
2
julia> typeof(x)
Int64
```
[Vectorized "dot" operators](#man-dot-operators)
-------------------------------------------------
For *every* binary operation like `^`, there is a corresponding "dot" operation `.^` that is *automatically* defined to perform `^` element-by-element on arrays. For example, `[1,2,3] ^ 3` is not defined, since there is no standard mathematical meaning to "cubing" a (non-square) array, but `[1,2,3] .^ 3` is defined as computing the elementwise (or "vectorized") result `[1^3, 2^3, 3^3]`. Similarly for unary operators like `!` or `√`, there is a corresponding `.√` that applies the operator elementwise.
```
julia> [1,2,3] .^ 3
3-element Vector{Int64}:
1
8
27
```
More specifically, `a .^ b` is parsed as the ["dot" call](../functions/index#man-vectorized) `(^).(a,b)`, which performs a [broadcast](../arrays/index#Broadcasting) operation: it can combine arrays and scalars, arrays of the same size (performing the operation elementwise), and even arrays of different shapes (e.g. combining row and column vectors to produce a matrix). Moreover, like all vectorized "dot calls," these "dot operators" are *fusing*. For example, if you compute `2 .* A.^2 .+ sin.(A)` (or equivalently `@. 2A^2 + sin(A)`, using the [`@.`](../../base/arrays/index#Base.Broadcast.@__dot__) macro) for an array `A`, it performs a *single* loop over `A`, computing `2a^2 + sin(a)` for each element `a` of `A`. In particular, nested dot calls like `f.(g.(x))` are fused, and "adjacent" binary operators like `x .+ 3 .* x.^2` are equivalent to nested dot calls `(+).(x, (*).(3, (^).(x, 2)))`.
Furthermore, "dotted" updating operators like `a .+= b` (or `@. a += b`) are parsed as `a .= a .+ b`, where `.=` is a fused *in-place* assignment operation (see the [dot syntax documentation](../functions/index#man-vectorized)).
Note the dot syntax is also applicable to user-defined operators. For example, if you define `⊗(A,B) = kron(A,B)` to give a convenient infix syntax `A ⊗ B` for Kronecker products ([`kron`](../../stdlib/linearalgebra/index#Base.kron)), then `[A,B] .⊗ [C,D]` will compute `[A⊗C, B⊗D]` with no additional coding.
Combining dot operators with numeric literals can be ambiguous. For example, it is not clear whether `1.+x` means `1. + x` or `1 .+ x`. Therefore this syntax is disallowed, and spaces must be used around the operator in such cases.
[Numeric Comparisons](#Numeric-Comparisons)
--------------------------------------------
Standard comparison operations are defined for all the primitive numeric types:
| Operator | Name |
| --- | --- |
| [`==`](../../base/math/index#Base.:==) | equality |
| [`!=`](../../base/math/index#Base.:!=), [`≠`](../../base/math/index#Base.:!=) | inequality |
| [`<`](#) | less than |
| [`<=`](#), [`≤`](#) | less than or equal to |
| [`>`](#) | greater than |
| [`>=`](#), [`≥`](#) | greater than or equal to |
Here are some simple examples:
```
julia> 1 == 1
true
julia> 1 == 2
false
julia> 1 != 2
true
julia> 1 == 1.0
true
julia> 1 < 2
true
julia> 1.0 > 3
false
julia> 1 >= 1.0
true
julia> -1 <= 1
true
julia> -1 <= -1
true
julia> -1 <= -2
false
julia> 3 < -0.5
false
```
Integers are compared in the standard manner – by comparison of bits. Floating-point numbers are compared according to the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754-2008):
* Finite numbers are ordered in the usual manner.
* Positive zero is equal but not greater than negative zero.
* `Inf` is equal to itself and greater than everything else except `NaN`.
* `-Inf` is equal to itself and less than everything else except `NaN`.
* `NaN` is not equal to, not less than, and not greater than anything, including itself.
The last point is potentially surprising and thus worth noting:
```
julia> NaN == NaN
false
julia> NaN != NaN
true
julia> NaN < NaN
false
julia> NaN > NaN
false
```
and can cause headaches when working with [arrays](../arrays/index#man-multi-dim-arrays):
```
julia> [1 NaN] == [1 NaN]
false
```
Julia provides additional functions to test numbers for special values, which can be useful in situations like hash key comparisons:
| Function | Tests if |
| --- | --- |
| [`isequal(x, y)`](../../base/base/index#Base.isequal) | `x` and `y` are identical |
| [`isfinite(x)`](../../base/numbers/index#Base.isfinite) | `x` is a finite number |
| [`isinf(x)`](../../base/numbers/index#Base.isinf) | `x` is infinite |
| [`isnan(x)`](../../base/numbers/index#Base.isnan) | `x` is not a number |
[`isequal`](../../base/base/index#Base.isequal) considers `NaN`s equal to each other:
```
julia> isequal(NaN, NaN)
true
julia> isequal([1 NaN], [1 NaN])
true
julia> isequal(NaN, NaN32)
true
```
`isequal` can also be used to distinguish signed zeros:
```
julia> -0.0 == 0.0
true
julia> isequal(-0.0, 0.0)
false
```
Mixed-type comparisons between signed integers, unsigned integers, and floats can be tricky. A great deal of care has been taken to ensure that Julia does them correctly.
For other types, `isequal` defaults to calling [`==`](../../base/math/index#Base.:==), so if you want to define equality for your own types then you only need to add a [`==`](../../base/math/index#Base.:==) method. If you define your own equality function, you should probably define a corresponding [`hash`](../../base/base/index#Base.hash) method to ensure that `isequal(x,y)` implies `hash(x) == hash(y)`.
###
[Chaining comparisons](#Chaining-comparisons)
Unlike most languages, with the [notable exception of Python](https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators), comparisons can be arbitrarily chained:
```
julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
true
```
Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the `&&` operator for scalar comparisons, and the [`&`](../../base/math/index#Base.:&) operator for elementwise comparisons, which allows them to work on arrays. For example, `0 .< A .< 1` gives a boolean array whose entries are true where the corresponding elements of `A` are between 0 and 1.
Note the evaluation behavior of chained comparisons:
```
julia> v(x) = (println(x); x)
v (generic function with 1 method)
julia> v(1) < v(2) <= v(3)
2
1
3
true
julia> v(1) > v(2) <= v(3)
2
1
false
```
The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) && v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `&&` operator should be used explicitly (see [Short-Circuit Evaluation](../control-flow/index#Short-Circuit-Evaluation)).
###
[Elementary Functions](#Elementary-Functions)
Julia provides a comprehensive collection of mathematical functions and operators. These mathematical operations are defined over as broad a class of numerical values as permit sensible definitions, including integers, floating-point numbers, rationals, and complex numbers, wherever such definitions make sense.
Moreover, these functions (like any Julia function) can be applied in "vectorized" fashion to arrays and other collections with the [dot syntax](../functions/index#man-vectorized) `f.(A)`, e.g. `sin.(A)` will compute the sine of each element of an array `A`.
[Operator Precedence and Associativity](#Operator-Precedence-and-Associativity)
--------------------------------------------------------------------------------
Julia applies the following order and associativity of operations, from highest precedence to lowest:
| Category | Operators | Associativity |
| --- | --- | --- |
| Syntax | `.` followed by `::` | Left |
| Exponentiation | `^` | Right |
| Unary | `+ - √` | Right[[1]](#footnote-1) |
| Bitshifts | `<< >> >>>` | Left |
| Fractions | `//` | Left |
| Multiplication | `* / % & \ ÷` | Left[[2]](#footnote-2) |
| Addition | `+ - | ⊻` | Left[[2]](#footnote-2) |
| Syntax | `: ..` | Left |
| Syntax | `|>` | Left |
| Syntax | `<|` | Right |
| Comparisons | `> < >= <= == === != !== <:` | Non-associative |
| Control flow | `&&` followed by `||` followed by `?` | Right |
| Pair | `=>` | Right |
| Assignments | `= += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>=` | Right |
For a complete list of *every* Julia operator's precedence, see the top of this file: [`src/julia-parser.scm`](https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm). Note that some of the operators there are not defined in the `Base` module but may be given definitions by standard libraries, packages or user code.
You can also find the numerical precedence for any given operator via the built-in function `Base.operator_precedence`, where higher numbers take precedence:
```
julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)
(11, 12, 17)
julia> Base.operator_precedence(:sin), Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (Note the necessary parens on `:(=)`)
(0, 1, 1)
```
A symbol representing the operator associativity can also be found by calling the built-in function `Base.operator_associativity`:
```
julia> Base.operator_associativity(:-), Base.operator_associativity(:+), Base.operator_associativity(:^)
(:left, :none, :right)
julia> Base.operator_associativity(:⊗), Base.operator_associativity(:sin), Base.operator_associativity(:→)
(:left, :none, :right)
```
Note that symbols such as `:sin` return precedence `0`. This value represents invalid operators and not operators of lowest precedence. Similarly, such operators are assigned associativity `:none`.
[Numeric literal coefficients](../integers-and-floating-point-numbers/index#man-numeric-literal-coefficients), e.g. `2x`, are treated as multiplications with higher precedence than any other binary operation, with the exception of `^` where they have higher precedence only as the exponent.
```
julia> x = 3; 2x^2
18
julia> x = 3; 2^2x
64
```
Juxtaposition parses like a unary operator, which has the same natural asymmetry around exponents: `-x^y` and `2x^y` parse as `-(x^y)` and `2(x^y)` whereas `x^-y` and `x^2y` parse as `x^(-y)` and `x^(2y)`.
[Numerical Conversions](#Numerical-Conversions)
------------------------------------------------
Julia supports three forms of numerical conversion, which differ in their handling of inexact conversions.
* The notation `T(x)` or `convert(T,x)` converts `x` to a value of type `T`.
+ If `T` is a floating-point type, the result is the nearest representable value, which could be positive or negative infinity.
+ If `T` is an integer type, an `InexactError` is raised if `x` is not representable by `T`.
* `x % T` converts an integer `x` to a value of integer type `T` congruent to `x` modulo `2^n`, where `n` is the number of bits in `T`. In other words, the binary representation is truncated to fit.
* The [Rounding functions](#Rounding-functions) take a type `T` as an optional argument. For example, `round(Int,x)` is a shorthand for `Int(round(x))`.
The following examples show the different forms.
```
julia> Int8(127)
127
julia> Int8(128)
ERROR: InexactError: trunc(Int8, 128)
Stacktrace:
[...]
julia> Int8(127.0)
127
julia> Int8(3.14)
ERROR: InexactError: Int8(3.14)
Stacktrace:
[...]
julia> Int8(128.0)
ERROR: InexactError: Int8(128.0)
Stacktrace:
[...]
julia> 127 % Int8
127
julia> 128 % Int8
-128
julia> round(Int8,127.4)
127
julia> round(Int8,127.6)
ERROR: InexactError: trunc(Int8, 128.0)
Stacktrace:
[...]
```
See [Conversion and Promotion](../conversion-and-promotion/index#conversion-and-promotion) for how to define your own conversions and promotions.
###
[Rounding functions](#Rounding-functions)
| Function | Description | Return type |
| --- | --- | --- |
| [`round(x)`](#) | round `x` to the nearest integer | `typeof(x)` |
| [`round(T, x)`](#) | round `x` to the nearest integer | `T` |
| [`floor(x)`](../../base/math/index#Base.floor) | round `x` towards `-Inf` | `typeof(x)` |
| [`floor(T, x)`](../../base/math/index#Base.floor) | round `x` towards `-Inf` | `T` |
| [`ceil(x)`](../../base/math/index#Base.ceil) | round `x` towards `+Inf` | `typeof(x)` |
| [`ceil(T, x)`](../../base/math/index#Base.ceil) | round `x` towards `+Inf` | `T` |
| [`trunc(x)`](../../base/math/index#Base.trunc) | round `x` towards zero | `typeof(x)` |
| [`trunc(T, x)`](../../base/math/index#Base.trunc) | round `x` towards zero | `T` |
###
[Division functions](#Division-functions)
| Function | Description |
| --- | --- |
| [`div(x,y)`](../../base/math/index#Base.div), `x÷y` | truncated division; quotient rounded towards zero |
| [`fld(x,y)`](../../base/math/index#Base.fld) | floored division; quotient rounded towards `-Inf` |
| [`cld(x,y)`](../../base/math/index#Base.cld) | ceiling division; quotient rounded towards `+Inf` |
| [`rem(x,y)`](../../base/math/index#Base.rem), `x%y` | remainder; satisfies `x == div(x,y)*y + rem(x,y)`; sign matches `x` |
| [`mod(x,y)`](../../base/math/index#Base.mod) | modulus; satisfies `x == fld(x,y)*y + mod(x,y)`; sign matches `y` |
| [`mod1(x,y)`](../../base/math/index#Base.mod1) | `mod` with offset 1; returns `r∈(0,y]` for `y>0` or `r∈[y,0)` for `y<0`, where `mod(r, y) == mod(x, y)` |
| [`mod2pi(x)`](../../base/math/index#Base.Math.mod2pi) | modulus with respect to 2pi; `0 <= mod2pi(x) < 2pi` |
| [`divrem(x,y)`](../../base/math/index#Base.divrem) | returns `(div(x,y),rem(x,y))` |
| [`fldmod(x,y)`](../../base/math/index#Base.fldmod) | returns `(fld(x,y),mod(x,y))` |
| [`gcd(x,y...)`](../../base/math/index#Base.gcd) | greatest positive common divisor of `x`, `y`,... |
| [`lcm(x,y...)`](../../base/math/index#Base.lcm) | least positive common multiple of `x`, `y`,... |
###
[Sign and absolute value functions](#Sign-and-absolute-value-functions)
| Function | Description |
| --- | --- |
| [`abs(x)`](../../base/math/index#Base.abs) | a positive value with the magnitude of `x` |
| [`abs2(x)`](../../base/math/index#Base.abs2) | the squared magnitude of `x` |
| [`sign(x)`](../../base/math/index#Base.sign) | indicates the sign of `x`, returning -1, 0, or +1 |
| [`signbit(x)`](../../base/math/index#Base.signbit) | indicates whether the sign bit is on (true) or off (false) |
| [`copysign(x,y)`](../../base/math/index#Base.copysign) | a value with the magnitude of `x` and the sign of `y` |
| [`flipsign(x,y)`](../../base/math/index#Base.flipsign) | a value with the magnitude of `x` and the sign of `x*y` |
###
[Powers, logs and roots](#Powers,-logs-and-roots)
| Function | Description |
| --- | --- |
| [`sqrt(x)`](#), `√x` | square root of `x` |
| [`cbrt(x)`](../../base/math/index#Base.Math.cbrt), `∛x` | cube root of `x` |
| [`hypot(x,y)`](../../base/math/index#Base.Math.hypot) | hypotenuse of right-angled triangle with other sides of length `x` and `y` |
| [`exp(x)`](#) | natural exponential function at `x` |
| [`expm1(x)`](../../base/math/index#Base.expm1) | accurate `exp(x)-1` for `x` near zero |
| [`ldexp(x,n)`](../../base/math/index#Base.Math.ldexp) | `x*2^n` computed efficiently for integer values of `n` |
| [`log(x)`](#) | natural logarithm of `x` |
| [`log(b,x)`](#) | base `b` logarithm of `x` |
| [`log2(x)`](../../base/math/index#Base.log2) | base 2 logarithm of `x` |
| [`log10(x)`](../../base/math/index#Base.log10) | base 10 logarithm of `x` |
| [`log1p(x)`](../../base/math/index#Base.log1p) | accurate `log(1+x)` for `x` near zero |
| [`exponent(x)`](../../base/numbers/index#Base.Math.exponent) | binary exponent of `x` |
| [`significand(x)`](../../base/numbers/index#Base.Math.significand) | binary significand (a.k.a. mantissa) of a floating-point number `x` |
For an overview of why functions like [`hypot`](../../base/math/index#Base.Math.hypot), [`expm1`](../../base/math/index#Base.expm1), and [`log1p`](../../base/math/index#Base.log1p) are necessary and useful, see John D. Cook's excellent pair of blog posts on the subject: [expm1, log1p, erfc](https://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/), and [hypot](https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/).
###
[Trigonometric and hyperbolic functions](#Trigonometric-and-hyperbolic-functions)
All the standard trigonometric and hyperbolic functions are also defined:
```
sin cos tan cot sec csc
sinh cosh tanh coth sech csch
asin acos atan acot asec acsc
asinh acosh atanh acoth asech acsch
sinc cosc
```
These are all single-argument functions, with [`atan`](#) also accepting two arguments corresponding to a traditional [`atan2`](https://en.wikipedia.org/wiki/Atan2) function.
Additionally, [`sinpi(x)`](../../base/math/index#Base.Math.sinpi) and [`cospi(x)`](../../base/math/index#Base.Math.cospi) are provided for more accurate computations of [`sin(pi*x)`](#) and [`cos(pi*x)`](#) respectively.
In order to compute trigonometric functions with degrees instead of radians, suffix the function with `d`. For example, [`sind(x)`](../../base/math/index#Base.Math.sind) computes the sine of `x` where `x` is specified in degrees. The complete list of trigonometric functions with degree variants is:
```
sind cosd tand cotd secd cscd
asind acosd atand acotd asecd acscd
```
###
[Special functions](#Special-functions)
Many other special mathematical functions are provided by the package [SpecialFunctions.jl](https://github.com/JuliaMath/SpecialFunctions.jl).
* [1](#citeref-1)The unary operators `+` and `-` require explicit parentheses around their argument to disambiguate them from the operator `++`, etc. Other compositions of unary operators are parsed with right-associativity, e. g., `√√-a` as `√(√(-a))`.
* [2](#citeref-2)The operators `+`, `++` and `*` are non-associative. `a + b + c` is parsed as `+(a, b, c)` not `+(+(a, b), c)`. However, the fallback methods for `+(a, b, c, d...)` and `*(a, b, c, d...)` both default to left-associative evaluation.
| programming_docs |
julia Multi-Threading Multi-Threading
===============
Visit this [blog post](https://julialang.org/blog/2019/07/multithreading/) for a presentation of Julia multi-threading features.
[Starting Julia with multiple threads](#Starting-Julia-with-multiple-threads)
------------------------------------------------------------------------------
By default, Julia starts up with a single thread of execution. This can be verified by using the command [`Threads.nthreads()`](../../base/multi-threading/index#Base.Threads.nthreads):
```
julia> Threads.nthreads()
1
```
The number of execution threads is controlled either by using the `-t`/`--threads` command line argument or by using the [`JULIA_NUM_THREADS`](../environment-variables/index#JULIA_NUM_THREADS) environment variable. When both are specified, then `-t`/`--threads` takes precedence.
The number of threads can either be specified as an integer (`--threads=4`) or as `auto` (`--threads=auto`), where `auto` sets the number of threads to the number of local CPU threads.
The `-t`/`--threads` command line argument requires at least Julia 1.5. In older versions you must use the environment variable instead.
Using `auto` as value of the environment variable `JULIA_NUM_THREADS` requires at least Julia 1.7. In older versions, this value is ignored.
Lets start Julia with 4 threads:
```
$ julia --threads 4
```
Let's verify there are 4 threads at our disposal.
```
julia> Threads.nthreads()
4
```
But we are currently on the master thread. To check, we use the function [`Threads.threadid`](../../base/multi-threading/index#Base.Threads.threadid)
```
julia> Threads.threadid()
1
```
If you prefer to use the environment variable you can set it as follows in Bash (Linux/macOS):
```
export JULIA_NUM_THREADS=4
```
C shell on Linux/macOS, CMD on Windows:
```
set JULIA_NUM_THREADS=4
```
Powershell on Windows:
```
$env:JULIA_NUM_THREADS=4
```
Note that this must be done *before* starting Julia.
The number of threads specified with `-t`/`--threads` is propagated to worker processes that are spawned using the `-p`/`--procs` or `--machine-file` command line options. For example, `julia -p2 -t2` spawns 1 main process with 2 worker processes, and all three processes have 2 threads enabled. For more fine grained control over worker threads use [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs) and pass `-t`/`--threads` as `exeflags`.
[Data-race freedom](#Data-race-freedom)
----------------------------------------
You are entirely responsible for ensuring that your program is data-race free, and nothing promised here can be assumed if you do not observe that requirement. The observed results may be highly unintuitive.
The best way to ensure this is to acquire a lock around any access to data that can be observed from multiple threads. For example, in most cases you should use the following code pattern:
```
julia> lock(lk) do
use(a)
end
julia> begin
lock(lk)
try
use(a)
finally
unlock(lk)
end
end
```
where `lk` is a lock (e.g. `ReentrantLock()`) and `a` data.
Additionally, Julia is not memory safe in the presence of a data race. Be very careful about reading *any* data if another thread might write to it! Instead, always use the lock pattern above when changing data (such as assigning to a global or closure variable) accessed by other threads.
```
Thread 1:
global b = false
global a = rand()
global b = true
Thread 2:
while !b; end
bad_read1(a) # it is NOT safe to access `a` here!
Thread 3:
while !@isdefined(a); end
bad_read2(a) # it is NOT safe to access `a` here
```
[The `@threads` Macro](#The-@threads-Macro)
--------------------------------------------
Let's work a simple example using our native threads. Let us create an array of zeros:
```
julia> a = zeros(10)
10-element Vector{Float64}:
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
```
Let us operate on this array simultaneously using 4 threads. We'll have each thread write its thread ID into each location.
Julia supports parallel loops using the [`Threads.@threads`](../../base/multi-threading/index#Base.Threads.@threads) macro. This macro is affixed in front of a `for` loop to indicate to Julia that the loop is a multi-threaded region:
```
julia> Threads.@threads for i = 1:10
a[i] = Threads.threadid()
end
```
The iteration space is split among the threads, after which each thread writes its thread ID to its assigned locations:
```
julia> a
10-element Vector{Float64}:
1.0
1.0
1.0
2.0
2.0
2.0
3.0
3.0
4.0
4.0
```
Note that [`Threads.@threads`](../../base/multi-threading/index#Base.Threads.@threads) does not have an optional reduction parameter like [`@distributed`](../../stdlib/distributed/index#Distributed.@distributed).
[Atomic Operations](#Atomic-Operations)
----------------------------------------
Julia supports accessing and modifying values *atomically*, that is, in a thread-safe way to avoid [race conditions](https://en.wikipedia.org/wiki/Race_condition). A value (which must be of a primitive type) can be wrapped as [`Threads.Atomic`](../../base/multi-threading/index#Base.Threads.Atomic) to indicate it must be accessed in this way. Here we can see an example:
```
julia> i = Threads.Atomic{Int}(0);
julia> ids = zeros(4);
julia> old_is = zeros(4);
julia> Threads.@threads for id in 1:4
old_is[id] = Threads.atomic_add!(i, id)
ids[id] = id
end
julia> old_is
4-element Vector{Float64}:
0.0
1.0
7.0
3.0
julia> i[]
10
julia> ids
4-element Vector{Float64}:
1.0
2.0
3.0
4.0
```
Had we tried to do the addition without the atomic tag, we might have gotten the wrong answer due to a race condition. An example of what would happen if we didn't avoid the race:
```
julia> using Base.Threads
julia> nthreads()
4
julia> acc = Ref(0)
Base.RefValue{Int64}(0)
julia> @threads for i in 1:1000
acc[] += 1
end
julia> acc[]
926
julia> acc = Atomic{Int64}(0)
Atomic{Int64}(0)
julia> @threads for i in 1:1000
atomic_add!(acc, 1)
end
julia> acc[]
1000
```
[Per-field atomics](#man-atomics)
----------------------------------
We can also use atomics on a more granular level using the [`@atomic`](../../base/multi-threading/index#Base.@atomic), [`@atomicswap`](../../base/multi-threading/index#Base.@atomicswap), and [`@atomicreplace`](../../base/multi-threading/index#Base.@atomicreplace) macros.
Specific details of the memory model and other details of the design are written in the [Julia Atomics Manifesto](https://gist.github.com/vtjnash/11b0031f2e2a66c9c24d33e810b34ec0), which will later be published formally.
Any field in a struct declaration can be decorated with `@atomic`, and then any write must be marked with `@atomic` also, and must use one of the defined atomic orderings (`:monotonic`, `:acquire`, `:release`, `:acquire_release`, or `:sequentially_consistent`). Any read of an atomic field can also be annotated with an atomic ordering constraint, or will be done with monotonic (relaxed) ordering if unspecified.
Per-field atomics requires at least Julia 1.7.
[Side effects and mutable function arguments](#Side-effects-and-mutable-function-arguments)
--------------------------------------------------------------------------------------------
When using multi-threading we have to be careful when using functions that are not [pure](https://en.wikipedia.org/wiki/Pure_function) as we might get a wrong answer. For instance functions that have a [name ending with `!`](../style-guide/index#bang-convention) by convention modify their arguments and thus are not pure.
[@threadcall](#@threadcall)
----------------------------
External libraries, such as those called via [`ccall`](../../base/c/index#ccall), pose a problem for Julia's task-based I/O mechanism. If a C library performs a blocking operation, that prevents the Julia scheduler from executing any other tasks until the call returns. (Exceptions are calls into custom C code that call back into Julia, which may then yield, or C code that calls `jl_yield()`, the C equivalent of [`yield`](../../base/parallel/index#Base.yield).)
The [`@threadcall`](../../base/multi-threading/index#Base.@threadcall) macro provides a way to avoid stalling execution in such a scenario. It schedules a C function for execution in a separate thread. A threadpool with a default size of 4 is used for this. The size of the threadpool is controlled via environment variable `UV_THREADPOOL_SIZE`. While waiting for a free thread, and during function execution once a thread is available, the requesting task (on the main Julia event loop) yields to other tasks. Note that `@threadcall` does not return until the execution is complete. From a user point of view, it is therefore a blocking call like other Julia APIs.
It is very important that the called function does not call back into Julia, as it will segfault.
`@threadcall` may be removed/changed in future versions of Julia.
[Caveats](#Caveats)
--------------------
At this time, most operations in the Julia runtime and standard libraries can be used in a thread-safe manner, if the user code is data-race free. However, in some areas work on stabilizing thread support is ongoing. Multi-threaded programming has many inherent difficulties, and if a program using threads exhibits unusual or undesirable behavior (e.g. crashes or mysterious results), thread interactions should typically be suspected first.
There are a few specific limitations and warnings to be aware of when using threads in Julia:
* Base collection types require manual locking if used simultaneously by multiple threads where at least one thread modifies the collection (common examples include `push!` on arrays, or inserting items into a `Dict`).
* The schedule used by `@spawn` is nondeterministic and should not be relied on.
* Compute-bound, non-memory-allocating tasks can prevent garbage collection from running in other threads that are allocating memory. In these cases it may be necessary to insert a manual call to `GC.safepoint()` to allow GC to run. This limitation will be removed in the future.
* Avoid running top-level operations, e.g. `include`, or `eval` of type, method, and module definitions in parallel.
* Be aware that finalizers registered by a library may break if threads are enabled. This may require some transitional work across the ecosystem before threading can be widely adopted with confidence. See the next section for further details.
[Safe use of Finalizers](#Safe-use-of-Finalizers)
--------------------------------------------------
Because finalizers can interrupt any code, they must be very careful in how they interact with any global state. Unfortunately, the main reason that finalizers are used is to update global state (a pure function is generally rather pointless as a finalizer). This leads us to a bit of a conundrum. There are a few approaches to dealing with this problem:
1. When single-threaded, code could call the internal `jl_gc_enable_finalizers` C function to prevent finalizers from being scheduled inside a critical region. Internally, this is used inside some functions (such as our C locks) to prevent recursion when doing certain operations (incremental package loading, codegen, etc.). The combination of a lock and this flag can be used to make finalizers safe.
2. A second strategy, employed by Base in a couple places, is to explicitly delay a finalizer until it may be able to acquire its lock non-recursively. The following example demonstrates how this strategy could be applied to `Distributed.finalize_ref`:
```
function finalize_ref(r::AbstractRemoteRef)
if r.where > 0 # Check if the finalizer is already run
if islocked(client_refs) || !trylock(client_refs)
# delay finalizer for later if we aren't free to acquire the lock
finalizer(finalize_ref, r)
return nothing
end
try # `lock` should always be followed by `try`
if r.where > 0 # Must check again here
# Do actual cleanup here
r.where = 0
end
finally
unlock(client_refs)
end
end
nothing
end
```
3. A related third strategy is to use a yield-free queue. We don't currently have a lock-free queue implemented in Base, but `Base.InvasiveLinkedListSynchronized{T}` is suitable. This can frequently be a good strategy to use for code with event loops. For example, this strategy is employed by `Gtk.jl` to manage lifetime ref-counting. In this approach, we don't do any explicit work inside the `finalizer`, and instead add it to a queue to run at a safer time. In fact, Julia's task scheduler already uses this, so defining the finalizer as `x -> @spawn do_cleanup(x)` is one example of this approach. Note however that this doesn't control which thread `do_cleanup` runs on, so `do_cleanup` would still need to acquire a lock. That doesn't need to be true if you implement your own queue, as you can explicitly only drain that queue from your thread.
julia Metaprogramming Metaprogramming
===============
The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros operating at the level of [abstract syntax trees](https://en.wikipedia.org/wiki/Abstract_syntax_tree). In contrast, preprocessor "macro" systems, like that of C and C++, perform textual manipulation and substitution before any actual parsing or interpretation occurs. Because all data types and code in Julia are represented by Julia data structures, powerful [reflection](https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29) capabilities are available to explore the internals of a program and its types just like any other data.
[Program representation](#Program-representation)
--------------------------------------------------
Every Julia program starts life as a string:
```
julia> prog = "1 + 1"
"1 + 1"
```
**What happens next?**
The next step is to [parse](https://en.wikipedia.org/wiki/Parsing#Computer_languages) each string into an object called an expression, represented by the Julia type [`Expr`](../../base/base/index#Core.Expr):
```
julia> ex1 = Meta.parse(prog)
:(1 + 1)
julia> typeof(ex1)
Expr
```
`Expr` objects contain two parts:
* a [`Symbol`](../../base/base/index#Core.Symbol) identifying the kind of expression. A symbol is an [interned string](https://en.wikipedia.org/wiki/String_interning) identifier (more discussion below).
```
julia> ex1.head
:call
```
* the expression arguments, which may be symbols, other expressions, or literal values:
```
julia> ex1.args
3-element Vector{Any}:
:+
1
1
```
Expressions may also be constructed directly in [prefix notation](https://en.wikipedia.org/wiki/Polish_notation):
```
julia> ex2 = Expr(:call, :+, 1, 1)
:(1 + 1)
```
The two expressions constructed above – by parsing and by direct construction – are equivalent:
```
julia> ex1 == ex2
true
```
**The key point here is that Julia code is internally represented as a data structure that is accessible from the language itself.**
The [`dump`](../../base/io-network/index#Base.dump) function provides indented and annotated display of `Expr` objects:
```
julia> dump(ex2)
Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol +
2: Int64 1
3: Int64 1
```
`Expr` objects may also be nested:
```
julia> ex3 = Meta.parse("(4 + 4) / 2")
:((4 + 4) / 2)
```
Another way to view expressions is with `Meta.show_sexpr`, which displays the [S-expression](https://en.wikipedia.org/wiki/S-expression) form of a given `Expr`, which may look very familiar to users of Lisp. Here's an example illustrating the display on a nested `Expr`:
```
julia> Meta.show_sexpr(ex3)
(:call, :/, (:call, :+, 4, 4), 2)
```
###
[Symbols](#Symbols)
The `:` character has two syntactic purposes in Julia. The first form creates a [`Symbol`](../../base/base/index#Core.Symbol), an [interned string](https://en.wikipedia.org/wiki/String_interning) used as one building-block of expressions:
```
julia> s = :foo
:foo
julia> typeof(s)
Symbol
```
The [`Symbol`](../../base/base/index#Core.Symbol) constructor takes any number of arguments and creates a new symbol by concatenating their string representations together:
```
julia> :foo == Symbol("foo")
true
julia> Symbol("func",10)
:func10
julia> Symbol(:var,'_',"sym")
:var_sym
```
Note that to use `:` syntax, the symbol's name must be a valid identifier. Otherwise the `Symbol(str)` constructor must be used.
In the context of an expression, symbols are used to indicate access to variables; when an expression is evaluated, a symbol is replaced with the value bound to that symbol in the appropriate [scope](../variables-and-scoping/index#scope-of-variables).
Sometimes extra parentheses around the argument to `:` are needed to avoid ambiguity in parsing:
```
julia> :(:)
:(:)
julia> :(::)
:(::)
```
[Expressions and evaluation](#Expressions-and-evaluation)
----------------------------------------------------------
###
[Quoting](#Quoting)
The second syntactic purpose of the `:` character is to create expression objects without using the explicit [`Expr`](../../base/base/index#Core.Expr) constructor. This is referred to as *quoting*. The `:` character, followed by paired parentheses around a single statement of Julia code, produces an `Expr` object based on the enclosed code. Here is an example of the short form used to quote an arithmetic expression:
```
julia> ex = :(a+b*c+1)
:(a + b * c + 1)
julia> typeof(ex)
Expr
```
(to view the structure of this expression, try `ex.head` and `ex.args`, or use [`dump`](../../base/io-network/index#Base.dump) as above or [`Meta.@dump`](../../base/io-network/index#Base.Meta.@dump))
Note that equivalent expressions may be constructed using [`Meta.parse`](#) or the direct `Expr` form:
```
julia> :(a + b*c + 1) ==
Meta.parse("a + b*c + 1") ==
Expr(:call, :+, :a, Expr(:call, :*, :b, :c), 1)
true
```
Expressions provided by the parser generally only have symbols, other expressions, and literal values as their args, whereas expressions constructed by Julia code can have arbitrary run-time values without literal forms as args. In this specific example, `+` and `a` are symbols, `*(b,c)` is a subexpression, and `1` is a literal 64-bit signed integer.
There is a second syntactic form of quoting for multiple expressions: blocks of code enclosed in `quote ... end`.
```
julia> ex = quote
x = 1
y = 2
x + y
end
quote
#= none:2 =#
x = 1
#= none:3 =#
y = 2
#= none:4 =#
x + y
end
julia> typeof(ex)
Expr
```
###
[Interpolation](#man-expression-interpolation)
Direct construction of [`Expr`](../../base/base/index#Core.Expr) objects with value arguments is powerful, but `Expr` constructors can be tedious compared to "normal" Julia syntax. As an alternative, Julia allows *interpolation* of literals or expressions into quoted expressions. Interpolation is indicated by a prefix `$`.
In this example, the value of variable `a` is interpolated:
```
julia> a = 1;
julia> ex = :($a + b)
:(1 + b)
```
Interpolating into an unquoted expression is not supported and will cause a compile-time error:
```
julia> $a + b
ERROR: syntax: "$" expression outside quote
```
In this example, the tuple `(1,2,3)` is interpolated as an expression into a conditional test:
```
julia> ex = :(a in $:((1,2,3)) )
:(a in (1, 2, 3))
```
The use of `$` for expression interpolation is intentionally reminiscent of [string interpolation](../strings/index#string-interpolation) and [command interpolation](../running-external-programs/index#command-interpolation). Expression interpolation allows convenient, readable programmatic construction of complex Julia expressions.
###
[Splatting interpolation](#Splatting-interpolation)
Notice that the `$` interpolation syntax allows inserting only a single expression into an enclosing expression. Occasionally, you have an array of expressions and need them all to become arguments of the surrounding expression. This can be done with the syntax `$(xs...)`. For example, the following code generates a function call where the number of arguments is determined programmatically:
```
julia> args = [:x, :y, :z];
julia> :(f(1, $(args...)))
:(f(1, x, y, z))
```
###
[Nested quote](#Nested-quote)
Naturally, it is possible for quote expressions to contain other quote expressions. Understanding how interpolation works in these cases can be a bit tricky. Consider this example:
```
julia> x = :(1 + 2);
julia> e = quote quote $x end end
quote
#= none:1 =#
$(Expr(:quote, quote
#= none:1 =#
$(Expr(:$, :x))
end))
end
```
Notice that the result contains `$x`, which means that `x` has not been evaluated yet. In other words, the `$` expression "belongs to" the inner quote expression, and so its argument is only evaluated when the inner quote expression is:
```
julia> eval(e)
quote
#= none:1 =#
1 + 2
end
```
However, the outer `quote` expression is able to interpolate values inside the `$` in the inner quote. This is done with multiple `$`s:
```
julia> e = quote quote $$x end end
quote
#= none:1 =#
$(Expr(:quote, quote
#= none:1 =#
$(Expr(:$, :(1 + 2)))
end))
end
```
Notice that `(1 + 2)` now appears in the result instead of the symbol `x`. Evaluating this expression yields an interpolated `3`:
```
julia> eval(e)
quote
#= none:1 =#
3
end
```
The intuition behind this behavior is that `x` is evaluated once for each `$`: one `$` works similarly to `eval(:x)`, giving `x`'s value, while two `$`s do the equivalent of `eval(eval(:x))`.
###
[QuoteNode](#man-quote-node)
The usual representation of a `quote` form in an AST is an [`Expr`](../../base/base/index#Core.Expr) with head `:quote`:
```
julia> dump(Meta.parse(":(1+2)"))
Expr
head: Symbol quote
args: Array{Any}((1,))
1: Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol +
2: Int64 1
3: Int64 2
```
As we have seen, such expressions support interpolation with `$`. However, in some situations it is necessary to quote code *without* performing interpolation. This kind of quoting does not yet have syntax, but is represented internally as an object of type `QuoteNode`:
```
julia> eval(Meta.quot(Expr(:$, :(1+2))))
3
julia> eval(QuoteNode(Expr(:$, :(1+2))))
:($(Expr(:$, :(1 + 2))))
```
The parser yields `QuoteNode`s for simple quoted items like symbols:
```
julia> dump(Meta.parse(":x"))
QuoteNode
value: Symbol x
```
`QuoteNode` can also be used for certain advanced metaprogramming tasks.
###
[Evaluating expressions](#Evaluating-expressions)
Given an expression object, one can cause Julia to evaluate (execute) it at global scope using [`eval`](../../base/base/index#Base.MainInclude.eval):
```
julia> ex1 = :(1 + 2)
:(1 + 2)
julia> eval(ex1)
3
julia> ex = :(a + b)
:(a + b)
julia> eval(ex)
ERROR: UndefVarError: b not defined
[...]
julia> a = 1; b = 2;
julia> eval(ex)
3
```
Every [module](../modules/index#modules) has its own [`eval`](../../base/base/index#Base.MainInclude.eval) function that evaluates expressions in its global scope. Expressions passed to [`eval`](../../base/base/index#Base.MainInclude.eval) are not limited to returning values – they can also have side-effects that alter the state of the enclosing module's environment:
```
julia> ex = :(x = 1)
:(x = 1)
julia> x
ERROR: UndefVarError: x not defined
julia> eval(ex)
1
julia> x
1
```
Here, the evaluation of an expression object causes a value to be assigned to the global variable `x`.
Since expressions are just `Expr` objects which can be constructed programmatically and then evaluated, it is possible to dynamically generate arbitrary code which can then be run using [`eval`](../../base/base/index#Base.MainInclude.eval). Here is a simple example:
```
julia> a = 1;
julia> ex = Expr(:call, :+, a, :b)
:(1 + b)
julia> a = 0; b = 2;
julia> eval(ex)
3
```
The value of `a` is used to construct the expression `ex` which applies the `+` function to the value 1 and the variable `b`. Note the important distinction between the way `a` and `b` are used:
* The value of the *variable* `a` at expression construction time is used as an immediate value in the expression. Thus, the value of `a` when the expression is evaluated no longer matters: the value in the expression is already `1`, independent of whatever the value of `a` might be.
* On the other hand, the *symbol* `:b` is used in the expression construction, so the value of the variable `b` at that time is irrelevant – `:b` is just a symbol and the variable `b` need not even be defined. At expression evaluation time, however, the value of the symbol `:b` is resolved by looking up the value of the variable `b`.
###
[Functions on `Expr`essions](#Functions-on-Expressions)
As hinted above, one extremely useful feature of Julia is the capability to generate and manipulate Julia code within Julia itself. We have already seen one example of a function returning [`Expr`](../../base/base/index#Core.Expr) objects: the [`parse`](../../base/numbers/index#Base.parse) function, which takes a string of Julia code and returns the corresponding `Expr`. A function can also take one or more `Expr` objects as arguments, and return another `Expr`. Here is a simple, motivating example:
```
julia> function math_expr(op, op1, op2)
expr = Expr(:call, op, op1, op2)
return expr
end
math_expr (generic function with 1 method)
julia> ex = math_expr(:+, 1, Expr(:call, :*, 4, 5))
:(1 + 4 * 5)
julia> eval(ex)
21
```
As another example, here is a function that doubles any numeric argument, but leaves expressions alone:
```
julia> function make_expr2(op, opr1, opr2)
opr1f, opr2f = map(x -> isa(x, Number) ? 2*x : x, (opr1, opr2))
retexpr = Expr(:call, op, opr1f, opr2f)
return retexpr
end
make_expr2 (generic function with 1 method)
julia> make_expr2(:+, 1, 2)
:(2 + 4)
julia> ex = make_expr2(:+, 1, Expr(:call, :*, 5, 8))
:(2 + 5 * 8)
julia> eval(ex)
42
```
[Macros](#man-macros)
----------------------
Macros provide a mechanism to include generated code in the final body of a program. A macro maps a tuple of arguments to a returned *expression*, and the resulting expression is compiled directly rather than requiring a runtime [`eval`](../../base/base/index#Base.MainInclude.eval) call. Macro arguments may include expressions, literal values, and symbols.
###
[Basics](#Basics)
Here is an extraordinarily simple macro:
```
julia> macro sayhello()
return :( println("Hello, world!") )
end
@sayhello (macro with 1 method)
```
Macros have a dedicated character in Julia's syntax: the `@` (at-sign), followed by the unique name declared in a `macro NAME ... end` block. In this example, the compiler will replace all instances of `@sayhello` with:
```
:( println("Hello, world!") )
```
When `@sayhello` is entered in the REPL, the expression executes immediately, thus we only see the evaluation result:
```
julia> @sayhello()
Hello, world!
```
Now, consider a slightly more complex macro:
```
julia> macro sayhello(name)
return :( println("Hello, ", $name) )
end
@sayhello (macro with 1 method)
```
This macro takes one argument: `name`. When `@sayhello` is encountered, the quoted expression is *expanded* to interpolate the value of the argument into the final expression:
```
julia> @sayhello("human")
Hello, human
```
We can view the quoted return expression using the function [`macroexpand`](../../base/base/index#Base.macroexpand) (**important note:** this is an extremely useful tool for debugging macros):
```
julia> ex = macroexpand(Main, :(@sayhello("human")) )
:(Main.println("Hello, ", "human"))
julia> typeof(ex)
Expr
```
We can see that the `"human"` literal has been interpolated into the expression.
There also exists a macro [`@macroexpand`](../../base/base/index#Base.@macroexpand) that is perhaps a bit more convenient than the `macroexpand` function:
```
julia> @macroexpand @sayhello "human"
:(println("Hello, ", "human"))
```
###
[Hold up: why macros?](#Hold-up:-why-macros?)
We have already seen a function `f(::Expr...) -> Expr` in a previous section. In fact, [`macroexpand`](../../base/base/index#Base.macroexpand) is also such a function. So, why do macros exist?
Macros are necessary because they execute when code is parsed, therefore, macros allow the programmer to generate and include fragments of customized code *before* the full program is run. To illustrate the difference, consider the following example:
```
julia> macro twostep(arg)
println("I execute at parse time. The argument is: ", arg)
return :(println("I execute at runtime. The argument is: ", $arg))
end
@twostep (macro with 1 method)
julia> ex = macroexpand(Main, :(@twostep :(1, 2, 3)) );
I execute at parse time. The argument is: :((1, 2, 3))
```
The first call to [`println`](../../base/io-network/index#Base.println) is executed when [`macroexpand`](../../base/base/index#Base.macroexpand) is called. The resulting expression contains *only* the second `println`:
```
julia> typeof(ex)
Expr
julia> ex
:(println("I execute at runtime. The argument is: ", $(Expr(:copyast, :($(QuoteNode(:((1, 2, 3)))))))))
julia> eval(ex)
I execute at runtime. The argument is: (1, 2, 3)
```
###
[Macro invocation](#Macro-invocation)
Macros are invoked with the following general syntax:
```
@name expr1 expr2 ...
@name(expr1, expr2, ...)
```
Note the distinguishing `@` before the macro name and the lack of commas between the argument expressions in the first form, and the lack of whitespace after `@name` in the second form. The two styles should not be mixed. For example, the following syntax is different from the examples above; it passes the tuple `(expr1, expr2, ...)` as one argument to the macro:
```
@name (expr1, expr2, ...)
```
An alternative way to invoke a macro over an array literal (or comprehension) is to juxtapose both without using parentheses. In this case, the array will be the only expression fed to the macro. The following syntax is equivalent (and different from `@name [a b] * v`):
```
@name[a b] * v
@name([a b]) * v
```
It is important to emphasize that macros receive their arguments as expressions, literals, or symbols. One way to explore macro arguments is to call the [`show`](#) function within the macro body:
```
julia> macro showarg(x)
show(x)
# ... remainder of macro, returning an expression
end
@showarg (macro with 1 method)
julia> @showarg(a)
:a
julia> @showarg(1+1)
:(1 + 1)
julia> @showarg(println("Yo!"))
:(println("Yo!"))
```
In addition to the given argument list, every macro is passed extra arguments named `__source__` and `__module__`.
The argument `__source__` provides information (in the form of a `LineNumberNode` object) about the parser location of the `@` sign from the macro invocation. This allows macros to include better error diagnostic information, and is commonly used by logging, string-parser macros, and docs, for example, as well as to implement the [`@__LINE__`](../../base/base/index#Base.@__LINE__), [`@__FILE__`](../../base/base/index#Base.@__FILE__), and [`@__DIR__`](../../base/base/index#Base.@__DIR__) macros.
The location information can be accessed by referencing `__source__.line` and `__source__.file`:
```
julia> macro __LOCATION__(); return QuoteNode(__source__); end
@__LOCATION__ (macro with 1 method)
julia> dump(
@__LOCATION__(
))
LineNumberNode
line: Int64 2
file: Symbol none
```
The argument `__module__` provides information (in the form of a `Module` object) about the expansion context of the macro invocation. This allows macros to look up contextual information, such as existing bindings, or to insert the value as an extra argument to a runtime function call doing self-reflection in the current module.
###
[Building an advanced macro](#Building-an-advanced-macro)
Here is a simplified definition of Julia's [`@assert`](../../base/base/index#Base.@assert) macro:
```
julia> macro assert(ex)
return :( $ex ? nothing : throw(AssertionError($(string(ex)))) )
end
@assert (macro with 1 method)
```
This macro can be used like this:
```
julia> @assert 1 == 1.0
julia> @assert 1 == 0
ERROR: AssertionError: 1 == 0
```
In place of the written syntax, the macro call is expanded at parse time to its returned result. This is equivalent to writing:
```
1 == 1.0 ? nothing : throw(AssertionError("1 == 1.0"))
1 == 0 ? nothing : throw(AssertionError("1 == 0"))
```
That is, in the first call, the expression `:(1 == 1.0)` is spliced into the test condition slot, while the value of `string(:(1 == 1.0))` is spliced into the assertion message slot. The entire expression, thus constructed, is placed into the syntax tree where the `@assert` macro call occurs. Then at execution time, if the test expression evaluates to true, then [`nothing`](../../base/constants/index#Core.nothing) is returned, whereas if the test is false, an error is raised indicating the asserted expression that was false. Notice that it would not be possible to write this as a function, since only the *value* of the condition is available and it would be impossible to display the expression that computed it in the error message.
The actual definition of `@assert` in Julia Base is more complicated. It allows the user to optionally specify their own error message, instead of just printing the failed expression. Just like in functions with a variable number of arguments ([Varargs Functions](../functions/index#Varargs-Functions)), this is specified with an ellipses following the last argument:
```
julia> macro assert(ex, msgs...)
msg_body = isempty(msgs) ? ex : msgs[1]
msg = string(msg_body)
return :($ex ? nothing : throw(AssertionError($msg)))
end
@assert (macro with 1 method)
```
Now `@assert` has two modes of operation, depending upon the number of arguments it receives! If there's only one argument, the tuple of expressions captured by `msgs` will be empty and it will behave the same as the simpler definition above. But now if the user specifies a second argument, it is printed in the message body instead of the failing expression. You can inspect the result of a macro expansion with the aptly named [`@macroexpand`](../../base/base/index#Base.@macroexpand) macro:
```
julia> @macroexpand @assert a == b
:(if Main.a == Main.b
Main.nothing
else
Main.throw(Main.AssertionError("a == b"))
end)
julia> @macroexpand @assert a==b "a should equal b!"
:(if Main.a == Main.b
Main.nothing
else
Main.throw(Main.AssertionError("a should equal b!"))
end)
```
There is yet another case that the actual `@assert` macro handles: what if, in addition to printing "a should equal b," we wanted to print their values? One might naively try to use string interpolation in the custom message, e.g., `@assert a==b "a ($a) should equal b ($b)!"`, but this won't work as expected with the above macro. Can you see why? Recall from [string interpolation](../strings/index#string-interpolation) that an interpolated string is rewritten to a call to [`string`](../../base/strings/index#Base.string). Compare:
```
julia> typeof(:("a should equal b"))
String
julia> typeof(:("a ($a) should equal b ($b)!"))
Expr
julia> dump(:("a ($a) should equal b ($b)!"))
Expr
head: Symbol string
args: Array{Any}((5,))
1: String "a ("
2: Symbol a
3: String ") should equal b ("
4: Symbol b
5: String ")!"
```
So now instead of getting a plain string in `msg_body`, the macro is receiving a full expression that will need to be evaluated in order to display as expected. This can be spliced directly into the returned expression as an argument to the [`string`](../../base/strings/index#Base.string) call; see [`error.jl`](https://github.com/JuliaLang/julia/blob/master/base/error.jl) for the complete implementation.
The `@assert` macro makes great use of splicing into quoted expressions to simplify the manipulation of expressions inside the macro body.
###
[Hygiene](#Hygiene)
An issue that arises in more complex macros is that of [hygiene](https://en.wikipedia.org/wiki/Hygienic_macro). In short, macros must ensure that the variables they introduce in their returned expressions do not accidentally clash with existing variables in the surrounding code they expand into. Conversely, the expressions that are passed into a macro as arguments are often *expected* to evaluate in the context of the surrounding code, interacting with and modifying the existing variables. Another concern arises from the fact that a macro may be called in a different module from where it was defined. In this case we need to ensure that all global variables are resolved to the correct module. Julia already has a major advantage over languages with textual macro expansion (like C) in that it only needs to consider the returned expression. All the other variables (such as `msg` in `@assert` above) follow the [normal scoping block behavior](../variables-and-scoping/index#scope-of-variables).
To demonstrate these issues, let us consider writing a `@time` macro that takes an expression as its argument, records the time, evaluates the expression, records the time again, prints the difference between the before and after times, and then has the value of the expression as its final value. The macro might look like this:
```
macro time(ex)
return quote
local t0 = time_ns()
local val = $ex
local t1 = time_ns()
println("elapsed time: ", (t1-t0)/1e9, " seconds")
val
end
end
```
Here, we want `t0`, `t1`, and `val` to be private temporary variables, and we want `time_ns` to refer to the [`time_ns`](../../base/base/index#Base.time_ns) function in Julia Base, not to any `time_ns` variable the user might have (the same applies to `println`). Imagine the problems that could occur if the user expression `ex` also contained assignments to a variable called `t0`, or defined its own `time_ns` variable. We might get errors, or mysteriously incorrect behavior.
Julia's macro expander solves these problems in the following way. First, variables within a macro result are classified as either local or global. A variable is considered local if it is assigned to (and not declared global), declared local, or used as a function argument name. Otherwise, it is considered global. Local variables are then renamed to be unique (using the [`gensym`](../../base/base/index#Base.gensym) function, which generates new symbols), and global variables are resolved within the macro definition environment. Therefore both of the above concerns are handled; the macro's locals will not conflict with any user variables, and `time_ns` and `println` will refer to the Julia Base definitions.
One problem remains however. Consider the following use of this macro:
```
module MyModule
import Base.@time
time_ns() = ... # compute something
@time time_ns()
end
```
Here the user expression `ex` is a call to `time_ns`, but not the same `time_ns` function that the macro uses. It clearly refers to `MyModule.time_ns`. Therefore we must arrange for the code in `ex` to be resolved in the macro call environment. This is done by "escaping" the expression with [`esc`](../../base/base/index#Base.esc):
```
macro time(ex)
...
local val = $(esc(ex))
...
end
```
An expression wrapped in this manner is left alone by the macro expander and simply pasted into the output verbatim. Therefore it will be resolved in the macro call environment.
This escaping mechanism can be used to "violate" hygiene when necessary, in order to introduce or manipulate user variables. For example, the following macro sets `x` to zero in the call environment:
```
julia> macro zerox()
return esc(:(x = 0))
end
@zerox (macro with 1 method)
julia> function foo()
x = 1
@zerox
return x # is zero
end
foo (generic function with 1 method)
julia> foo()
0
```
This kind of manipulation of variables should be used judiciously, but is occasionally quite handy.
Getting the hygiene rules correct can be a formidable challenge. Before using a macro, you might want to consider whether a function closure would be sufficient. Another useful strategy is to defer as much work as possible to runtime. For example, many macros simply wrap their arguments in a `QuoteNode` or other similar [`Expr`](../../base/base/index#Core.Expr). Some examples of this include `@task body` which simply returns `schedule(Task(() -> $body))`, and `@eval expr`, which simply returns `eval(QuoteNode(expr))`.
To demonstrate, we might rewrite the `@time` example above as:
```
macro time(expr)
return :(timeit(() -> $(esc(expr))))
end
function timeit(f)
t0 = time_ns()
val = f()
t1 = time_ns()
println("elapsed time: ", (t1-t0)/1e9, " seconds")
return val
end
```
However, we don't do this for a good reason: wrapping the `expr` in a new scope block (the anonymous function) also slightly changes the meaning of the expression (the scope of any variables in it), while we want `@time` to be usable with minimum impact on the wrapped code.
###
[Macros and dispatch](#Macros-and-dispatch)
Macros, just like Julia functions, are generic. This means they can also have multiple method definitions, thanks to multiple dispatch:
```
julia> macro m end
@m (macro with 0 methods)
julia> macro m(args...)
println("$(length(args)) arguments")
end
@m (macro with 1 method)
julia> macro m(x,y)
println("Two arguments")
end
@m (macro with 2 methods)
julia> @m "asd"
1 arguments
julia> @m 1 2
Two arguments
```
However one should keep in mind, that macro dispatch is based on the types of AST that are handed to the macro, not the types that the AST evaluates to at runtime:
```
julia> macro m(::Int)
println("An Integer")
end
@m (macro with 3 methods)
julia> @m 2
An Integer
julia> x = 2
2
julia> @m x
1 arguments
```
[Code Generation](#Code-Generation)
------------------------------------
When a significant amount of repetitive boilerplate code is required, it is common to generate it programmatically to avoid redundancy. In most languages, this requires an extra build step, and a separate program to generate the repetitive code. In Julia, expression interpolation and [`eval`](../../base/base/index#Base.MainInclude.eval) allow such code generation to take place in the normal course of program execution. For example, consider the following custom type
```
struct MyNumber
x::Float64
end
# output
```
for which we want to add a number of methods to. We can do this programmatically in the following loop:
```
for op = (:sin, :cos, :tan, :log, :exp)
eval(quote
Base.$op(a::MyNumber) = MyNumber($op(a.x))
end)
end
# output
```
and we can now use those functions with our custom type:
```
julia> x = MyNumber(π)
MyNumber(3.141592653589793)
julia> sin(x)
MyNumber(1.2246467991473532e-16)
julia> cos(x)
MyNumber(-1.0)
```
In this manner, Julia acts as its own [preprocessor](https://en.wikipedia.org/wiki/Preprocessor), and allows code generation from inside the language. The above code could be written slightly more tersely using the `:` prefix quoting form:
```
for op = (:sin, :cos, :tan, :log, :exp)
eval(:(Base.$op(a::MyNumber) = MyNumber($op(a.x))))
end
```
This sort of in-language code generation, however, using the `eval(quote(...))` pattern, is common enough that Julia comes with a macro to abbreviate this pattern:
```
for op = (:sin, :cos, :tan, :log, :exp)
@eval Base.$op(a::MyNumber) = MyNumber($op(a.x))
end
```
The [`@eval`](../../base/base/index#Base.@eval) macro rewrites this call to be precisely equivalent to the above longer versions. For longer blocks of generated code, the expression argument given to [`@eval`](../../base/base/index#Base.@eval) can be a block:
```
@eval begin
# multiple lines
end
```
[Non-Standard String Literals](#meta-non-standard-string-literals)
-------------------------------------------------------------------
Recall from [Strings](../strings/index#non-standard-string-literals) that string literals prefixed by an identifier are called non-standard string literals, and can have different semantics than un-prefixed string literals. For example:
* `r"^\s*(?:#|$)"` produces a [regular expression object](../strings/index#man-regex-literals) rather than a string
* `b"DATA\xff\u2200"` is a [byte array literal](../strings/index#man-byte-array-literals) for `[68,65,84,65,255,226,136,128]`.
Perhaps surprisingly, these behaviors are not hard-coded into the Julia parser or compiler. Instead, they are custom behaviors provided by a general mechanism that anyone can use: prefixed string literals are parsed as calls to specially-named macros. For example, the regular expression macro is just the following:
```
macro r_str(p)
Regex(p)
end
```
That's all. This macro says that the literal contents of the string literal `r"^\s*(?:#|$)"` should be passed to the `@r_str` macro and the result of that expansion should be placed in the syntax tree where the string literal occurs. In other words, the expression `r"^\s*(?:#|$)"` is equivalent to placing the following object directly into the syntax tree:
```
Regex("^\\s*(?:#|\$)")
```
Not only is the string literal form shorter and far more convenient, but it is also more efficient: since the regular expression is compiled and the `Regex` object is actually created *when the code is compiled*, the compilation occurs only once, rather than every time the code is executed. Consider if the regular expression occurs in a loop:
```
for line = lines
m = match(r"^\s*(?:#|$)", line)
if m === nothing
# non-comment
else
# comment
end
end
```
Since the regular expression `r"^\s*(?:#|$)"` is compiled and inserted into the syntax tree when this code is parsed, the expression is only compiled once instead of each time the loop is executed. In order to accomplish this without macros, one would have to write this loop like this:
```
re = Regex("^\\s*(?:#|\$)")
for line = lines
m = match(re, line)
if m === nothing
# non-comment
else
# comment
end
end
```
Moreover, if the compiler could not determine that the regex object was constant over all loops, certain optimizations might not be possible, making this version still less efficient than the more convenient literal form above. Of course, there are still situations where the non-literal form is more convenient: if one needs to interpolate a variable into the regular expression, one must take this more verbose approach; in cases where the regular expression pattern itself is dynamic, potentially changing upon each loop iteration, a new regular expression object must be constructed on each iteration. In the vast majority of use cases, however, regular expressions are not constructed based on run-time data. In this majority of cases, the ability to write regular expressions as compile-time values is invaluable.
The mechanism for user-defined string literals is deeply, profoundly powerful. Not only are Julia's non-standard literals implemented using it, but the command literal syntax (``echo "Hello, $person"``) is also implemented using the following innocuous-looking macro:
```
macro cmd(str)
:(cmd_gen($(shell_parse(str)[1])))
end
```
Of course, a large amount of complexity is hidden in the functions used in this macro definition, but they are just functions, written entirely in Julia. You can read their source and see precisely what they do – and all they do is construct expression objects to be inserted into your program's syntax tree.
Like string literals, command literals can also be prefixed by an identifier to form what are called non-standard command literals. These command literals are parsed as calls to specially-named macros. For example, the syntax `custom`literal`` is parsed as `@custom_cmd "literal"`. Julia itself does not contain any non-standard command literals, but packages can make use of this syntax. Aside from the different syntax and the `_cmd` suffix instead of the `_str` suffix, non-standard command literals behave exactly like non-standard string literals.
In the event that two modules provide non-standard string or command literals with the same name, it is possible to qualify the string or command literal with a module name. For instance, if both `Foo` and `Bar` provide non-standard string literal `@x_str`, then one can write `Foo.x"literal"` or `Bar.x"literal"` to disambiguate between the two.
Another way to define a macro would be like this:
```
macro foo_str(str, flag)
# do stuff
end
```
This macro can then be called with the following syntax:
```
foo"str"flag
```
The type of flag in the above mentioned syntax would be a `String` with contents of whatever trails after the string literal.
[Generated functions](#Generated-functions)
--------------------------------------------
A very special macro is [`@generated`](../../base/base/index#Base.@generated), which allows you to define so-called *generated functions*. These have the capability to generate specialized code depending on the types of their arguments with more flexibility and/or less code than what can be achieved with multiple dispatch. While macros work with expressions at parse time and cannot access the types of their inputs, a generated function gets expanded at a time when the types of the arguments are known, but the function is not yet compiled.
Instead of performing some calculation or action, a generated function declaration returns a quoted expression which then forms the body for the method corresponding to the types of the arguments. When a generated function is called, the expression it returns is compiled and then run. To make this efficient, the result is usually cached. And to make this inferable, only a limited subset of the language is usable. Thus, generated functions provide a flexible way to move work from run time to compile time, at the expense of greater restrictions on allowed constructs.
When defining generated functions, there are five main differences to ordinary functions:
1. You annotate the function declaration with the `@generated` macro. This adds some information to the AST that lets the compiler know that this is a generated function.
2. In the body of the generated function you only have access to the *types* of the arguments – not their values.
3. Instead of calculating something or performing some action, you return a *quoted expression* which, when evaluated, does what you want.
4. Generated functions are only permitted to call functions that were defined *before* the definition of the generated function. (Failure to follow this may result in getting `MethodErrors` referring to functions from a future world-age.)
5. Generated functions must not *mutate* or *observe* any non-constant global state (including, for example, IO, locks, non-local dictionaries, or using [`hasmethod`](../../base/base/index#Base.hasmethod)). This means they can only read global constants, and cannot have any side effects. In other words, they must be completely pure. Due to an implementation limitation, this also means that they currently cannot define a closure or generator.
It's easiest to illustrate this with an example. We can declare a generated function `foo` as
```
julia> @generated function foo(x)
Core.println(x)
return :(x * x)
end
foo (generic function with 1 method)
```
Note that the body returns a quoted expression, namely `:(x * x)`, rather than just the value of `x * x`.
From the caller's perspective, this is identical to a regular function; in fact, you don't have to know whether you're calling a regular or generated function. Let's see how `foo` behaves:
```
julia> x = foo(2); # note: output is from println() statement in the body
Int64
julia> x # now we print x
4
julia> y = foo("bar");
String
julia> y
"barbar"
```
So, we see that in the body of the generated function, `x` is the *type* of the passed argument, and the value returned by the generated function, is the result of evaluating the quoted expression we returned from the definition, now with the *value* of `x`.
What happens if we evaluate `foo` again with a type that we have already used?
```
julia> foo(4)
16
```
Note that there is no printout of [`Int64`](../../base/numbers/index#Core.Int64). We can see that the body of the generated function was only executed once here, for the specific set of argument types, and the result was cached. After that, for this example, the expression returned from the generated function on the first invocation was re-used as the method body. However, the actual caching behavior is an implementation-defined performance optimization, so it is invalid to depend too closely on this behavior.
The number of times a generated function is generated *might* be only once, but it *might* also be more often, or appear to not happen at all. As a consequence, you should *never* write a generated function with side effects - when, and how often, the side effects occur is undefined. (This is true for macros too - and just like for macros, the use of [`eval`](../../base/base/index#Base.MainInclude.eval) in a generated function is a sign that you're doing something the wrong way.) However, unlike macros, the runtime system cannot correctly handle a call to [`eval`](../../base/base/index#Base.MainInclude.eval), so it is disallowed.
It is also important to see how `@generated` functions interact with method redefinition. Following the principle that a correct `@generated` function must not observe any mutable state or cause any mutation of global state, we see the following behavior. Observe that the generated function *cannot* call any method that was not defined prior to the *definition* of the generated function itself.
Initially `f(x)` has one definition
```
julia> f(x) = "original definition";
```
Define other operations that use `f(x)`:
```
julia> g(x) = f(x);
julia> @generated gen1(x) = f(x);
julia> @generated gen2(x) = :(f(x));
```
We now add some new definitions for `f(x)`:
```
julia> f(x::Int) = "definition for Int";
julia> f(x::Type{Int}) = "definition for Type{Int}";
```
and compare how these results differ:
```
julia> f(1)
"definition for Int"
julia> g(1)
"definition for Int"
julia> gen1(1)
"original definition"
julia> gen2(1)
"definition for Int"
```
Each method of a generated function has its own view of defined functions:
```
julia> @generated gen1(x::Real) = f(x);
julia> gen1(1)
"definition for Type{Int}"
```
The example generated function `foo` above did not do anything a normal function `foo(x) = x * x` could not do (except printing the type on the first invocation, and incurring higher overhead). However, the power of a generated function lies in its ability to compute different quoted expressions depending on the types passed to it:
```
julia> @generated function bar(x)
if x <: Integer
return :(x ^ 2)
else
return :(x)
end
end
bar (generic function with 1 method)
julia> bar(4)
16
julia> bar("baz")
"baz"
```
(although of course this contrived example would be more easily implemented using multiple dispatch...)
Abusing this will corrupt the runtime system and cause undefined behavior:
```
julia> @generated function baz(x)
if rand() < .9
return :(x^2)
else
return :("boo!")
end
end
baz (generic function with 1 method)
```
Since the body of the generated function is non-deterministic, its behavior, *and the behavior of all subsequent code* is undefined.
*Don't copy these examples!*
These examples are hopefully helpful to illustrate how generated functions work, both in the definition end and at the call site; however, *don't copy them*, for the following reasons:
* the `foo` function has side-effects (the call to `Core.println`), and it is undefined exactly when, how often or how many times these side-effects will occur
* the `bar` function solves a problem that is better solved with multiple dispatch - defining `bar(x) = x` and `bar(x::Integer) = x ^ 2` will do the same thing, but it is both simpler and faster.
* the `baz` function is pathological
Note that the set of operations that should not be attempted in a generated function is unbounded, and the runtime system can currently only detect a subset of the invalid operations. There are many other operations that will simply corrupt the runtime system without notification, usually in subtle ways not obviously connected to the bad definition. Because the function generator is run during inference, it must respect all of the limitations of that code.
Some operations that should not be attempted include:
1. Caching of native pointers.
2. Interacting with the contents or methods of `Core.Compiler` in any way.
3. Observing any mutable state.
* Inference on the generated function may be run at *any* time, including while your code is attempting to observe or mutate this state.
4. Taking any locks: C code you call out to may use locks internally, (for example, it is not problematic to call `malloc`, even though most implementations require locks internally) but don't attempt to hold or acquire any while executing Julia code.
5. Calling any function that is defined after the body of the generated function. This condition is relaxed for incrementally-loaded precompiled modules to allow calling any function in the module.
Alright, now that we have a better understanding of how generated functions work, let's use them to build some more advanced (and valid) functionality...
###
[An advanced example](#An-advanced-example)
Julia's base library has an internal `sub2ind` function to calculate a linear index into an n-dimensional array, based on a set of n multilinear indices - in other words, to calculate the index `i` that can be used to index into an array `A` using `A[i]`, instead of `A[x,y,z,...]`. One possible implementation is the following:
```
julia> function sub2ind_loop(dims::NTuple{N}, I::Integer...) where N
ind = I[N] - 1
for i = N-1:-1:1
ind = I[i]-1 + dims[i]*ind
end
return ind + 1
end
sub2ind_loop (generic function with 1 method)
julia> sub2ind_loop((3, 5), 1, 2)
4
```
The same thing can be done using recursion:
```
julia> sub2ind_rec(dims::Tuple{}) = 1;
julia> sub2ind_rec(dims::Tuple{}, i1::Integer, I::Integer...) =
i1 == 1 ? sub2ind_rec(dims, I...) : throw(BoundsError());
julia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer) = i1;
julia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer, I::Integer...) =
i1 + dims[1] * (sub2ind_rec(Base.tail(dims), I...) - 1);
julia> sub2ind_rec((3, 5), 1, 2)
4
```
Both these implementations, although different, do essentially the same thing: a runtime loop over the dimensions of the array, collecting the offset in each dimension into the final index.
However, all the information we need for the loop is embedded in the type information of the arguments. Thus, we can utilize generated functions to move the iteration to compile-time; in compiler parlance, we use generated functions to manually unroll the loop. The body becomes almost identical, but instead of calculating the linear index, we build up an *expression* that calculates the index:
```
julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N
ex = :(I[$N] - 1)
for i = (N - 1):-1:1
ex = :(I[$i] - 1 + dims[$i] * $ex)
end
return :($ex + 1)
end
sub2ind_gen (generic function with 1 method)
julia> sub2ind_gen((3, 5), 1, 2)
4
```
**What code will this generate?**
An easy way to find out is to extract the body into another (regular) function:
```
julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N
return sub2ind_gen_impl(dims, I...)
end
sub2ind_gen (generic function with 1 method)
julia> function sub2ind_gen_impl(dims::Type{T}, I...) where T <: NTuple{N,Any} where N
length(I) == N || return :(error("partial indexing is unsupported"))
ex = :(I[$N] - 1)
for i = (N - 1):-1:1
ex = :(I[$i] - 1 + dims[$i] * $ex)
end
return :($ex + 1)
end
sub2ind_gen_impl (generic function with 1 method)
```
We can now execute `sub2ind_gen_impl` and examine the expression it returns:
```
julia> sub2ind_gen_impl(Tuple{Int,Int}, Int, Int)
:(((I[1] - 1) + dims[1] * (I[2] - 1)) + 1)
```
So, the method body that will be used here doesn't include a loop at all - just indexing into the two tuples, multiplication and addition/subtraction. All the looping is performed compile-time, and we avoid looping during execution entirely. Thus, we only loop *once per type*, in this case once per `N` (except in edge cases where the function is generated more than once - see disclaimer above).
###
[Optionally-generated functions](#Optionally-generated-functions)
Generated functions can achieve high efficiency at run time, but come with a compile time cost: a new function body must be generated for every combination of concrete argument types. Typically, Julia is able to compile "generic" versions of functions that will work for any arguments, but with generated functions this is impossible. This means that programs making heavy use of generated functions might be impossible to statically compile.
To solve this problem, the language provides syntax for writing normal, non-generated alternative implementations of generated functions. Applied to the `sub2ind` example above, it would look like this:
```
function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N
if N != length(I)
throw(ArgumentError("Number of dimensions must match number of indices."))
end
if @generated
ex = :(I[$N] - 1)
for i = (N - 1):-1:1
ex = :(I[$i] - 1 + dims[$i] * $ex)
end
return :($ex + 1)
else
ind = I[N] - 1
for i = (N - 1):-1:1
ind = I[i] - 1 + dims[i]*ind
end
return ind + 1
end
end
```
Internally, this code creates two implementations of the function: a generated one where the first block in `if @generated` is used, and a normal one where the `else` block is used. Inside the `then` part of the `if @generated` block, code has the same semantics as other generated functions: argument names refer to types, and the code should return an expression. Multiple `if @generated` blocks may occur, in which case the generated implementation uses all of the `then` blocks and the alternate implementation uses all of the `else` blocks.
Notice that we added an error check to the top of the function. This code will be common to both versions, and is run-time code in both versions (it will be quoted and returned as an expression from the generated version). That means that the values and types of local variables are not available at code generation time –- the code-generation code can only see the types of arguments.
In this style of definition, the code generation feature is essentially an optional optimization. The compiler will use it if convenient, but otherwise may choose to use the normal implementation instead. This style is preferred, since it allows the compiler to make more decisions and compile programs in more ways, and since normal code is more readable than code-generating code. However, which implementation is used depends on compiler implementation details, so it is essential for the two implementations to behave identically.
| programming_docs |
julia Multi-processing and Distributed Computing Multi-processing and Distributed Computing
==========================================
An implementation of distributed memory parallel computing is provided by module [`Distributed`](../../stdlib/distributed/index#man-distributed) as part of the standard library shipped with Julia.
Most modern computers possess more than one CPU, and several computers can be combined together in a cluster. Harnessing the power of these multiple CPUs allows many computations to be completed more quickly. There are two major factors that influence performance: the speed of the CPUs themselves, and the speed of their access to memory. In a cluster, it's fairly obvious that a given CPU will have fastest access to the RAM within the same computer (node). Perhaps more surprisingly, similar issues are relevant on a typical multicore laptop, due to differences in the speed of main memory and the [cache](https://www.akkadia.org/drepper/cpumemory.pdf). Consequently, a good multiprocessing environment should allow control over the "ownership" of a chunk of memory by a particular CPU. Julia provides a multiprocessing environment based on message passing to allow programs to run on multiple processes in separate memory domains at once.
Julia's implementation of message passing is different from other environments such as MPI[[1]](#footnote-1). Communication in Julia is generally "one-sided", meaning that the programmer needs to explicitly manage only one process in a two-process operation. Furthermore, these operations typically do not look like "message send" and "message receive" but rather resemble higher-level operations like calls to user functions.
Distributed programming in Julia is built on two primitives: *remote references* and *remote calls*. A remote reference is an object that can be used from any process to refer to an object stored on a particular process. A remote call is a request by one process to call a certain function on certain arguments on another (possibly the same) process.
Remote references come in two flavors: [`Future`](../../stdlib/distributed/index#Distributed.Future) and [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel).
A remote call returns a [`Future`](../../stdlib/distributed/index#Distributed.Future) to its result. Remote calls return immediately; the process that made the call proceeds to its next operation while the remote call happens somewhere else. You can wait for a remote call to finish by calling [`wait`](../../base/parallel/index#Base.wait) on the returned [`Future`](../../stdlib/distributed/index#Distributed.Future), and you can obtain the full value of the result using [`fetch`](#).
On the other hand, [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) s are rewritable. For example, multiple processes can co-ordinate their processing by referencing the same remote `Channel`.
Each process has an associated identifier. The process providing the interactive Julia prompt always has an `id` equal to 1. The processes used by default for parallel operations are referred to as "workers". When there is only one process, process 1 is considered a worker. Otherwise, workers are considered to be all processes other than process 1. As a result, adding 2 or more processes is required to gain benefits from parallel processing methods like [`pmap`](../../stdlib/distributed/index#Distributed.pmap). Adding a single process is beneficial if you just wish to do other things in the main process while a long computation is running on the worker.
Let's try this out. Starting with `julia -p n` provides `n` worker processes on the local machine. Generally it makes sense for `n` to equal the number of CPU threads (logical cores) on the machine. Note that the `-p` argument implicitly loads module [`Distributed`](../../stdlib/distributed/index#man-distributed).
```
$ julia -p 2
julia> r = remotecall(rand, 2, 2, 2)
Future(2, 1, 4, nothing)
julia> s = @spawnat 2 1 .+ fetch(r)
Future(2, 1, 5, nothing)
julia> fetch(s)
2×2 Array{Float64,2}:
1.18526 1.50912
1.16296 1.60607
```
The first argument to [`remotecall`](#) is the function to call. Most parallel programming in Julia does not reference specific processes or the number of processes available, but [`remotecall`](#) is considered a low-level interface providing finer control. The second argument to [`remotecall`](#) is the `id` of the process that will do the work, and the remaining arguments will be passed to the function being called.
As you can see, in the first line we asked process 2 to construct a 2-by-2 random matrix, and in the second line we asked it to add 1 to it. The result of both calculations is available in the two futures, `r` and `s`. The [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) macro evaluates the expression in the second argument on the process specified by the first argument.
Occasionally you might want a remotely-computed value immediately. This typically happens when you read from a remote object to obtain data needed by the next local operation. The function [`remotecall_fetch`](#) exists for this purpose. It is equivalent to `fetch(remotecall(...))` but is more efficient.
```
julia> remotecall_fetch(r-> fetch(r)[1, 1], 2, r)
0.18526337335308085
```
This fetches the array on worker 2 and returns the first value. Note, that `fetch` doesn't move any data in this case, since it's executed on the worker that owns the array. One can also write:
```
julia> remotecall_fetch(getindex, 2, r, 1, 1)
0.10824216411304866
```
Remember that [`getindex(r,1,1)`](#) is [equivalent](../arrays/index#man-array-indexing) to `r[1,1]`, so this call fetches the first element of the future `r`.
To make things easier, the symbol `:any` can be passed to [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat), which picks where to do the operation for you:
```
julia> r = @spawnat :any rand(2,2)
Future(2, 1, 4, nothing)
julia> s = @spawnat :any 1 .+ fetch(r)
Future(3, 1, 5, nothing)
julia> fetch(s)
2×2 Array{Float64,2}:
1.38854 1.9098
1.20939 1.57158
```
Note that we used `1 .+ fetch(r)` instead of `1 .+ r`. This is because we do not know where the code will run, so in general a [`fetch`](#) might be required to move `r` to the process doing the addition. In this case, [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) is smart enough to perform the computation on the process that owns `r`, so the [`fetch`](#) will be a no-op (no work is done).
(It is worth noting that [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) is not built-in but defined in Julia as a [macro](../metaprogramming/index#man-macros). It is possible to define your own such constructs.)
An important thing to remember is that, once fetched, a [`Future`](../../stdlib/distributed/index#Distributed.Future) will cache its value locally. Further [`fetch`](#) calls do not entail a network hop. Once all referencing [`Future`](../../stdlib/distributed/index#Distributed.Future)s have fetched, the remote stored value is deleted.
[`@async`](../../base/parallel/index#Base.@async) is similar to [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat), but only runs tasks on the local process. We use it to create a "feeder" task for each process. Each task picks the next index that needs to be computed, then waits for its process to finish, then repeats until we run out of indices. Note that the feeder tasks do not begin to execute until the main task reaches the end of the [`@sync`](../../base/parallel/index#Base.@sync) block, at which point it surrenders control and waits for all the local tasks to complete before returning from the function. As for v0.7 and beyond, the feeder tasks are able to share state via `nextidx` because they all run on the same process. Even if `Tasks` are scheduled cooperatively, locking may still be required in some contexts, as in [asynchronous I/O](../faq/index#faq-async-io). This means context switches only occur at well-defined points: in this case, when [`remotecall_fetch`](#) is called. This is the current state of implementation and it may change for future Julia versions, as it is intended to make it possible to run up to N `Tasks` on M `Process`, aka [M:N Threading](https://en.wikipedia.org/wiki/Thread_(computing)#Models). Then a lock acquiring\releasing model for `nextidx` will be needed, as it is not safe to let multiple processes read-write a resource at the same time.
[Code Availability and Loading Packages](#code-availability)
-------------------------------------------------------------
Your code must be available on any process that runs it. For example, type the following into the Julia prompt:
```
julia> function rand2(dims...)
return 2*rand(dims...)
end
julia> rand2(2,2)
2×2 Array{Float64,2}:
0.153756 0.368514
1.15119 0.918912
julia> fetch(@spawnat :any rand2(2,2))
ERROR: RemoteException(2, CapturedException(UndefVarError(Symbol("#rand2"))
Stacktrace:
[...]
```
Process 1 knew about the function `rand2`, but process 2 did not.
Most commonly you'll be loading code from files or packages, and you have a considerable amount of flexibility in controlling which processes load code. Consider a file, `DummyModule.jl`, containing the following code:
```
module DummyModule
export MyType, f
mutable struct MyType
a::Int
end
f(x) = x^2+1
println("loaded")
end
```
In order to refer to `MyType` across all processes, `DummyModule.jl` needs to be loaded on every process. Calling `include("DummyModule.jl")` loads it only on a single process. To load it on every process, use the [`@everywhere`](../../stdlib/distributed/index#Distributed.@everywhere) macro (starting Julia with `julia -p 2`):
```
julia> @everywhere include("DummyModule.jl")
loaded
From worker 3: loaded
From worker 2: loaded
```
As usual, this does not bring `DummyModule` into scope on any of the process, which requires [`using`](../../base/base/index#using) or [`import`](../../base/base/index#import). Moreover, when `DummyModule` is brought into scope on one process, it is not on any other:
```
julia> using .DummyModule
julia> MyType(7)
MyType(7)
julia> fetch(@spawnat 2 MyType(7))
ERROR: On worker 2:
UndefVarError: MyType not defined
⋮
julia> fetch(@spawnat 2 DummyModule.MyType(7))
MyType(7)
```
However, it's still possible, for instance, to send a `MyType` to a process which has loaded `DummyModule` even if it's not in scope:
```
julia> put!(RemoteChannel(2), MyType(7))
RemoteChannel{Channel{Any}}(2, 1, 13)
```
A file can also be preloaded on multiple processes at startup with the `-L` flag, and a driver script can be used to drive the computation:
```
julia -p <n> -L file1.jl -L file2.jl driver.jl
```
The Julia process running the driver script in the example above has an `id` equal to 1, just like a process providing an interactive prompt.
Finally, if `DummyModule.jl` is not a standalone file but a package, then `using DummyModule` will *load* `DummyModule.jl` on all processes, but only bring it into scope on the process where [`using`](../../base/base/index#using) was called.
[Starting and managing worker processes](#Starting-and-managing-worker-processes)
----------------------------------------------------------------------------------
The base Julia installation has in-built support for two types of clusters:
* A local cluster specified with the `-p` option as shown above.
* A cluster spanning machines using the `--machine-file` option. This uses a passwordless `ssh` login to start Julia worker processes (from the same path as the current host) on the specified machines. Each machine definition takes the form `[count*][user@]host[:port] [bind_addr[:port]]`. `user` defaults to current user, `port` to the standard ssh port. `count` is the number of workers to spawn on the node, and defaults to 1. The optional `bind-to bind_addr[:port]` specifies the IP address and port that other workers should use to connect to this worker.
Functions [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs), [`rmprocs`](../../stdlib/distributed/index#Distributed.rmprocs), [`workers`](../../stdlib/distributed/index#Distributed.workers), and others are available as a programmatic means of adding, removing and querying the processes in a cluster.
```
julia> using Distributed
julia> addprocs(2)
2-element Array{Int64,1}:
2
3
```
Module [`Distributed`](../../stdlib/distributed/index#man-distributed) must be explicitly loaded on the master process before invoking [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs). It is automatically made available on the worker processes.
Note that workers do not run a `~/.julia/config/startup.jl` startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes. You may use `addprocs(exeflags="--project")` to initialize a worker with a particular environment, and then `@everywhere using <modulename>` or `@everywhere include("file.jl")`.
Other types of clusters can be supported by writing your own custom `ClusterManager`, as described below in the [ClusterManagers](#ClusterManagers) section.
[Data Movement](#Data-Movement)
--------------------------------
Sending messages and moving data constitute most of the overhead in a distributed program. Reducing the number of messages and the amount of data sent is critical to achieving performance and scalability. To this end, it is important to understand the data movement performed by Julia's various distributed programming constructs.
[`fetch`](#) can be considered an explicit data movement operation, since it directly asks that an object be moved to the local machine. [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) (and a few related constructs) also moves data, but this is not as obvious, hence it can be called an implicit data movement operation. Consider these two approaches to constructing and squaring a random matrix:
Method 1:
```
julia> A = rand(1000,1000);
julia> Bref = @spawnat :any A^2;
[...]
julia> fetch(Bref);
```
Method 2:
```
julia> Bref = @spawnat :any rand(1000,1000)^2;
[...]
julia> fetch(Bref);
```
The difference seems trivial, but in fact is quite significant due to the behavior of [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat). In the first method, a random matrix is constructed locally, then sent to another process where it is squared. In the second method, a random matrix is both constructed and squared on another process. Therefore the second method sends much less data than the first.
In this toy example, the two methods are easy to distinguish and choose from. However, in a real program designing data movement might require more thought and likely some measurement. For example, if the first process needs matrix `A` then the first method might be better. Or, if computing `A` is expensive and only the current process has it, then moving it to another process might be unavoidable. Or, if the current process has very little to do between the [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) and `fetch(Bref)`, it might be better to eliminate the parallelism altogether. Or imagine `rand(1000,1000)` is replaced with a more expensive operation. Then it might make sense to add another [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) statement just for this step.
[Global variables](#Global-variables)
--------------------------------------
Expressions executed remotely via [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat), or closures specified for remote execution using [`remotecall`](#) may refer to global variables. Global bindings under module `Main` are treated a little differently compared to global bindings in other modules. Consider the following code snippet:
```
A = rand(10,10)
remotecall_fetch(()->sum(A), 2)
```
In this case [`sum`](../../base/collections/index#Base.sum) MUST be defined in the remote process. Note that `A` is a global variable defined in the local workspace. Worker 2 does not have a variable called `A` under `Main`. The act of shipping the closure `()->sum(A)` to worker 2 results in `Main.A` being defined on 2. `Main.A` continues to exist on worker 2 even after the call [`remotecall_fetch`](#) returns. Remote calls with embedded global references (under `Main` module only) manage globals as follows:
* New global bindings are created on destination workers if they are referenced as part of a remote call.
* Global constants are declared as constants on remote nodes too.
* Globals are re-sent to a destination worker only in the context of a remote call, and then only if its value has changed. Also, the cluster does not synchronize global bindings across nodes. For example:
```
A = rand(10,10)
remotecall_fetch(()->sum(A), 2) # worker 2
A = rand(10,10)
remotecall_fetch(()->sum(A), 3) # worker 3
A = nothing
```
Executing the above snippet results in `Main.A` on worker 2 having a different value from `Main.A` on worker 3, while the value of `Main.A` on node 1 is set to `nothing`.
As you may have realized, while memory associated with globals may be collected when they are reassigned on the master, no such action is taken on the workers as the bindings continue to be valid. [`clear!`](#) can be used to manually reassign specific globals on remote nodes to `nothing` once they are no longer required. This will release any memory associated with them as part of a regular garbage collection cycle.
Thus programs should be careful referencing globals in remote calls. In fact, it is preferable to avoid them altogether if possible. If you must reference globals, consider using `let` blocks to localize global variables.
For example:
```
julia> A = rand(10,10);
julia> remotecall_fetch(()->A, 2);
julia> B = rand(10,10);
julia> let B = B
remotecall_fetch(()->B, 2)
end;
julia> @fetchfrom 2 InteractiveUtils.varinfo()
name size summary
––––––––– ––––––––– ––––––––––––––––––––––
A 800 bytes 10×10 Array{Float64,2}
Base Module
Core Module
Main Module
```
As can be seen, global variable `A` is defined on worker 2, but `B` is captured as a local variable and hence a binding for `B` does not exist on worker 2.
[Parallel Map and Loops](#Parallel-Map-and-Loops)
--------------------------------------------------
Fortunately, many useful parallel computations do not require data movement. A common example is a Monte Carlo simulation, where multiple processes can handle independent simulation trials simultaneously. We can use [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) to flip coins on two processes. First, write the following function in `count_heads.jl`:
```
function count_heads(n)
c::Int = 0
for i = 1:n
c += rand(Bool)
end
c
end
```
The function `count_heads` simply adds together `n` random bits. Here is how we can perform some trials on two machines, and add together the results:
```
julia> @everywhere include_string(Main, $(read("count_heads.jl", String)), "count_heads.jl")
julia> a = @spawnat :any count_heads(100000000)
Future(2, 1, 6, nothing)
julia> b = @spawnat :any count_heads(100000000)
Future(3, 1, 7, nothing)
julia> fetch(a)+fetch(b)
100001564
```
This example demonstrates a powerful and often-used parallel programming pattern. Many iterations run independently over several processes, and then their results are combined using some function. The combination process is called a *reduction*, since it is generally tensor-rank-reducing: a vector of numbers is reduced to a single number, or a matrix is reduced to a single row or column, etc. In code, this typically looks like the pattern `x = f(x,v[i])`, where `x` is the accumulator, `f` is the reduction function, and the `v[i]` are the elements being reduced. It is desirable for `f` to be associative, so that it does not matter what order the operations are performed in.
Notice that our use of this pattern with `count_heads` can be generalized. We used two explicit [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) statements, which limits the parallelism to two processes. To run on any number of processes, we can use a *parallel for loop*, running in distributed memory, which can be written in Julia using [`@distributed`](../../stdlib/distributed/index#Distributed.@distributed) like this:
```
nheads = @distributed (+) for i = 1:200000000
Int(rand(Bool))
end
```
This construct implements the pattern of assigning iterations to multiple processes, and combining them with a specified reduction (in this case `(+)`). The result of each iteration is taken as the value of the last expression inside the loop. The whole parallel loop expression itself evaluates to the final answer.
Note that although parallel for loops look like serial for loops, their behavior is dramatically different. In particular, the iterations do not happen in a specified order, and writes to variables or arrays will not be globally visible since iterations run on different processes. Any variables used inside the parallel loop will be copied and broadcast to each process.
For example, the following code will not work as intended:
```
a = zeros(100000)
@distributed for i = 1:100000
a[i] = i
end
```
This code will not initialize all of `a`, since each process will have a separate copy of it. Parallel for loops like these must be avoided. Fortunately, [Shared Arrays](#man-shared-arrays) can be used to get around this limitation:
```
using SharedArrays
a = SharedArray{Float64}(10)
@distributed for i = 1:10
a[i] = i
end
```
Using "outside" variables in parallel loops is perfectly reasonable if the variables are read-only:
```
a = randn(1000)
@distributed (+) for i = 1:100000
f(a[rand(1:end)])
end
```
Here each iteration applies `f` to a randomly-chosen sample from a vector `a` shared by all processes.
As you could see, the reduction operator can be omitted if it is not needed. In that case, the loop executes asynchronously, i.e. it spawns independent tasks on all available workers and returns an array of [`Future`](../../stdlib/distributed/index#Distributed.Future) immediately without waiting for completion. The caller can wait for the [`Future`](../../stdlib/distributed/index#Distributed.Future) completions at a later point by calling [`fetch`](#) on them, or wait for completion at the end of the loop by prefixing it with [`@sync`](../../base/parallel/index#Base.@sync), like `@sync @distributed for`.
In some cases no reduction operator is needed, and we merely wish to apply a function to all integers in some range (or, more generally, to all elements in some collection). This is another useful operation called *parallel map*, implemented in Julia as the [`pmap`](../../stdlib/distributed/index#Distributed.pmap) function. For example, we could compute the singular values of several large random matrices in parallel as follows:
```
julia> M = Matrix{Float64}[rand(1000,1000) for i = 1:10];
julia> pmap(svdvals, M);
```
Julia's [`pmap`](../../stdlib/distributed/index#Distributed.pmap) is designed for the case where each function call does a large amount of work. In contrast, `@distributed for` can handle situations where each iteration is tiny, perhaps merely summing two numbers. Only worker processes are used by both [`pmap`](../../stdlib/distributed/index#Distributed.pmap) and `@distributed for` for the parallel computation. In case of `@distributed for`, the final reduction is done on the calling process.
[Remote References and AbstractChannels](#Remote-References-and-AbstractChannels)
----------------------------------------------------------------------------------
Remote references always refer to an implementation of an `AbstractChannel`.
A concrete implementation of an `AbstractChannel` (like `Channel`), is required to implement [`put!`](#), [`take!`](#), [`fetch`](#), [`isready`](#) and [`wait`](../../base/parallel/index#Base.wait). The remote object referred to by a [`Future`](../../stdlib/distributed/index#Distributed.Future) is stored in a `Channel{Any}(1)`, i.e., a `Channel` of size 1 capable of holding objects of `Any` type.
[`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel), which is rewritable, can point to any type and size of channels, or any other implementation of an `AbstractChannel`.
The constructor `RemoteChannel(f::Function, pid)()` allows us to construct references to channels holding more than one value of a specific type. `f` is a function executed on `pid` and it must return an `AbstractChannel`.
For example, `RemoteChannel(()->Channel{Int}(10), pid)`, will return a reference to a channel of type `Int` and size 10. The channel exists on worker `pid`.
Methods [`put!`](#), [`take!`](#), [`fetch`](#), [`isready`](#) and [`wait`](../../base/parallel/index#Base.wait) on a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) are proxied onto the backing store on the remote process.
[`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) can thus be used to refer to user implemented `AbstractChannel` objects. A simple example of this is provided in `dictchannel.jl` in the [Examples repository](https://github.com/JuliaAttic/Examples), which uses a dictionary as its remote store.
[Channels and RemoteChannels](#Channels-and-RemoteChannels)
------------------------------------------------------------
* A [`Channel`](../../base/parallel/index#Base.Channel) is local to a process. Worker 2 cannot directly refer to a [`Channel`](../../base/parallel/index#Base.Channel) on worker 3 and vice-versa. A [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel), however, can put and take values across workers.
* A [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) can be thought of as a *handle* to a [`Channel`](../../base/parallel/index#Base.Channel).
* The process id, `pid`, associated with a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) identifies the process where the backing store, i.e., the backing [`Channel`](../../base/parallel/index#Base.Channel) exists.
* Any process with a reference to a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) can put and take items from the channel. Data is automatically sent to (or retrieved from) the process a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) is associated with.
* Serializing a [`Channel`](../../base/parallel/index#Base.Channel) also serializes any data present in the channel. Deserializing it therefore effectively makes a copy of the original object.
* On the other hand, serializing a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) only involves the serialization of an identifier that identifies the location and instance of [`Channel`](../../base/parallel/index#Base.Channel) referred to by the handle. A deserialized [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) object (on any worker), therefore also points to the same backing store as the original.
The channels example from above can be modified for interprocess communication, as shown below.
We start 4 workers to process a single `jobs` remote channel. Jobs, identified by an id (`job_id`), are written to the channel. Each remotely executing task in this simulation reads a `job_id`, waits for a random amount of time and writes back a tuple of `job_id`, time taken and its own `pid` to the results channel. Finally all the `results` are printed out on the master process.
```
julia> addprocs(4); # add worker processes
julia> const jobs = RemoteChannel(()->Channel{Int}(32));
julia> const results = RemoteChannel(()->Channel{Tuple}(32));
julia> @everywhere function do_work(jobs, results) # define work function everywhere
while true
job_id = take!(jobs)
exec_time = rand()
sleep(exec_time) # simulates elapsed time doing actual work
put!(results, (job_id, exec_time, myid()))
end
end
julia> function make_jobs(n)
for i in 1:n
put!(jobs, i)
end
end;
julia> n = 12;
julia> errormonitor(@async make_jobs(n)); # feed the jobs channel with "n" jobs
julia> for p in workers() # start tasks on the workers to process requests in parallel
remote_do(do_work, p, jobs, results)
end
julia> @elapsed while n > 0 # print out results
job_id, exec_time, where = take!(results)
println("$job_id finished in $(round(exec_time; digits=2)) seconds on worker $where")
global n = n - 1
end
1 finished in 0.18 seconds on worker 4
2 finished in 0.26 seconds on worker 5
6 finished in 0.12 seconds on worker 4
7 finished in 0.18 seconds on worker 4
5 finished in 0.35 seconds on worker 5
4 finished in 0.68 seconds on worker 2
3 finished in 0.73 seconds on worker 3
11 finished in 0.01 seconds on worker 3
12 finished in 0.02 seconds on worker 3
9 finished in 0.26 seconds on worker 5
8 finished in 0.57 seconds on worker 4
10 finished in 0.58 seconds on worker 2
0.055971741
```
###
[Remote References and Distributed Garbage Collection](#Remote-References-and-Distributed-Garbage-Collection)
Objects referred to by remote references can be freed only when *all* held references in the cluster are deleted.
The node where the value is stored keeps track of which of the workers have a reference to it. Every time a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) or a (unfetched) [`Future`](../../stdlib/distributed/index#Distributed.Future) is serialized to a worker, the node pointed to by the reference is notified. And every time a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) or a (unfetched) [`Future`](../../stdlib/distributed/index#Distributed.Future) is garbage collected locally, the node owning the value is again notified. This is implemented in an internal cluster aware serializer. Remote references are only valid in the context of a running cluster. Serializing and deserializing references to and from regular `IO` objects is not supported.
The notifications are done via sending of "tracking" messages–an "add reference" message when a reference is serialized to a different process and a "delete reference" message when a reference is locally garbage collected.
Since [`Future`](../../stdlib/distributed/index#Distributed.Future)s are write-once and cached locally, the act of [`fetch`](#)ing a [`Future`](../../stdlib/distributed/index#Distributed.Future) also updates reference tracking information on the node owning the value.
The node which owns the value frees it once all references to it are cleared.
With [`Future`](../../stdlib/distributed/index#Distributed.Future)s, serializing an already fetched [`Future`](../../stdlib/distributed/index#Distributed.Future) to a different node also sends the value since the original remote store may have collected the value by this time.
It is important to note that *when* an object is locally garbage collected depends on the size of the object and the current memory pressure in the system.
In case of remote references, the size of the local reference object is quite small, while the value stored on the remote node may be quite large. Since the local object may not be collected immediately, it is a good practice to explicitly call [`finalize`](../../base/base/index#Base.finalize) on local instances of a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel), or on unfetched [`Future`](../../stdlib/distributed/index#Distributed.Future)s. Since calling [`fetch`](#) on a [`Future`](../../stdlib/distributed/index#Distributed.Future) also removes its reference from the remote store, this is not required on fetched [`Future`](../../stdlib/distributed/index#Distributed.Future)s. Explicitly calling [`finalize`](../../base/base/index#Base.finalize) results in an immediate message sent to the remote node to go ahead and remove its reference to the value.
Once finalized, a reference becomes invalid and cannot be used in any further calls.
[Local invocations](#Local-invocations)
----------------------------------------
Data is necessarily copied over to the remote node for execution. This is the case for both remotecalls and when data is stored to a [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) / [`Future`](../../stdlib/distributed/index#Distributed.Future) on a different node. As expected, this results in a copy of the serialized objects on the remote node. However, when the destination node is the local node, i.e. the calling process id is the same as the remote node id, it is executed as a local call. It is usually (not always) executed in a different task - but there is no serialization/deserialization of data. Consequently, the call refers to the same object instances as passed - no copies are created. This behavior is highlighted below:
```
julia> using Distributed;
julia> rc = RemoteChannel(()->Channel(3)); # RemoteChannel created on local node
julia> v = [0];
julia> for i in 1:3
v[1] = i # Reusing `v`
put!(rc, v)
end;
julia> result = [take!(rc) for _ in 1:3];
julia> println(result);
Array{Int64,1}[[3], [3], [3]]
julia> println("Num Unique objects : ", length(unique(map(objectid, result))));
Num Unique objects : 1
julia> addprocs(1);
julia> rc = RemoteChannel(()->Channel(3), workers()[1]); # RemoteChannel created on remote node
julia> v = [0];
julia> for i in 1:3
v[1] = i
put!(rc, v)
end;
julia> result = [take!(rc) for _ in 1:3];
julia> println(result);
Array{Int64,1}[[1], [2], [3]]
julia> println("Num Unique objects : ", length(unique(map(objectid, result))));
Num Unique objects : 3
```
As can be seen, [`put!`](#) on a locally owned [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel) with the same object `v` modified between calls results in the same single object instance stored. As opposed to copies of `v` being created when the node owning `rc` is a different node.
It is to be noted that this is generally not an issue. It is something to be factored in only if the object is both being stored locally and modified post the call. In such cases it may be appropriate to store a `deepcopy` of the object.
This is also true for remotecalls on the local node as seen in the following example:
```
julia> using Distributed; addprocs(1);
julia> v = [0];
julia> v2 = remotecall_fetch(x->(x[1] = 1; x), myid(), v); # Executed on local node
julia> println("v=$v, v2=$v2, ", v === v2);
v=[1], v2=[1], true
julia> v = [0];
julia> v2 = remotecall_fetch(x->(x[1] = 1; x), workers()[1], v); # Executed on remote node
julia> println("v=$v, v2=$v2, ", v === v2);
v=[0], v2=[1], false
```
As can be seen once again, a remote call onto the local node behaves just like a direct invocation. The call modifies local objects passed as arguments. In the remote invocation, it operates on a copy of the arguments.
To repeat, in general this is not an issue. If the local node is also being used as a compute node, and the arguments used post the call, this behavior needs to be factored in and if required deep copies of arguments must be passed to the call invoked on the local node. Calls on remote nodes will always operate on copies of arguments.
[Shared Arrays](#man-shared-arrays)
------------------------------------
Shared Arrays use system shared memory to map the same array across many processes. While there are some similarities to a [`DArray`](https://github.com/JuliaParallel/DistributedArrays.jl), the behavior of a [`SharedArray`](../../stdlib/sharedarrays/index#SharedArrays.SharedArray) is quite different. In a [`DArray`](https://github.com/JuliaParallel/DistributedArrays.jl), each process has local access to just a chunk of the data, and no two processes share the same chunk; in contrast, in a [`SharedArray`](../../stdlib/sharedarrays/index#SharedArrays.SharedArray) each "participating" process has access to the entire array. A [`SharedArray`](../../stdlib/sharedarrays/index#SharedArrays.SharedArray) is a good choice when you want to have a large amount of data jointly accessible to two or more processes on the same machine.
Shared Array support is available via module `SharedArrays` which must be explicitly loaded on all participating workers.
[`SharedArray`](../../stdlib/sharedarrays/index#SharedArrays.SharedArray) indexing (assignment and accessing values) works just as with regular arrays, and is efficient because the underlying memory is available to the local process. Therefore, most algorithms work naturally on [`SharedArray`](../../stdlib/sharedarrays/index#SharedArrays.SharedArray)s, albeit in single-process mode. In cases where an algorithm insists on an [`Array`](../../base/arrays/index#Core.Array) input, the underlying array can be retrieved from a [`SharedArray`](../../stdlib/sharedarrays/index#SharedArrays.SharedArray) by calling [`sdata`](../../stdlib/sharedarrays/index#SharedArrays.sdata). For other `AbstractArray` types, [`sdata`](../../stdlib/sharedarrays/index#SharedArrays.sdata) just returns the object itself, so it's safe to use [`sdata`](../../stdlib/sharedarrays/index#SharedArrays.sdata) on any `Array`-type object.
The constructor for a shared array is of the form:
```
SharedArray{T,N}(dims::NTuple; init=false, pids=Int[])
```
which creates an `N`-dimensional shared array of a bits type `T` and size `dims` across the processes specified by `pids`. Unlike distributed arrays, a shared array is accessible only from those participating workers specified by the `pids` named argument (and the creating process too, if it is on the same host). Note that only elements that are [`isbits`](../../base/base/index#Base.isbits) are supported in a SharedArray.
If an `init` function, of signature `initfn(S::SharedArray)`, is specified, it is called on all the participating workers. You can specify that each worker runs the `init` function on a distinct portion of the array, thereby parallelizing initialization.
Here's a brief example:
```
julia> using Distributed
julia> addprocs(3)
3-element Array{Int64,1}:
2
3
4
julia> @everywhere using SharedArrays
julia> S = SharedArray{Int,2}((3,4), init = S -> S[localindices(S)] = repeat([myid()], length(localindices(S))))
3×4 SharedArray{Int64,2}:
2 2 3 4
2 3 3 4
2 3 4 4
julia> S[3,2] = 7
7
julia> S
3×4 SharedArray{Int64,2}:
2 2 3 4
2 3 3 4
2 7 4 4
```
[`SharedArrays.localindices`](../../stdlib/sharedarrays/index#SharedArrays.localindices) provides disjoint one-dimensional ranges of indices, and is sometimes convenient for splitting up tasks among processes. You can, of course, divide the work any way you wish:
```
julia> S = SharedArray{Int,2}((3,4), init = S -> S[indexpids(S):length(procs(S)):length(S)] = repeat([myid()], length( indexpids(S):length(procs(S)):length(S))))
3×4 SharedArray{Int64,2}:
2 2 2 2
3 3 3 3
4 4 4 4
```
Since all processes have access to the underlying data, you do have to be careful not to set up conflicts. For example:
```
@sync begin
for p in procs(S)
@async begin
remotecall_wait(fill!, p, S, p)
end
end
end
```
would result in undefined behavior. Because each process fills the *entire* array with its own `pid`, whichever process is the last to execute (for any particular element of `S`) will have its `pid` retained.
As a more extended and complex example, consider running the following "kernel" in parallel:
```
q[i,j,t+1] = q[i,j,t] + u[i,j,t]
```
In this case, if we try to split up the work using a one-dimensional index, we are likely to run into trouble: if `q[i,j,t]` is near the end of the block assigned to one worker and `q[i,j,t+1]` is near the beginning of the block assigned to another, it's very likely that `q[i,j,t]` will not be ready at the time it's needed for computing `q[i,j,t+1]`. In such cases, one is better off chunking the array manually. Let's split along the second dimension. Define a function that returns the `(irange, jrange)` indices assigned to this worker:
```
julia> @everywhere function myrange(q::SharedArray)
idx = indexpids(q)
if idx == 0 # This worker is not assigned a piece
return 1:0, 1:0
end
nchunks = length(procs(q))
splits = [round(Int, s) for s in range(0, stop=size(q,2), length=nchunks+1)]
1:size(q,1), splits[idx]+1:splits[idx+1]
end
```
Next, define the kernel:
```
julia> @everywhere function advection_chunk!(q, u, irange, jrange, trange)
@show (irange, jrange, trange) # display so we can see what's happening
for t in trange, j in jrange, i in irange
q[i,j,t+1] = q[i,j,t] + u[i,j,t]
end
q
end
```
We also define a convenience wrapper for a `SharedArray` implementation
```
julia> @everywhere advection_shared_chunk!(q, u) =
advection_chunk!(q, u, myrange(q)..., 1:size(q,3)-1)
```
Now let's compare three different versions, one that runs in a single process:
```
julia> advection_serial!(q, u) = advection_chunk!(q, u, 1:size(q,1), 1:size(q,2), 1:size(q,3)-1);
```
one that uses [`@distributed`](../../stdlib/distributed/index#Distributed.@distributed):
```
julia> function advection_parallel!(q, u)
for t = 1:size(q,3)-1
@sync @distributed for j = 1:size(q,2)
for i = 1:size(q,1)
q[i,j,t+1]= q[i,j,t] + u[i,j,t]
end
end
end
q
end;
```
and one that delegates in chunks:
```
julia> function advection_shared!(q, u)
@sync begin
for p in procs(q)
@async remotecall_wait(advection_shared_chunk!, p, q, u)
end
end
q
end;
```
If we create `SharedArray`s and time these functions, we get the following results (with `julia -p 4`):
```
julia> q = SharedArray{Float64,3}((500,500,500));
julia> u = SharedArray{Float64,3}((500,500,500));
```
Run the functions once to JIT-compile and [`@time`](../../base/base/index#Base.@time) them on the second run:
```
julia> @time advection_serial!(q, u);
(irange,jrange,trange) = (1:500,1:500,1:499)
830.220 milliseconds (216 allocations: 13820 bytes)
julia> @time advection_parallel!(q, u);
2.495 seconds (3999 k allocations: 289 MB, 2.09% gc time)
julia> @time advection_shared!(q,u);
From worker 2: (irange,jrange,trange) = (1:500,1:125,1:499)
From worker 4: (irange,jrange,trange) = (1:500,251:375,1:499)
From worker 3: (irange,jrange,trange) = (1:500,126:250,1:499)
From worker 5: (irange,jrange,trange) = (1:500,376:500,1:499)
238.119 milliseconds (2264 allocations: 169 KB)
```
The biggest advantage of `advection_shared!` is that it minimizes traffic among the workers, allowing each to compute for an extended time on the assigned piece.
###
[Shared Arrays and Distributed Garbage Collection](#Shared-Arrays-and-Distributed-Garbage-Collection)
Like remote references, shared arrays are also dependent on garbage collection on the creating node to release references from all participating workers. Code which creates many short lived shared array objects would benefit from explicitly finalizing these objects as soon as possible. This results in both memory and file handles mapping the shared segment being released sooner.
[ClusterManagers](#ClusterManagers)
------------------------------------
The launching, management and networking of Julia processes into a logical cluster is done via cluster managers. A `ClusterManager` is responsible for
* launching worker processes in a cluster environment
* managing events during the lifetime of each worker
* optionally, providing data transport
A Julia cluster has the following characteristics:
* The initial Julia process, also called the `master`, is special and has an `id` of 1.
* Only the `master` process can add or remove worker processes.
* All processes can directly communicate with each other.
Connections between workers (using the in-built TCP/IP transport) is established in the following manner:
* [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs) is called on the master process with a `ClusterManager` object.
* [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs) calls the appropriate [`launch`](../../stdlib/distributed/index#Distributed.launch) method which spawns required number of worker processes on appropriate machines.
* Each worker starts listening on a free port and writes out its host and port information to [`stdout`](../../base/io-network/index#Base.stdout).
* The cluster manager captures the [`stdout`](../../base/io-network/index#Base.stdout) of each worker and makes it available to the master process.
* The master process parses this information and sets up TCP/IP connections to each worker.
* Every worker is also notified of other workers in the cluster.
* Each worker connects to all workers whose `id` is less than the worker's own `id`.
* In this way a mesh network is established, wherein every worker is directly connected with every other worker.
While the default transport layer uses plain [`TCPSocket`](../../stdlib/sockets/index#Sockets.TCPSocket), it is possible for a Julia cluster to provide its own transport.
Julia provides two in-built cluster managers:
* `LocalManager`, used when [`addprocs()`](../../stdlib/distributed/index#Distributed.addprocs) or [`addprocs(np::Integer)`](../../stdlib/distributed/index#Distributed.addprocs) are called
* `SSHManager`, used when [`addprocs(hostnames::Array)`](../../stdlib/distributed/index#Distributed.addprocs) is called with a list of hostnames
`LocalManager` is used to launch additional workers on the same host, thereby leveraging multi-core and multi-processor hardware.
Thus, a minimal cluster manager would need to:
* be a subtype of the abstract `ClusterManager`
* implement [`launch`](../../stdlib/distributed/index#Distributed.launch), a method responsible for launching new workers
* implement [`manage`](../../stdlib/distributed/index#Distributed.manage), which is called at various events during a worker's lifetime (for example, sending an interrupt signal)
[`addprocs(manager::FooManager)`](../../stdlib/distributed/index#Distributed.addprocs) requires `FooManager` to implement:
```
function launch(manager::FooManager, params::Dict, launched::Array, c::Condition)
[...]
end
function manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)
[...]
end
```
As an example let us see how the `LocalManager`, the manager responsible for starting workers on the same host, is implemented:
```
struct LocalManager <: ClusterManager
np::Integer
end
function launch(manager::LocalManager, params::Dict, launched::Array, c::Condition)
[...]
end
function manage(manager::LocalManager, id::Integer, config::WorkerConfig, op::Symbol)
[...]
end
```
The [`launch`](../../stdlib/distributed/index#Distributed.launch) method takes the following arguments:
* `manager::ClusterManager`: the cluster manager that [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs) is called with
* `params::Dict`: all the keyword arguments passed to [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs)
* `launched::Array`: the array to append one or more `WorkerConfig` objects to
* `c::Condition`: the condition variable to be notified as and when workers are launched
The [`launch`](../../stdlib/distributed/index#Distributed.launch) method is called asynchronously in a separate task. The termination of this task signals that all requested workers have been launched. Hence the [`launch`](../../stdlib/distributed/index#Distributed.launch) function MUST exit as soon as all the requested workers have been launched.
Newly launched workers are connected to each other and the master process in an all-to-all manner. Specifying the command line argument `--worker[=<cookie>]` results in the launched processes initializing themselves as workers and connections being set up via TCP/IP sockets.
All workers in a cluster share the same [cookie](#man-cluster-cookie) as the master. When the cookie is unspecified, i.e, with the `--worker` option, the worker tries to read it from its standard input. `LocalManager` and `SSHManager` both pass the cookie to newly launched workers via their standard inputs.
By default a worker will listen on a free port at the address returned by a call to [`getipaddr()`](../../stdlib/sockets/index#Sockets.getipaddr). A specific address to listen on may be specified by optional argument `--bind-to bind_addr[:port]`. This is useful for multi-homed hosts.
As an example of a non-TCP/IP transport, an implementation may choose to use MPI, in which case `--worker` must NOT be specified. Instead, newly launched workers should call `init_worker(cookie)` before using any of the parallel constructs.
For every worker launched, the [`launch`](../../stdlib/distributed/index#Distributed.launch) method must add a `WorkerConfig` object (with appropriate fields initialized) to `launched`
```
mutable struct WorkerConfig
# Common fields relevant to all cluster managers
io::Union{IO, Nothing}
host::Union{AbstractString, Nothing}
port::Union{Integer, Nothing}
# Used when launching additional workers at a host
count::Union{Int, Symbol, Nothing}
exename::Union{AbstractString, Cmd, Nothing}
exeflags::Union{Cmd, Nothing}
# External cluster managers can use this to store information at a per-worker level
# Can be a dict if multiple fields need to be stored.
userdata::Any
# SSHManager / SSH tunnel connections to workers
tunnel::Union{Bool, Nothing}
bind_addr::Union{AbstractString, Nothing}
sshflags::Union{Cmd, Nothing}
max_parallel::Union{Integer, Nothing}
# Used by Local/SSH managers
connect_at::Any
[...]
end
```
Most of the fields in `WorkerConfig` are used by the inbuilt managers. Custom cluster managers would typically specify only `io` or `host` / `port`:
* If `io` is specified, it is used to read host/port information. A Julia worker prints out its bind address and port at startup. This allows Julia workers to listen on any free port available instead of requiring worker ports to be configured manually.
* If `io` is not specified, `host` and `port` are used to connect.
* `count`, `exename` and `exeflags` are relevant for launching additional workers from a worker. For example, a cluster manager may launch a single worker per node, and use that to launch additional workers.
+ `count` with an integer value `n` will launch a total of `n` workers.
+ `count` with a value of `:auto` will launch as many workers as the number of CPU threads (logical cores) on that machine.
+ `exename` is the name of the `julia` executable including the full path.
+ `exeflags` should be set to the required command line arguments for new workers.
* `tunnel`, `bind_addr`, `sshflags` and `max_parallel` are used when a ssh tunnel is required to connect to the workers from the master process.
* `userdata` is provided for custom cluster managers to store their own worker-specific information.
`manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)` is called at different times during the worker's lifetime with appropriate `op` values:
* with `:register`/`:deregister` when a worker is added / removed from the Julia worker pool.
* with `:interrupt` when `interrupt(workers)` is called. The `ClusterManager` should signal the appropriate worker with an interrupt signal.
* with `:finalize` for cleanup purposes.
###
[Cluster Managers with Custom Transports](#Cluster-Managers-with-Custom-Transports)
Replacing the default TCP/IP all-to-all socket connections with a custom transport layer is a little more involved. Each Julia process has as many communication tasks as the workers it is connected to. For example, consider a Julia cluster of 32 processes in an all-to-all mesh network:
* Each Julia process thus has 31 communication tasks.
* Each task handles all incoming messages from a single remote worker in a message-processing loop.
* The message-processing loop waits on an `IO` object (for example, a [`TCPSocket`](../../stdlib/sockets/index#Sockets.TCPSocket) in the default implementation), reads an entire message, processes it and waits for the next one.
* Sending messages to a process is done directly from any Julia task–not just communication tasks–again, via the appropriate `IO` object.
Replacing the default transport requires the new implementation to set up connections to remote workers and to provide appropriate `IO` objects that the message-processing loops can wait on. The manager-specific callbacks to be implemented are:
```
connect(manager::FooManager, pid::Integer, config::WorkerConfig)
kill(manager::FooManager, pid::Int, config::WorkerConfig)
```
The default implementation (which uses TCP/IP sockets) is implemented as `connect(manager::ClusterManager, pid::Integer, config::WorkerConfig)`.
`connect` should return a pair of `IO` objects, one for reading data sent from worker `pid`, and the other to write data that needs to be sent to worker `pid`. Custom cluster managers can use an in-memory `BufferStream` as the plumbing to proxy data between the custom, possibly non-`IO` transport and Julia's in-built parallel infrastructure.
A `BufferStream` is an in-memory [`IOBuffer`](../../base/io-network/index#Base.IOBuffer) which behaves like an `IO`–it is a stream which can be handled asynchronously.
The folder `clustermanager/0mq` in the [Examples repository](https://github.com/JuliaAttic/Examples) contains an example of using ZeroMQ to connect Julia workers in a star topology with a 0MQ broker in the middle. Note: The Julia processes are still all *logically* connected to each other–any worker can message any other worker directly without any awareness of 0MQ being used as the transport layer.
When using custom transports:
* Julia workers must NOT be started with `--worker`. Starting with `--worker` will result in the newly launched workers defaulting to the TCP/IP socket transport implementation.
* For every incoming logical connection with a worker, `Base.process_messages(rd::IO, wr::IO)()` must be called. This launches a new task that handles reading and writing of messages from/to the worker represented by the `IO` objects.
* `init_worker(cookie, manager::FooManager)` *must* be called as part of worker process initialization.
* Field `connect_at::Any` in `WorkerConfig` can be set by the cluster manager when [`launch`](../../stdlib/distributed/index#Distributed.launch) is called. The value of this field is passed in all [`connect`](#) callbacks. Typically, it carries information on *how to connect* to a worker. For example, the TCP/IP socket transport uses this field to specify the `(host, port)` tuple at which to connect to a worker.
`kill(manager, pid, config)` is called to remove a worker from the cluster. On the master process, the corresponding `IO` objects must be closed by the implementation to ensure proper cleanup. The default implementation simply executes an `exit()` call on the specified remote worker.
The Examples folder `clustermanager/simple` is an example that shows a simple implementation using UNIX domain sockets for cluster setup.
###
[Network Requirements for LocalManager and SSHManager](#Network-Requirements-for-LocalManager-and-SSHManager)
Julia clusters are designed to be executed on already secured environments on infrastructure such as local laptops, departmental clusters, or even the cloud. This section covers network security requirements for the inbuilt `LocalManager` and `SSHManager`:
* The master process does not listen on any port. It only connects out to the workers.
* Each worker binds to only one of the local interfaces and listens on an ephemeral port number assigned by the OS.
* `LocalManager`, used by `addprocs(N)`, by default binds only to the loopback interface. This means that workers started later on remote hosts (or by anyone with malicious intentions) are unable to connect to the cluster. An `addprocs(4)` followed by an `addprocs(["remote_host"])` will fail. Some users may need to create a cluster comprising their local system and a few remote systems. This can be done by explicitly requesting `LocalManager` to bind to an external network interface via the `restrict` keyword argument: `addprocs(4; restrict=false)`.
* `SSHManager`, used by `addprocs(list_of_remote_hosts)`, launches workers on remote hosts via SSH. By default SSH is only used to launch Julia workers. Subsequent master-worker and worker-worker connections use plain, unencrypted TCP/IP sockets. The remote hosts must have passwordless login enabled. Additional SSH flags or credentials may be specified via keyword argument `sshflags`.
* `addprocs(list_of_remote_hosts; tunnel=true, sshflags=<ssh keys and other flags>)` is useful when we wish to use SSH connections for master-worker too. A typical scenario for this is a local laptop running the Julia REPL (i.e., the master) with the rest of the cluster on the cloud, say on Amazon EC2. In this case only port 22 needs to be opened at the remote cluster coupled with SSH client authenticated via public key infrastructure (PKI). Authentication credentials can be supplied via `sshflags`, for example `sshflags=`-i <keyfile>``.
In an all-to-all topology (the default), all workers connect to each other via plain TCP sockets. The security policy on the cluster nodes must thus ensure free connectivity between workers for the ephemeral port range (varies by OS).
Securing and encrypting all worker-worker traffic (via SSH) or encrypting individual messages can be done via a custom `ClusterManager`.
* If you specify `multiplex=true` as an option to [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs), SSH multiplexing is used to create a tunnel between the master and workers. If you have configured SSH multiplexing on your own and the connection has already been established, SSH multiplexing is used regardless of `multiplex` option. If multiplexing is enabled, forwarding is set by using the existing connection (`-O forward` option in ssh). This is beneficial if your servers require password authentication; you can avoid authentication in Julia by logging in to the server ahead of [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs). The control socket will be located at `~/.ssh/julia-%r@%h:%p` during the session unless the existing multiplexing connection is used. Note that bandwidth may be limited if you create multiple processes on a node and enable multiplexing, because in that case processes share a single multiplexing TCP connection.
###
[Cluster Cookie](#man-cluster-cookie)
All processes in a cluster share the same cookie which, by default, is a randomly generated string on the master process:
* [`cluster_cookie()`](#) returns the cookie, while `cluster_cookie(cookie)()` sets it and returns the new cookie.
* All connections are authenticated on both sides to ensure that only workers started by the master are allowed to connect to each other.
* The cookie may be passed to the workers at startup via argument `--worker=<cookie>`. If argument `--worker` is specified without the cookie, the worker tries to read the cookie from its standard input ([`stdin`](../../base/io-network/index#Base.stdin)). The `stdin` is closed immediately after the cookie is retrieved.
* `ClusterManager`s can retrieve the cookie on the master by calling [`cluster_cookie()`](#). Cluster managers not using the default TCP/IP transport (and hence not specifying `--worker`) must call `init_worker(cookie, manager)` with the same cookie as on the master.
Note that environments requiring higher levels of security can implement this via a custom `ClusterManager`. For example, cookies can be pre-shared and hence not specified as a startup argument.
[Specifying Network Topology (Experimental)](#Specifying-Network-Topology-(Experimental))
------------------------------------------------------------------------------------------
The keyword argument `topology` passed to [`addprocs`](../../stdlib/distributed/index#Distributed.addprocs) is used to specify how the workers must be connected to each other:
* `:all_to_all`, the default: all workers are connected to each other.
* `:master_worker`: only the driver process, i.e. `pid` 1, has connections to the workers.
* `:custom`: the `launch` method of the cluster manager specifies the connection topology via the fields `ident` and `connect_idents` in `WorkerConfig`. A worker with a cluster-manager-provided identity `ident` will connect to all workers specified in `connect_idents`.
Keyword argument `lazy=true|false` only affects `topology` option `:all_to_all`. If `true`, the cluster starts off with the master connected to all workers. Specific worker-worker connections are established at the first remote invocation between two workers. This helps in reducing initial resources allocated for intra-cluster communication. Connections are setup depending on the runtime requirements of a parallel program. Default value for `lazy` is `true`.
Currently, sending a message between unconnected workers results in an error. This behaviour, as with the functionality and interface, should be considered experimental in nature and may change in future releases.
[Noteworthy external packages](#Noteworthy-external-packages)
--------------------------------------------------------------
Outside of Julia parallelism there are plenty of external packages that should be mentioned. For example [MPI.jl](https://github.com/JuliaParallel/MPI.jl) is a Julia wrapper for the `MPI` protocol, [Dagger.jl](https://github.com/JuliaParallel/Dagger.jl) provides functionality similar to Python's [Dask](https://dask.org/), and [DistributedArrays.jl](https://github.com/JuliaParallel/Distributedarrays.jl) provides array operations distributed across workers, as presented in [Shared Arrays](../../stdlib/sharedarrays/index#Shared-Arrays).
A mention must be made of Julia's GPU programming ecosystem, which includes:
1. [CUDA.jl](https://github.com/JuliaGPU/CUDA.jl) wraps the various CUDA libraries and supports compiling Julia kernels for Nvidia GPUs.
2. [oneAPI.jl](https://github.com/JuliaGPU/oneAPI.jl) wraps the oneAPI unified programming model, and supports executing Julia kernels on supported accelerators. Currently only Linux is supported.
3. [AMDGPU.jl](https://github.com/JuliaGPU/AMDGPU.jl) wraps the AMD ROCm libraries and supports compiling Julia kernels for AMD GPUs. Currently only Linux is supported.
4. High-level libraries like [KernelAbstractions.jl](https://github.com/JuliaGPU/KernelAbstractions.jl), [Tullio.jl](https://github.com/mcabbott/Tullio.jl) and [ArrayFire.jl](https://github.com/JuliaComputing/ArrayFire.jl).
In the following example we will use both `DistributedArrays.jl` and `CUDA.jl` to distribute an array across multiple processes by first casting it through `distribute()` and `CuArray()`.
Remember when importing `DistributedArrays.jl` to import it across all processes using [`@everywhere`](../../stdlib/distributed/index#Distributed.@everywhere)
```
$ ./julia -p 4
julia> addprocs()
julia> @everywhere using DistributedArrays
julia> using CUDA
julia> B = ones(10_000) ./ 2;
julia> A = ones(10_000) .* π;
julia> C = 2 .* A ./ B;
julia> all(C .≈ 4*π)
true
julia> typeof(C)
Array{Float64,1}
julia> dB = distribute(B);
julia> dA = distribute(A);
julia> dC = 2 .* dA ./ dB;
julia> all(dC .≈ 4*π)
true
julia> typeof(dC)
DistributedArrays.DArray{Float64,1,Array{Float64,1}}
julia> cuB = CuArray(B);
julia> cuA = CuArray(A);
julia> cuC = 2 .* cuA ./ cuB;
julia> all(cuC .≈ 4*π);
true
julia> typeof(cuC)
CuArray{Float64,1}
```
In the following example we will use both `DistributedArrays.jl` and `CUDA.jl` to distribute an array across multiple processes and call a generic function on it.
```
function power_method(M, v)
for i in 1:100
v = M*v
v /= norm(v)
end
return v, norm(M*v) / norm(v) # or (M*v) ./ v
end
```
`power_method` repeatedly creates a new vector and normalizes it. We have not specified any type signature in function declaration, let's see if it works with the aforementioned datatypes:
```
julia> M = [2. 1; 1 1];
julia> v = rand(2)
2-element Array{Float64,1}:
0.40395
0.445877
julia> power_method(M,v)
([0.850651, 0.525731], 2.618033988749895)
julia> cuM = CuArray(M);
julia> cuv = CuArray(v);
julia> curesult = power_method(cuM, cuv);
julia> typeof(curesult)
CuArray{Float64,1}
julia> dM = distribute(M);
julia> dv = distribute(v);
julia> dC = power_method(dM, dv);
julia> typeof(dC)
Tuple{DistributedArrays.DArray{Float64,1,Array{Float64,1}},Float64}
```
To end this short exposure to external packages, we can consider `MPI.jl`, a Julia wrapper of the MPI protocol. As it would take too long to consider every inner function, it would be better to simply appreciate the approach used to implement the protocol.
Consider this toy script which simply calls each subprocess, instantiate its rank and when the master process is reached, performs the ranks' sum
```
import MPI
MPI.Init()
comm = MPI.COMM_WORLD
MPI.Barrier(comm)
root = 0
r = MPI.Comm_rank(comm)
sr = MPI.Reduce(r, MPI.SUM, root, comm)
if(MPI.Comm_rank(comm) == root)
@printf("sum of ranks: %s\n", sr)
end
MPI.Finalize()
```
```
mpirun -np 4 ./julia example.jl
```
* [1](#citeref-1)In this context, MPI refers to the MPI-1 standard. Beginning with MPI-2, the MPI standards committee introduced a new set of communication mechanisms, collectively referred to as Remote Memory Access (RMA). The motivation for adding rma to the MPI standard was to facilitate one-sided communication patterns. For additional information on the latest MPI standard, see <https://mpi-forum.org/docs>.
| programming_docs |
julia Documentation Documentation
=============
[Accessing Documentation](#Accessing-Documentation)
----------------------------------------------------
Documentation can be accessed at the REPL or in [IJulia](https://github.com/JuliaLang/IJulia.jl) by typing `?` followed by the name of a function or macro, and pressing `Enter`. For example,
```
?cos
?@time
?r""
```
will show documentation for the relevant function, macro or string macro respectively. Most Julia environments provide a way to access documentation directly:
* [VS Code](https://www.julia-vscode.org/) shows documentation when you hover over a function name. You can also use the Julia panel in the sidebar to search for documentation.
* In [Pluto](https://github.com/fonsp/Pluto.jl), open the "Live Docs" panel on the bottom right.
* In [Juno](https://junolab.org) using `Ctrl-J, Ctrl-D` will show the documentation for the object
under the cursor.
[Writing Documentation](#Writing-Documentation)
------------------------------------------------
Julia enables package developers and users to document functions, types and other objects easily via a built-in documentation system.
The basic syntax is simple: any string appearing just before an object (function, macro, type or instance) will be interpreted as documenting it (these are called *docstrings*). Note that no blank lines or comments may intervene between a docstring and the documented object. Here is a basic example:
```
"Tell whether there are too foo items in the array."
foo(xs::Array) = ...
```
Documentation is interpreted as [Markdown](https://en.wikipedia.org/wiki/Markdown), so you can use indentation and code fences to delimit code examples from text. Technically, any object can be associated with any other as metadata; Markdown happens to be the default, but one can construct other string macros and pass them to the `@doc` macro just as well.
Markdown support is implemented in the `Markdown` standard library and for a full list of supported syntax see the [documentation](../../stdlib/markdown/index#markdown_stdlib).
Here is a more complex example, still using Markdown:
```
"""
bar(x[, y])
Compute the Bar index between `x` and `y`.
If `y` is unspecified, compute the Bar index between all pairs of columns of `x`.
# Examples
```julia-repl
julia> bar([1, 2], [1, 2])
1
```
"""
function bar(x, y) ...
```
As in the example above, we recommend following some simple conventions when writing documentation:
1. Always show the signature of a function at the top of the documentation, with a four-space indent so that it is printed as Julia code.
This can be identical to the signature present in the Julia code (like `mean(x::AbstractArray)`), or a simplified form. Optional arguments should be represented with their default values (i.e. `f(x, y=1)`) when possible, following the actual Julia syntax. Optional arguments which do not have a default value should be put in brackets (i.e. `f(x[, y])` and `f(x[, y[, z]])`). An alternative solution is to use several lines: one without optional arguments, the other(s) with them. This solution can also be used to document several related methods of a given function. When a function accepts many keyword arguments, only include a `<keyword arguments>` placeholder in the signature (i.e. `f(x; <keyword arguments>)`), and give the complete list under an `# Arguments` section (see point 4 below).
2. Include a single one-line sentence describing what the function does or what the object represents after the simplified signature block. If needed, provide more details in a second paragraph, after a blank line.
The one-line sentence should use the imperative form ("Do this", "Return that") instead of the third person (do not write "Returns the length...") when documenting functions. It should end with a period. If the meaning of a function cannot be summarized easily, splitting it into separate composable parts could be beneficial (this should not be taken as an absolute requirement for every single case though).
3. Do not repeat yourself.
Since the function name is given by the signature, there is no need to start the documentation with "The function `bar`...": go straight to the point. Similarly, if the signature specifies the types of the arguments, mentioning them in the description is redundant.
4. Only provide an argument list when really necessary.
For simple functions, it is often clearer to mention the role of the arguments directly in the description of the function's purpose. An argument list would only repeat information already provided elsewhere. However, providing an argument list can be a good idea for complex functions with many arguments (in particular keyword arguments). In that case, insert it after the general description of the function, under an `# Arguments` header, with one `-` bullet for each argument. The list should mention the types and default values (if any) of the arguments:
```
"""
...
# Arguments
- `n::Integer`: the number of elements to compute.
- `dim::Integer=1`: the dimensions along which to perform the computation.
...
"""
```
5. Provide hints to related functions.
Sometimes there are functions of related functionality. To increase discoverability please provide a short list of these in a `See also` paragraph.
```
See also [`bar!`](@ref), [`baz`](@ref), [`baaz`](@ref).
```
6. Include any code examples in an `# Examples` section.
Examples should, whenever possible, be written as *doctests*. A *doctest* is a fenced code block (see [Code blocks](../../stdlib/markdown/index#Code-blocks)) starting with ````jldoctest` and contains any number of `julia>` prompts together with inputs and expected outputs that mimic the Julia REPL.
Doctests are enabled by [`Documenter.jl`](https://github.com/JuliaDocs/Documenter.jl). For more detailed documentation see Documenter's [manual](https://juliadocs.github.io/Documenter.jl/).
For example in the following docstring a variable `a` is defined and the expected result, as printed in a Julia REPL, appears afterwards:
```
"""
Some nice documentation here.
# Examples
```jldoctest
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
```
"""
```
Calling `rand` and other RNG-related functions should be avoided in doctests since they will not produce consistent outputs during different Julia sessions. If you would like to show some random number generation related functionality, one option is to explicitly construct and seed your own RNG object (see [`Random`](../../stdlib/random/index#Random-Numbers)) and pass it to the functions you are doctesting.
Operating system word size ([`Int32`](../../base/numbers/index#Core.Int32) or [`Int64`](../../base/numbers/index#Core.Int64)) as well as path separator differences (`/` or `\`) will also affect the reproducibility of some doctests.
Note that whitespace in your doctest is significant! The doctest will fail if you misalign the output of pretty-printing an array, for example.
You can then run `make -C doc doctest=true` to run all the doctests in the Julia Manual and API documentation, which will ensure that your example works.
To indicate that the output result is truncated, you may write `[...]` at the line where checking should stop. This is useful to hide a stacktrace (which contains non-permanent references to lines of julia code) when the doctest shows that an exception is thrown, for example:
```
```jldoctest
julia> div(1, 0)
ERROR: DivideError: integer division error
[...]
```
```
Examples that are untestable should be written within fenced code blocks starting with ````julia` so that they are highlighted correctly in the generated documentation.
Wherever possible examples should be **self-contained** and **runnable** so that readers are able to try them out without having to include any dependencies.
7. Use backticks to identify code and equations.
Julia identifiers and code excerpts should always appear between backticks ``` to enable highlighting. Equations in the LaTeX syntax can be inserted between double backticks ````. Use Unicode characters rather than their LaTeX escape sequence, i.e. ```α = 1``` rather than ```\\alpha = 1```.
8. Place the starting and ending `"""` characters on lines by themselves.
That is, write:
```
"""
...
...
"""
f(x, y) = ...
```
rather than:
```
"""...
..."""
f(x, y) = ...
```
This makes it clearer where docstrings start and end.
9. Respect the line length limit used in the surrounding code.
Docstrings are edited using the same tools as code. Therefore, the same conventions should apply. It is recommended that lines are at most 92 characters wide.
10. Provide information allowing custom types to implement the function in an `# Implementation` section. These implementation details are intended for developers rather than users, explaining e.g. which functions should be overridden and which functions automatically use appropriate fallbacks. Such details are best kept separate from the main description of the function's behavior.
11. For long docstrings, consider splitting the documentation with an `# Extended help` header. The typical help-mode will show only the material above the header; you can access the full help by adding a '?' at the beginning of the expression (i.e., "??foo" rather than "?foo").
[Functions & Methods](#Functions-and-Methods)
----------------------------------------------
Functions in Julia may have multiple implementations, known as methods. While it's good practice for generic functions to have a single purpose, Julia allows methods to be documented individually if necessary. In general, only the most generic method should be documented, or even the function itself (i.e. the object created without any methods by `function bar end`). Specific methods should only be documented if their behaviour differs from the more generic ones. In any case, they should not repeat the information provided elsewhere. For example:
```
"""
*(x, y, z...)
Multiplication operator. `x * y * z *...` calls this function with multiple
arguments, i.e. `*(x, y, z...)`.
"""
function *(x, y, z...)
# ... [implementation sold separately] ...
end
"""
*(x::AbstractString, y::AbstractString, z::AbstractString...)
When applied to strings, concatenates them.
"""
function *(x::AbstractString, y::AbstractString, z::AbstractString...)
# ... [insert secret sauce here] ...
end
help?> *
search: * .*
*(x, y, z...)
Multiplication operator. x * y * z *... calls this function with multiple
arguments, i.e. *(x,y,z...).
*(x::AbstractString, y::AbstractString, z::AbstractString...)
When applied to strings, concatenates them.
```
When retrieving documentation for a generic function, the metadata for each method is concatenated with the `catdoc` function, which can of course be overridden for custom types.
[Advanced Usage](#Advanced-Usage)
----------------------------------
The `@doc` macro associates its first argument with its second in a per-module dictionary called `META`.
To make it easier to write documentation, the parser treats the macro name `@doc` specially: if a call to `@doc` has one argument, but another expression appears after a single line break, then that additional expression is added as an argument to the macro. Therefore the following syntax is parsed as a 2-argument call to `@doc`:
```
@doc raw"""
...
"""
f(x) = x
```
This makes it possible to use expressions other than normal string literals (such as the `raw""` string macro) as a docstring.
When used for retrieving documentation, the `@doc` macro (or equally, the `doc` function) will search all `META` dictionaries for metadata relevant to the given object and return it. The returned object (some Markdown content, for example) will by default display itself intelligently. This design also makes it easy to use the doc system in a programmatic way; for example, to re-use documentation between different versions of a function:
```
@doc "..." foo!
@doc (@doc foo!) foo
```
Or for use with Julia's metaprogramming functionality:
```
for (f, op) in ((:add, :+), (:subtract, :-), (:multiply, :*), (:divide, :/))
@eval begin
$f(a,b) = $op(a,b)
end
end
@doc "`add(a,b)` adds `a` and `b` together" add
@doc "`subtract(a,b)` subtracts `b` from `a`" subtract
```
Documentation written in non-toplevel blocks, such as `begin`, `if`, `for`, and `let`, is added to the documentation system as blocks are evaluated. For example:
```
if condition()
"..."
f(x) = x
end
```
will add documentation to `f(x)` when `condition()` is `true`. Note that even if `f(x)` goes out of scope at the end of the block, its documentation will remain.
It is possible to make use of metaprogramming to assist in the creation of documentation. When using string-interpolation within the docstring you will need to use an extra `$` as shown with `$($name)`:
```
for func in (:day, :dayofmonth)
name = string(func)
@eval begin
@doc """
$($name)(dt::TimeType) -> Int64
The day of month of a `Date` or `DateTime` as an `Int64`.
""" $func(dt::Dates.TimeType)
end
end
```
###
[Dynamic documentation](#Dynamic-documentation)
Sometimes the appropriate documentation for an instance of a type depends on the field values of that instance, rather than just on the type itself. In these cases, you can add a method to `Docs.getdoc` for your custom type that returns the documentation on a per-instance basis. For instance,
```
struct MyType
value::Int
end
Docs.getdoc(t::MyType) = "Documentation for MyType with value $(t.value)"
x = MyType(1)
y = MyType(2)
```
`?x` will display "Documentation for MyType with value 1" while `?y` will display "Documentation for MyType with value 2".
[Syntax Guide](#Syntax-Guide)
------------------------------
This guide provides a comprehensive overview of how to attach documentation to all Julia syntax constructs for which providing documentation is possible.
In the following examples `"..."` is used to illustrate an arbitrary docstring.
###
[`$` and `\` characters](#and-%5C%5C-characters)
The `$` and `\` characters are still parsed as string interpolation or start of an escape sequence in docstrings too. The `raw""` string macro together with the `@doc` macro can be used to avoid having to escape them. This is handy when the docstrings include LaTeX or Julia source code examples containing interpolation:
```
@doc raw"""
```math
\LaTeX
```
"""
function f end
```
###
[Functions and Methods](#Functions-and-Methods-2)
```
"..."
function f end
"..."
f
```
Adds docstring `"..."` to the function `f`. The first version is the preferred syntax, however both are equivalent.
```
"..."
f(x) = x
"..."
function f(x)
x
end
"..."
f(x)
```
Adds docstring `"..."` to the method `f(::Any)`.
```
"..."
f(x, y = 1) = x + y
```
Adds docstring `"..."` to two `Method`s, namely `f(::Any)` and `f(::Any, ::Any)`.
###
[Macros](#Macros)
```
"..."
macro m(x) end
```
Adds docstring `"..."` to the `@m(::Any)` macro definition.
```
"..."
:(@m)
```
Adds docstring `"..."` to the macro named `@m`.
###
[Types](#Types)
```
"..."
abstract type T1 end
"..."
mutable struct T2
...
end
"..."
struct T3
...
end
```
Adds the docstring `"..."` to types `T1`, `T2`, and `T3`.
```
"..."
struct T
"x"
x
"y"
y
end
```
Adds docstring `"..."` to type `T`, `"x"` to field `T.x` and `"y"` to field `T.y`. Also applicable to `mutable struct` types.
###
[Modules](#Modules)
```
"..."
module M end
module M
"..."
M
end
```
Adds docstring `"..."` to the `Module` `M`. Adding the docstring above the `Module` is the preferred syntax, however both are equivalent.
```
"..."
baremodule M
# ...
end
baremodule M
import Base: @doc
"..."
f(x) = x
end
```
Documenting a `baremodule` by placing a docstring above the expression automatically imports `@doc` into the module. These imports must be done manually when the module expression is not documented.
###
[Global Variables](#Global-Variables)
```
"..."
const a = 1
"..."
b = 2
"..."
global c = 3
```
Adds docstring `"..."` to the `Binding`s `a`, `b`, and `c`.
`Binding`s are used to store a reference to a particular `Symbol` in a `Module` without storing the referenced value itself.
When a `const` definition is only used to define an alias of another definition, such as is the case with the function `div` and its alias `÷` in `Base`, do not document the alias and instead document the actual function.
If the alias is documented and not the real definition then the docsystem (`?` mode) will not return the docstring attached to the alias when the real definition is searched for.
For example you should write
```
"..."
f(x) = x + 1
const alias = f
```
rather than
```
f(x) = x + 1
"..."
const alias = f
```
```
"..."
sym
```
Adds docstring `"..."` to the value associated with `sym`. However, it is preferred that `sym` is documented where it is defined.
###
[Multiple Objects](#Multiple-Objects)
```
"..."
a, b
```
Adds docstring `"..."` to `a` and `b` each of which should be a documentable expression. This syntax is equivalent to
```
"..."
a
"..."
b
```
Any number of expressions many be documented together in this way. This syntax can be useful when two functions are related, such as non-mutating and mutating versions `f` and `f!`.
###
[Macro-generated code](#Macro-generated-code)
```
"..."
@m expression
```
Adds docstring `"..."` to the expression generated by expanding `@m expression`. This allows for expressions decorated with `@inline`, `@noinline`, `@generated`, or any other macro to be documented in the same way as undecorated expressions.
Macro authors should take note that only macros that generate a single expression will automatically support docstrings. If a macro returns a block containing multiple subexpressions then the subexpression that should be documented must be marked using the [`@__doc__`](#Core.@__doc__) macro.
The [`@enum`](../../base/base/index#Base.Enums.@enum) macro makes use of `@__doc__` to allow for documenting [`Enum`](../../base/base/index#Base.Enums.Enum)s. Examining its definition should serve as an example of how to use `@__doc__` correctly.
###
`Core.@__doc__`Macro
```
@__doc__(ex)
```
Low-level macro used to mark expressions returned by a macro that should be documented. If more than one expression is marked then the same docstring is applied to each expression.
```
macro example(f)
quote
$(f)() = 0
@__doc__ $(f)(x) = 1
$(f)(x, y) = 2
end |> esc
end
```
`@__doc__` has no effect when a macro that uses it is not documented.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/Docs.jl#L440-L455)
julia Strings Strings
=======
Strings are finite sequences of characters. Of course, the real trouble comes when one asks what a character is. The characters that English speakers are familiar with are the letters `A`, `B`, `C`, etc., together with numerals and common punctuation symbols. These characters are standardized together with a mapping to integer values between 0 and 127 by the [ASCII](https://en.wikipedia.org/wiki/ASCII) standard. There are, of course, many other characters used in non-English languages, including variants of the ASCII characters with accents and other modifications, related scripts such as Cyrillic and Greek, and scripts completely unrelated to ASCII and English, including Arabic, Chinese, Hebrew, Hindi, Japanese, and Korean. The [Unicode](https://en.wikipedia.org/wiki/Unicode) standard tackles the complexities of what exactly a character is, and is generally accepted as the definitive standard addressing this problem. Depending on your needs, you can either ignore these complexities entirely and just pretend that only ASCII characters exist, or you can write code that can handle any of the characters or encodings that one may encounter when handling non-ASCII text. Julia makes dealing with plain ASCII text simple and efficient, and handling Unicode is as simple and efficient as possible. In particular, you can write C-style string code to process ASCII strings, and they will work as expected, both in terms of performance and semantics. If such code encounters non-ASCII text, it will gracefully fail with a clear error message, rather than silently introducing corrupt results. When this happens, modifying the code to handle non-ASCII data is straightforward.
There are a few noteworthy high-level features about Julia's strings:
* The built-in concrete type used for strings (and string literals) in Julia is [`String`](#). This supports the full range of [Unicode](https://en.wikipedia.org/wiki/Unicode) characters via the [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoding. (A [`transcode`](../../base/strings/index#Base.transcode) function is provided to convert to/from other Unicode encodings.)
* All string types are subtypes of the abstract type `AbstractString`, and external packages define additional `AbstractString` subtypes (e.g. for other encodings). If you define a function expecting a string argument, you should declare the type as `AbstractString` in order to accept any string type.
* Like C and Java, but unlike most dynamic languages, Julia has a first-class type for representing a single character, called [`AbstractChar`](../../base/strings/index#Core.AbstractChar). The built-in [`Char`](../../base/strings/index#Core.Char) subtype of `AbstractChar` is a 32-bit primitive type that can represent any Unicode character (and which is based on the UTF-8 encoding).
* As in Java, strings are immutable: the value of an `AbstractString` object cannot be changed. To construct a different string value, you construct a new string from parts of other strings.
* Conceptually, a string is a *partial function* from indices to characters: for some index values, no character value is returned, and instead an exception is thrown. This allows for efficient indexing into strings by the byte index of an encoded representation rather than by a character index, which cannot be implemented both efficiently and simply for variable-width encodings of Unicode strings.
[Characters](#man-characters)
------------------------------
A `Char` value represents a single character: it is just a 32-bit primitive type with a special literal representation and appropriate arithmetic behaviors, and which can be converted to a numeric value representing a [Unicode code point](https://en.wikipedia.org/wiki/Code_point). (Julia packages may define other subtypes of `AbstractChar`, e.g. to optimize operations for other [text encodings](https://en.wikipedia.org/wiki/Character_encoding).) Here is how `Char` values are input and shown:
```
julia> c = 'x'
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
julia> typeof(c)
Char
```
You can easily convert a `Char` to its integer value, i.e. code point:
```
julia> c = Int('x')
120
julia> typeof(c)
Int64
```
On 32-bit architectures, [`typeof(c)`](../../base/base/index#Core.typeof) will be [`Int32`](../../base/numbers/index#Core.Int32). You can convert an integer value back to a `Char` just as easily:
```
julia> Char(120)
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
```
Not all integer values are valid Unicode code points, but for performance, the `Char` conversion does not check that every character value is valid. If you want to check that each converted value is a valid code point, use the [`isvalid`](#) function:
```
julia> Char(0x110000)
'\U110000': Unicode U+110000 (category In: Invalid, too high)
julia> isvalid(Char, 0x110000)
false
```
As of this writing, the valid Unicode code points are `U+0000` through `U+D7FF` and `U+E000` through `U+10FFFF`. These have not all been assigned intelligible meanings yet, nor are they necessarily interpretable by applications, but all of these values are considered to be valid Unicode characters.
You can input any Unicode character in single quotes using `\u` followed by up to four hexadecimal digits or `\U` followed by up to eight hexadecimal digits (the longest valid value only requires six):
```
julia> '\u0'
'\0': ASCII/Unicode U+0000 (category Cc: Other, control)
julia> '\u78'
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
julia> '\u2200'
'∀': Unicode U+2200 (category Sm: Symbol, math)
julia> '\U10ffff'
'\U10ffff': Unicode U+10FFFF (category Cn: Other, not assigned)
```
Julia uses your system's locale and language settings to determine which characters can be printed as-is and which must be output using the generic, escaped `\u` or `\U` input forms. In addition to these Unicode escape forms, all of [C's traditional escaped input forms](https://en.wikipedia.org/wiki/C_syntax#Backslash_escapes) can also be used:
```
julia> Int('\0')
0
julia> Int('\t')
9
julia> Int('\n')
10
julia> Int('\e')
27
julia> Int('\x7f')
127
julia> Int('\177')
127
```
You can do comparisons and a limited amount of arithmetic with `Char` values:
```
julia> 'A' < 'a'
true
julia> 'A' <= 'a' <= 'Z'
false
julia> 'A' <= 'X' <= 'Z'
true
julia> 'x' - 'a'
23
julia> 'A' + 1
'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
```
[String Basics](#String-Basics)
--------------------------------
String literals are delimited by double quotes or triple double quotes:
```
julia> str = "Hello, world.\n"
"Hello, world.\n"
julia> """Contains "quote" characters"""
"Contains \"quote\" characters"
```
Long lines in strings can be broken up by preceding the newline with a backslash (`\`):
```
julia> "This is a long \
line"
"This is a long line"
```
If you want to extract a character from a string, you index into it:
```
julia> str[begin]
'H': ASCII/Unicode U+0048 (category Lu: Letter, uppercase)
julia> str[1]
'H': ASCII/Unicode U+0048 (category Lu: Letter, uppercase)
julia> str[6]
',': ASCII/Unicode U+002C (category Po: Punctuation, other)
julia> str[end]
'\n': ASCII/Unicode U+000A (category Cc: Other, control)
```
Many Julia objects, including strings, can be indexed with integers. The index of the first element (the first character of a string) is returned by [`firstindex(str)`](../../base/collections/index#Base.firstindex), and the index of the last element (character) with [`lastindex(str)`](../../base/collections/index#Base.lastindex). The keywords `begin` and `end` can be used inside an indexing operation as shorthand for the first and last indices, respectively, along the given dimension. String indexing, like most indexing in Julia, is 1-based: `firstindex` always returns `1` for any `AbstractString`. As we will see below, however, `lastindex(str)` is *not* in general the same as `length(str)` for a string, because some Unicode characters can occupy multiple "code units".
You can perform arithmetic and other operations with [`end`](../../base/base/index#end), just like a normal value:
```
julia> str[end-1]
'.': ASCII/Unicode U+002E (category Po: Punctuation, other)
julia> str[end÷2]
' ': ASCII/Unicode U+0020 (category Zs: Separator, space)
```
Using an index less than `begin` (`1`) or greater than `end` raises an error:
```
julia> str[begin-1]
ERROR: BoundsError: attempt to access 14-codeunit String at index [0]
[...]
julia> str[end+1]
ERROR: BoundsError: attempt to access 14-codeunit String at index [15]
[...]
```
You can also extract a substring using range indexing:
```
julia> str[4:9]
"lo, wo"
```
Notice that the expressions `str[k]` and `str[k:k]` do not give the same result:
```
julia> str[6]
',': ASCII/Unicode U+002C (category Po: Punctuation, other)
julia> str[6:6]
","
```
The former is a single character value of type `Char`, while the latter is a string value that happens to contain only a single character. In Julia these are very different things.
Range indexing makes a copy of the selected part of the original string. Alternatively, it is possible to create a view into a string using the type [`SubString`](../../base/strings/index#Base.SubString), for example:
```
julia> str = "long string"
"long string"
julia> substr = SubString(str, 1, 4)
"long"
julia> typeof(substr)
SubString{String}
```
Several standard functions like [`chop`](../../base/strings/index#Base.chop), [`chomp`](../../base/strings/index#Base.chomp) or [`strip`](../../base/strings/index#Base.strip) return a [`SubString`](../../base/strings/index#Base.SubString).
[Unicode and UTF-8](#Unicode-and-UTF-8)
----------------------------------------
Julia fully supports Unicode characters and strings. As [discussed above](#man-characters), in character literals, Unicode code points can be represented using Unicode `\u` and `\U` escape sequences, as well as all the standard C escape sequences. These can likewise be used to write string literals:
```
julia> s = "\u2200 x \u2203 y"
"∀ x ∃ y"
```
Whether these Unicode characters are displayed as escapes or shown as special characters depends on your terminal's locale settings and its support for Unicode. String literals are encoded using the UTF-8 encoding. UTF-8 is a variable-width encoding, meaning that not all characters are encoded in the same number of bytes ("code units"). In UTF-8, ASCII characters — i.e. those with code points less than 0x80 (128) – are encoded as they are in ASCII, using a single byte, while code points 0x80 and above are encoded using multiple bytes — up to four per character.
String indices in Julia refer to code units (= bytes for UTF-8), the fixed-width building blocks that are used to encode arbitrary characters (code points). This means that not every index into a `String` is necessarily a valid index for a character. If you index into a string at such an invalid byte index, an error is thrown:
```
julia> s[1]
'∀': Unicode U+2200 (category Sm: Symbol, math)
julia> s[2]
ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'∀', [4]=>' '
Stacktrace:
[...]
julia> s[3]
ERROR: StringIndexError: invalid index [3], valid nearby indices [1]=>'∀', [4]=>' '
Stacktrace:
[...]
julia> s[4]
' ': ASCII/Unicode U+0020 (category Zs: Separator, space)
```
In this case, the character `∀` is a three-byte character, so the indices 2 and 3 are invalid and the next character's index is 4; this next valid index can be computed by [`nextind(s,1)`](../../base/strings/index#Base.nextind), and the next index after that by `nextind(s,4)` and so on.
Since `end` is always the last valid index into a collection, `end-1` references an invalid byte index if the second-to-last character is multibyte.
```
julia> s[end-1]
' ': ASCII/Unicode U+0020 (category Zs: Separator, space)
julia> s[end-2]
ERROR: StringIndexError: invalid index [9], valid nearby indices [7]=>'∃', [10]=>' '
Stacktrace:
[...]
julia> s[prevind(s, end, 2)]
'∃': Unicode U+2203 (category Sm: Symbol, math)
```
The first case works, because the last character `y` and the space are one-byte characters, whereas `end-2` indexes into the middle of the `∃` multibyte representation. The correct way for this case is using `prevind(s, lastindex(s), 2)` or, if you're using that value to index into `s` you can write `s[prevind(s, end, 2)]` and `end` expands to `lastindex(s)`.
Extraction of a substring using range indexing also expects valid byte indices or an error is thrown:
```
julia> s[1:1]
"∀"
julia> s[1:2]
ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'∀', [4]=>' '
Stacktrace:
[...]
julia> s[1:4]
"∀ "
```
Because of variable-length encodings, the number of characters in a string (given by [`length(s)`](#)) is not always the same as the last index. If you iterate through the indices 1 through [`lastindex(s)`](../../base/collections/index#Base.lastindex) and index into `s`, the sequence of characters returned when errors aren't thrown is the sequence of characters comprising the string `s`. Thus `length(s) <= lastindex(s)`, since each character in a string must have its own index. The following is an inefficient and verbose way to iterate through the characters of `s`:
```
julia> for i = firstindex(s):lastindex(s)
try
println(s[i])
catch
# ignore the index error
end
end
∀
x
∃
y
```
The blank lines actually have spaces on them. Fortunately, the above awkward idiom is unnecessary for iterating through the characters in a string, since you can just use the string as an iterable object, no exception handling required:
```
julia> for c in s
println(c)
end
∀
x
∃
y
```
If you need to obtain valid indices for a string, you can use the [`nextind`](../../base/strings/index#Base.nextind) and [`prevind`](../../base/strings/index#Base.prevind) functions to increment/decrement to the next/previous valid index, as mentioned above. You can also use the [`eachindex`](../../base/arrays/index#Base.eachindex) function to iterate over the valid character indices:
```
julia> collect(eachindex(s))
7-element Vector{Int64}:
1
4
5
6
7
10
11
```
To access the raw code units (bytes for UTF-8) of the encoding, you can use the [`codeunit(s,i)`](../../base/strings/index#Base.codeunit) function, where the index `i` runs consecutively from `1` to [`ncodeunits(s)`](#). The [`codeunits(s)`](../../base/strings/index#Base.codeunits) function returns an `AbstractVector{UInt8}` wrapper that lets you access these raw codeunits (bytes) as an array.
Strings in Julia can contain invalid UTF-8 code unit sequences. This convention allows to treat any byte sequence as a `String`. In such situations a rule is that when parsing a sequence of code units from left to right characters are formed by the longest sequence of 8-bit code units that matches the start of one of the following bit patterns (each `x` can be `0` or `1`):
* `0xxxxxxx`;
* `110xxxxx` `10xxxxxx`;
* `1110xxxx` `10xxxxxx` `10xxxxxx`;
* `11110xxx` `10xxxxxx` `10xxxxxx` `10xxxxxx`;
* `10xxxxxx`;
* `11111xxx`.
In particular this means that overlong and too-high code unit sequences and prefixes thereof are treated as a single invalid character rather than multiple invalid characters. This rule may be best explained with an example:
```
julia> s = "\xc0\xa0\xe2\x88\xe2|"
"\xc0\xa0\xe2\x88\xe2|"
julia> foreach(display, s)
'\xc0\xa0': [overlong] ASCII/Unicode U+0020 (category Zs: Separator, space)
'\xe2\x88': Malformed UTF-8 (category Ma: Malformed, bad data)
'\xe2': Malformed UTF-8 (category Ma: Malformed, bad data)
'|': ASCII/Unicode U+007C (category Sm: Symbol, math)
julia> isvalid.(collect(s))
4-element BitArray{1}:
0
0
0
1
julia> s2 = "\xf7\xbf\xbf\xbf"
"\U1fffff"
julia> foreach(display, s2)
'\U1fffff': Unicode U+1FFFFF (category In: Invalid, too high)
```
We can see that the first two code units in the string `s` form an overlong encoding of space character. It is invalid, but is accepted in a string as a single character. The next two code units form a valid start of a three-byte UTF-8 sequence. However, the fifth code unit `\xe2` is not its valid continuation. Therefore code units 3 and 4 are also interpreted as malformed characters in this string. Similarly code unit 5 forms a malformed character because `|` is not a valid continuation to it. Finally the string `s2` contains one too high code point.
Julia uses the UTF-8 encoding by default, and support for new encodings can be added by packages. For example, the [LegacyStrings.jl](https://github.com/JuliaStrings/LegacyStrings.jl) package implements `UTF16String` and `UTF32String` types. Additional discussion of other encodings and how to implement support for them is beyond the scope of this document for the time being. For further discussion of UTF-8 encoding issues, see the section below on [byte array literals](#man-byte-array-literals). The [`transcode`](../../base/strings/index#Base.transcode) function is provided to convert data between the various UTF-xx encodings, primarily for working with external data and libraries.
[Concatenation](#man-concatenation)
------------------------------------
One of the most common and useful string operations is concatenation:
```
julia> greet = "Hello"
"Hello"
julia> whom = "world"
"world"
julia> string(greet, ", ", whom, ".\n")
"Hello, world.\n"
```
It's important to be aware of potentially dangerous situations such as concatenation of invalid UTF-8 strings. The resulting string may contain different characters than the input strings, and its number of characters may be lower than sum of numbers of characters of the concatenated strings, e.g.:
```
julia> a, b = "\xe2\x88", "\x80"
("\xe2\x88", "\x80")
julia> c = string(a, b)
"∀"
julia> collect.([a, b, c])
3-element Vector{Vector{Char}}:
['\xe2\x88']
['\x80']
['∀']
julia> length.([a, b, c])
3-element Vector{Int64}:
1
1
1
```
This situation can happen only for invalid UTF-8 strings. For valid UTF-8 strings concatenation preserves all characters in strings and additivity of string lengths.
Julia also provides [`*`](#) for string concatenation:
```
julia> greet * ", " * whom * ".\n"
"Hello, world.\n"
```
While `*` may seem like a surprising choice to users of languages that provide `+` for string concatenation, this use of `*` has precedent in mathematics, particularly in abstract algebra.
In mathematics, `+` usually denotes a *commutative* operation, where the order of the operands does not matter. An example of this is matrix addition, where `A + B == B + A` for any matrices `A` and `B` that have the same shape. In contrast, `*` typically denotes a *noncommutative* operation, where the order of the operands *does* matter. An example of this is matrix multiplication, where in general `A * B != B * A`. As with matrix multiplication, string concatenation is noncommutative: `greet * whom != whom * greet`. As such, `*` is a more natural choice for an infix string concatenation operator, consistent with common mathematical use.
More precisely, the set of all finite-length strings *S* together with the string concatenation operator `*` forms a [free monoid](https://en.wikipedia.org/wiki/Free_monoid) (*S*, `*`). The identity element of this set is the empty string, `""`. Whenever a free monoid is not commutative, the operation is typically represented as `\cdot`, `*`, or a similar symbol, rather than `+`, which as stated usually implies commutativity.
[Interpolation](#string-interpolation)
---------------------------------------
Constructing strings using concatenation can become a bit cumbersome, however. To reduce the need for these verbose calls to [`string`](../../base/strings/index#Base.string) or repeated multiplications, Julia allows interpolation into string literals using `$`, as in Perl:
```
julia> "$greet, $whom.\n"
"Hello, world.\n"
```
This is more readable and convenient and equivalent to the above string concatenation – the system rewrites this apparent single string literal into the call `string(greet, ", ", whom, ".\n")`.
The shortest complete expression after the `$` is taken as the expression whose value is to be interpolated into the string. Thus, you can interpolate any expression into a string using parentheses:
```
julia> "1 + 2 = $(1 + 2)"
"1 + 2 = 3"
```
Both concatenation and string interpolation call [`string`](../../base/strings/index#Base.string) to convert objects into string form. However, `string` actually just returns the output of [`print`](../../base/io-network/index#Base.print), so new types should add methods to [`print`](../../base/io-network/index#Base.print) or [`show`](#) instead of `string`.
Most non-`AbstractString` objects are converted to strings closely corresponding to how they are entered as literal expressions:
```
julia> v = [1,2,3]
3-element Vector{Int64}:
1
2
3
julia> "v: $v"
"v: [1, 2, 3]"
```
[`string`](../../base/strings/index#Base.string) is the identity for `AbstractString` and `AbstractChar` values, so these are interpolated into strings as themselves, unquoted and unescaped:
```
julia> c = 'x'
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
julia> "hi, $c"
"hi, x"
```
To include a literal `$` in a string literal, escape it with a backslash:
```
julia> print("I have \$100 in my account.\n")
I have $100 in my account.
```
[Triple-Quoted String Literals](#Triple-Quoted-String-Literals)
----------------------------------------------------------------
When strings are created using triple-quotes (`"""..."""`) they have some special behavior that can be useful for creating longer blocks of text.
First, triple-quoted strings are also dedented to the level of the least-indented line. This is useful for defining strings within code that is indented. For example:
```
julia> str = """
Hello,
world.
"""
" Hello,\n world.\n"
```
In this case the final (empty) line before the closing `"""` sets the indentation level.
The dedentation level is determined as the longest common starting sequence of spaces or tabs in all lines, excluding the line following the opening `"""` and lines containing only spaces or tabs (the line containing the closing `"""` is always included). Then for all lines, excluding the text following the opening `"""`, the common starting sequence is removed (including lines containing only spaces and tabs if they start with this sequence), e.g.:
```
julia> """ This
is
a test"""
" This\nis\n a test"
```
Next, if the opening `"""` is followed by a newline, the newline is stripped from the resulting string.
```
"""hello"""
```
is equivalent to
```
"""
hello"""
```
but
```
"""
hello"""
```
will contain a literal newline at the beginning.
Stripping of the newline is performed after the dedentation. For example:
```
julia> """
Hello,
world."""
"Hello,\nworld."
```
If the newline is removed using a backslash, dedentation will be respected as well:
```
julia> """
Averylong\
word"""
"Averylongword"
```
Trailing whitespace is left unaltered.
Triple-quoted string literals can contain `"` characters without escaping.
Note that line breaks in literal strings, whether single- or triple-quoted, result in a newline (LF) character `\n` in the string, even if your editor uses a carriage return `\r` (CR) or CRLF combination to end lines. To include a CR in a string, use an explicit escape `\r`; for example, you can enter the literal string `"a CRLF line ending\r\n"`.
[Common Operations](#Common-Operations)
----------------------------------------
You can lexicographically compare strings using the standard comparison operators:
```
julia> "abracadabra" < "xylophone"
true
julia> "abracadabra" == "xylophone"
false
julia> "Hello, world." != "Goodbye, world."
true
julia> "1 + 2 = 3" == "1 + 2 = $(1 + 2)"
true
```
You can search for the index of a particular character using the [`findfirst`](#) and [`findlast`](#) functions:
```
julia> findfirst('o', "xylophone")
4
julia> findlast('o', "xylophone")
7
julia> findfirst('z', "xylophone")
```
You can start the search for a character at a given offset by using the functions [`findnext`](#) and [`findprev`](#):
```
julia> findnext('o', "xylophone", 1)
4
julia> findnext('o', "xylophone", 5)
7
julia> findprev('o', "xylophone", 5)
4
julia> findnext('o', "xylophone", 8)
```
You can use the [`occursin`](../../base/strings/index#Base.occursin) function to check if a substring is found within a string:
```
julia> occursin("world", "Hello, world.")
true
julia> occursin("o", "Xylophon")
true
julia> occursin("a", "Xylophon")
false
julia> occursin('o', "Xylophon")
true
```
The last example shows that [`occursin`](../../base/strings/index#Base.occursin) can also look for a character literal.
Two other handy string functions are [`repeat`](../../base/arrays/index#Base.repeat) and [`join`](../../base/strings/index#Base.join):
```
julia> repeat(".:Z:.", 10)
".:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:."
julia> join(["apples", "bananas", "pineapples"], ", ", " and ")
"apples, bananas and pineapples"
```
Some other useful functions include:
* [`firstindex(str)`](../../base/collections/index#Base.firstindex) gives the minimal (byte) index that can be used to index into `str` (always 1 for strings, not necessarily true for other containers).
* [`lastindex(str)`](../../base/collections/index#Base.lastindex) gives the maximal (byte) index that can be used to index into `str`.
* [`length(str)`](#) the number of characters in `str`.
* [`length(str, i, j)`](#) the number of valid character indices in `str` from `i` to `j`.
* [`ncodeunits(str)`](#) number of [code units](https://en.wikipedia.org/wiki/Character_encoding#Terminology) in a string.
* [`codeunit(str, i)`](../../base/strings/index#Base.codeunit) gives the code unit value in the string `str` at index `i`.
* [`thisind(str, i)`](../../base/strings/index#Base.thisind) given an arbitrary index into a string find the first index of the character into which the index points.
* [`nextind(str, i, n=1)`](../../base/strings/index#Base.nextind) find the start of the `n`th character starting after index `i`.
* [`prevind(str, i, n=1)`](../../base/strings/index#Base.prevind) find the start of the `n`th character starting before index `i`.
[Non-Standard String Literals](#non-standard-string-literals)
--------------------------------------------------------------
There are situations when you want to construct a string or use string semantics, but the behavior of the standard string construct is not quite what is needed. For these kinds of situations, Julia provides non-standard string literals. A non-standard string literal looks like a regular double-quoted string literal, but is immediately prefixed by an identifier, and may behave differently from a normal string literal.
[Regular expressions](#man-regex-literals), [byte array literals](#man-byte-array-literals), and [version number literals](#man-version-number-literals), as described below, are some examples of non-standard string literals. Users and packages may also define new non-standard string literals. Further documentation is given in the [Metaprogramming](../metaprogramming/index#meta-non-standard-string-literals) section.
[Regular Expressions](#man-regex-literals)
-------------------------------------------
Julia has Perl-compatible regular expressions (regexes), as provided by the [PCRE](https://www.pcre.org/) library (a description of the syntax can be found [here](https://www.pcre.org/current/doc/html/pcre2syntax.html)). Regular expressions are related to strings in two ways: the obvious connection is that regular expressions are used to find regular patterns in strings; the other connection is that regular expressions are themselves input as strings, which are parsed into a state machine that can be used to efficiently search for patterns in strings. In Julia, regular expressions are input using non-standard string literals prefixed with various identifiers beginning with `r`. The most basic regular expression literal without any options turned on just uses `r"..."`:
```
julia> re = r"^\s*(?:#|$)"
r"^\s*(?:#|$)"
julia> typeof(re)
Regex
```
To check if a regex matches a string, use [`occursin`](../../base/strings/index#Base.occursin):
```
julia> occursin(r"^\s*(?:#|$)", "not a comment")
false
julia> occursin(r"^\s*(?:#|$)", "# a comment")
true
```
As one can see here, [`occursin`](../../base/strings/index#Base.occursin) simply returns true or false, indicating whether a match for the given regex occurs in the string. Commonly, however, one wants to know not just whether a string matched, but also *how* it matched. To capture this information about a match, use the [`match`](../../base/strings/index#Base.match) function instead:
```
julia> match(r"^\s*(?:#|$)", "not a comment")
julia> match(r"^\s*(?:#|$)", "# a comment")
RegexMatch("#")
```
If the regular expression does not match the given string, [`match`](../../base/strings/index#Base.match) returns [`nothing`](../../base/constants/index#Core.nothing) – a special value that does not print anything at the interactive prompt. Other than not printing, it is a completely normal value and you can test for it programmatically:
```
m = match(r"^\s*(?:#|$)", line)
if m === nothing
println("not a comment")
else
println("blank or comment")
end
```
If a regular expression does match, the value returned by [`match`](../../base/strings/index#Base.match) is a [`RegexMatch`](../../base/strings/index#Base.RegexMatch) object. These objects record how the expression matches, including the substring that the pattern matches and any captured substrings, if there are any. This example only captures the portion of the substring that matches, but perhaps we want to capture any non-blank text after the comment character. We could do the following:
```
julia> m = match(r"^\s*(?:#\s*(.*?)\s*$|$)", "# a comment ")
RegexMatch("# a comment ", 1="a comment")
```
When calling [`match`](../../base/strings/index#Base.match), you have the option to specify an index at which to start the search. For example:
```
julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",1)
RegexMatch("1")
julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",6)
RegexMatch("2")
julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",11)
RegexMatch("3")
```
You can extract the following info from a `RegexMatch` object:
* the entire substring matched: `m.match`
* the captured substrings as an array of strings: `m.captures`
* the offset at which the whole match begins: `m.offset`
* the offsets of the captured substrings as a vector: `m.offsets`
For when a capture doesn't match, instead of a substring, `m.captures` contains `nothing` in that position, and `m.offsets` has a zero offset (recall that indices in Julia are 1-based, so a zero offset into a string is invalid). Here is a pair of somewhat contrived examples:
```
julia> m = match(r"(a|b)(c)?(d)", "acd")
RegexMatch("acd", 1="a", 2="c", 3="d")
julia> m.match
"acd"
julia> m.captures
3-element Vector{Union{Nothing, SubString{String}}}:
"a"
"c"
"d"
julia> m.offset
1
julia> m.offsets
3-element Vector{Int64}:
1
2
3
julia> m = match(r"(a|b)(c)?(d)", "ad")
RegexMatch("ad", 1="a", 2=nothing, 3="d")
julia> m.match
"ad"
julia> m.captures
3-element Vector{Union{Nothing, SubString{String}}}:
"a"
nothing
"d"
julia> m.offset
1
julia> m.offsets
3-element Vector{Int64}:
1
0
2
```
It is convenient to have captures returned as an array so that one can use destructuring syntax to bind them to local variables. As a convenience, the `RegexMatch` object implements iterator methods that pass through to the `captures` field, so you can destructure the match object directly:
```
julia> first, second, third = m; first
"a"
```
Captures can also be accessed by indexing the `RegexMatch` object with the number or name of the capture group:
```
julia> m=match(r"(?<hour>\d+):(?<minute>\d+)","12:45")
RegexMatch("12:45", hour="12", minute="45")
julia> m[:minute]
"45"
julia> m[2]
"45"
```
Captures can be referenced in a substitution string when using [`replace`](#) by using `\n` to refer to the nth capture group and prefixing the substitution string with `s`. Capture group 0 refers to the entire match object. Named capture groups can be referenced in the substitution with `\g<groupname>`. For example:
```
julia> replace("first second", r"(\w+) (?<agroup>\w+)" => s"\g<agroup> \1")
"second first"
```
Numbered capture groups can also be referenced as `\g<n>` for disambiguation, as in:
```
julia> replace("a", r"." => s"\g<0>1")
"a1"
```
You can modify the behavior of regular expressions by some combination of the flags `i`, `m`, `s`, and `x` after the closing double quote mark. These flags have the same meaning as they do in Perl, as explained in this excerpt from the [perlre manpage](https://perldoc.perl.org/perlre#Modifiers):
```
i Do case-insensitive pattern matching.
If locale matching rules are in effect, the case map is taken
from the current locale for code points less than 255, and
from Unicode rules for larger code points. However, matches
that would cross the Unicode rules/non-Unicode rules boundary
(ords 255/256) will not succeed.
m Treat string as multiple lines. That is, change "^" and "$"
from matching the start or end of the string to matching the
start or end of any line anywhere within the string.
s Treat string as single line. That is, change "." to match any
character whatsoever, even a newline, which normally it would
not match.
Used together, as r""ms, they let the "." match any character
whatsoever, while still allowing "^" and "$" to match,
respectively, just after and just before newlines within the
string.
x Tells the regular expression parser to ignore most whitespace
that is neither backslashed nor within a character class. You
can use this to break up your regular expression into
(slightly) more readable parts. The '#' character is also
treated as a metacharacter introducing a comment, just as in
ordinary code.
```
For example, the following regex has all three flags turned on:
```
julia> r"a+.*b+.*?d$"ism
r"a+.*b+.*?d$"ims
julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
RegexMatch("angry,\nBad world")
```
The `r"..."` literal is constructed without interpolation and unescaping (except for quotation mark `"` which still has to be escaped). Here is an example showing the difference from standard string literals:
```
julia> x = 10
10
julia> r"$x"
r"$x"
julia> "$x"
"10"
julia> r"\x"
r"\x"
julia> "\x"
ERROR: syntax: invalid escape sequence
```
Triple-quoted regex strings, of the form `r"""..."""`, are also supported (and may be convenient for regular expressions containing quotation marks or newlines).
The `Regex()` constructor may be used to create a valid regex string programmatically. This permits using the contents of string variables and other string operations when constructing the regex string. Any of the regex codes above can be used within the single string argument to `Regex()`. Here are some examples:
```
julia> using Dates
julia> d = Date(1962,7,10)
1962-07-10
julia> regex_d = Regex("Day " * string(day(d)))
r"Day 10"
julia> match(regex_d, "It happened on Day 10")
RegexMatch("Day 10")
julia> name = "Jon"
"Jon"
julia> regex_name = Regex("[\"( ]\\Q$name\\E[\") ]") # interpolate value of name
r"[\"( ]\QJon\E[\") ]"
julia> match(regex_name, " Jon ")
RegexMatch(" Jon ")
julia> match(regex_name, "[Jon]") === nothing
true
```
Note the use of the `\Q...\E` escape sequence. All characters between the `\Q` and the `\E` are interpreted as literal characters (after string interpolation). This escape sequence can be useful when interpolating, possibly malicious, user input.
[Byte Array Literals](#man-byte-array-literals)
------------------------------------------------
Another useful non-standard string literal is the byte-array string literal: `b"..."`. This form lets you use string notation to express read only literal byte arrays – i.e. arrays of [`UInt8`](../../base/numbers/index#Core.UInt8) values. The type of those objects is `CodeUnits{UInt8, String}`. The rules for byte array literals are the following:
* ASCII characters and ASCII escapes produce a single byte.
* `\x` and octal escape sequences produce the *byte* corresponding to the escape value.
* Unicode escape sequences produce a sequence of bytes encoding that code point in UTF-8.
There is some overlap between these rules since the behavior of `\x` and octal escapes less than 0x80 (128) are covered by both of the first two rules, but here these rules agree. Together, these rules allow one to easily use ASCII characters, arbitrary byte values, and UTF-8 sequences to produce arrays of bytes. Here is an example using all three:
```
julia> b"DATA\xff\u2200"
8-element Base.CodeUnits{UInt8, String}:
0x44
0x41
0x54
0x41
0xff
0xe2
0x88
0x80
```
The ASCII string "DATA" corresponds to the bytes 68, 65, 84, 65. `\xff` produces the single byte 255. The Unicode escape `\u2200` is encoded in UTF-8 as the three bytes 226, 136, 128. Note that the resulting byte array does not correspond to a valid UTF-8 string:
```
julia> isvalid("DATA\xff\u2200")
false
```
As it was mentioned `CodeUnits{UInt8, String}` type behaves like read only array of `UInt8` and if you need a standard vector you can convert it using `Vector{UInt8}`:
```
julia> x = b"123"
3-element Base.CodeUnits{UInt8, String}:
0x31
0x32
0x33
julia> x[1]
0x31
julia> x[1] = 0x32
ERROR: CanonicalIndexError: setindex! not defined for Base.CodeUnits{UInt8, String}
[...]
julia> Vector{UInt8}(x)
3-element Vector{UInt8}:
0x31
0x32
0x33
```
Also observe the significant distinction between `\xff` and `\uff`: the former escape sequence encodes the *byte 255*, whereas the latter escape sequence represents the *code point 255*, which is encoded as two bytes in UTF-8:
```
julia> b"\xff"
1-element Base.CodeUnits{UInt8, String}:
0xff
julia> b"\uff"
2-element Base.CodeUnits{UInt8, String}:
0xc3
0xbf
```
Character literals use the same behavior.
For code points less than `\u80`, it happens that the UTF-8 encoding of each code point is just the single byte produced by the corresponding `\x` escape, so the distinction can safely be ignored. For the escapes `\x80` through `\xff` as compared to `\u80` through `\uff`, however, there is a major difference: the former escapes all encode single bytes, which – unless followed by very specific continuation bytes – do not form valid UTF-8 data, whereas the latter escapes all represent Unicode code points with two-byte encodings.
If this is all extremely confusing, try reading ["The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets"](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/). It's an excellent introduction to Unicode and UTF-8, and may help alleviate some confusion regarding the matter.
[Version Number Literals](#man-version-number-literals)
--------------------------------------------------------
Version numbers can easily be expressed with non-standard string literals of the form [`v"..."`](../../base/base/index#Base.@v_str). Version number literals create [`VersionNumber`](../../base/base/index#Base.VersionNumber) objects which follow the specifications of [semantic versioning](https://semver.org/), and therefore are composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations. For example, `v"0.2.1-rc1+win64"` is broken into major version `0`, minor version `2`, patch version `1`, pre-release `rc1` and build `win64`. When entering a version literal, everything except the major version number is optional, therefore e.g. `v"0.2"` is equivalent to `v"0.2.0"` (with empty pre-release/build annotations), `v"2"` is equivalent to `v"2.0.0"`, and so on.
`VersionNumber` objects are mostly useful to easily and correctly compare two (or more) versions. For example, the constant [`VERSION`](../../base/constants/index#Base.VERSION) holds Julia version number as a `VersionNumber` object, and therefore one can define some version-specific behavior using simple statements as:
```
if v"0.2" <= VERSION < v"0.3-"
# do something specific to 0.2 release series
end
```
Note that in the above example the non-standard version number `v"0.3-"` is used, with a trailing `-`: this notation is a Julia extension of the standard, and it's used to indicate a version which is lower than any `0.3` release, including all of its pre-releases. So in the above example the code would only run with stable `0.2` versions, and exclude such versions as `v"0.3.0-rc1"`. In order to also allow for unstable (i.e. pre-release) `0.2` versions, the lower bound check should be modified like this: `v"0.2-" <= VERSION`.
Another non-standard version specification extension allows one to use a trailing `+` to express an upper limit on build versions, e.g. `VERSION > v"0.2-rc1+"` can be used to mean any version above `0.2-rc1` and any of its builds: it will return `false` for version `v"0.2-rc1+win64"` and `true` for `v"0.2-rc2"`.
It is good practice to use such special versions in comparisons (particularly, the trailing `-` should always be used on upper bounds unless there's a good reason not to), but they must not be used as the actual version number of anything, as they are invalid in the semantic versioning scheme.
Besides being used for the [`VERSION`](../../base/constants/index#Base.VERSION) constant, `VersionNumber` objects are widely used in the `Pkg` module, to specify packages versions and their dependencies.
[Raw String Literals](#man-raw-string-literals)
------------------------------------------------
Raw strings without interpolation or unescaping can be expressed with non-standard string literals of the form `raw"..."`. Raw string literals create ordinary `String` objects which contain the enclosed contents exactly as entered with no interpolation or unescaping. This is useful for strings which contain code or markup in other languages which use `$` or `\` as special characters.
The exception is that quotation marks still must be escaped, e.g. `raw"\""` is equivalent to `"\""`. To make it possible to express all strings, backslashes then also must be escaped, but only when appearing right before a quote character:
```
julia> println(raw"\\ \\\"")
\\ \"
```
Notice that the first two backslashes appear verbatim in the output, since they do not precede a quote character. However, the next backslash character escapes the backslash that follows it, and the last backslash escapes a quote, since these backslashes appear before a quote.
| programming_docs |
julia Asynchronous Programming Asynchronous Programming
========================
When a program needs to interact with the outside world, for example communicating with another machine over the internet, operations in the program may need to happen in an unpredictable order. Say your program needs to download a file. We would like to initiate the download operation, perform other operations while we wait for it to complete, and then resume the code that needs the downloaded file when it is available. This sort of scenario falls in the domain of asynchronous programming, sometimes also referred to as concurrent programming (since, conceptually, multiple things are happening at once).
To address these scenarios, Julia provides [`Task`](../../base/parallel/index#Core.Task)s (also known by several other names, such as symmetric coroutines, lightweight threads, cooperative multitasking, or one-shot continuations). When a piece of computing work (in practice, executing a particular function) is designated as a [`Task`](../../base/parallel/index#Core.Task), it becomes possible to interrupt it by switching to another [`Task`](../../base/parallel/index#Core.Task). The original [`Task`](../../base/parallel/index#Core.Task) can later be resumed, at which point it will pick up right where it left off. At first, this may seem similar to a function call. However there are two key differences. First, switching tasks does not use any space, so any number of task switches can occur without consuming the call stack. Second, switching among tasks can occur in any order, unlike function calls, where the called function must finish executing before control returns to the calling function.
[Basic `Task` operations](#Basic-Task-operations)
--------------------------------------------------
You can think of a `Task` as a handle to a unit of computational work to be performed. It has a create-start-run-finish lifecycle. Tasks are created by calling the `Task` constructor on a 0-argument function to run, or using the [`@task`](../../base/parallel/index#Base.@task) macro:
```
julia> t = @task begin; sleep(5); println("done"); end
Task (runnable) @0x00007f13a40c0eb0
```
`@task x` is equivalent to `Task(()->x)`.
This task will wait for five seconds, and then print `done`. However, it has not started running yet. We can run it whenever we're ready by calling [`schedule`](../../base/parallel/index#Base.schedule):
```
julia> schedule(t);
```
If you try this in the REPL, you will see that `schedule` returns immediately. That is because it simply adds `t` to an internal queue of tasks to run. Then, the REPL will print the next prompt and wait for more input. Waiting for keyboard input provides an opportunity for other tasks to run, so at that point `t` will start. `t` calls [`sleep`](../../base/parallel/index#Base.sleep), which sets a timer and stops execution. If other tasks have been scheduled, they could run then. After five seconds, the timer fires and restarts `t`, and you will see `done` printed. `t` is then finished.
The [`wait`](../../base/parallel/index#Base.wait) function blocks the calling task until some other task finishes. So for example if you type
```
julia> schedule(t); wait(t)
```
instead of only calling `schedule`, you will see a five second pause before the next input prompt appears. That is because the REPL is waiting for `t` to finish before proceeding.
It is common to want to create a task and schedule it right away, so the macro [`@async`](../../base/parallel/index#Base.@async) is provided for that purpose –- `@async x` is equivalent to `schedule(@task x)`.
[Communicating with Channels](#Communicating-with-Channels)
------------------------------------------------------------
In some problems, the various pieces of required work are not naturally related by function calls; there is no obvious "caller" or "callee" among the jobs that need to be done. An example is the producer-consumer problem, where one complex procedure is generating values and another complex procedure is consuming them. The consumer cannot simply call a producer function to get a value, because the producer may have more values to generate and so might not yet be ready to return. With tasks, the producer and consumer can both run as long as they need to, passing values back and forth as necessary.
Julia provides a [`Channel`](../../base/parallel/index#Base.Channel) mechanism for solving this problem. A [`Channel`](../../base/parallel/index#Base.Channel) is a waitable first-in first-out queue which can have multiple tasks reading from and writing to it.
Let's define a producer task, which produces values via the [`put!`](#) call. To consume values, we need to schedule the producer to run in a new task. A special [`Channel`](../../base/parallel/index#Base.Channel) constructor which accepts a 1-arg function as an argument can be used to run a task bound to a channel. We can then [`take!`](#) values repeatedly from the channel object:
```
julia> function producer(c::Channel)
put!(c, "start")
for n=1:4
put!(c, 2n)
end
put!(c, "stop")
end;
julia> chnl = Channel(producer);
julia> take!(chnl)
"start"
julia> take!(chnl)
2
julia> take!(chnl)
4
julia> take!(chnl)
6
julia> take!(chnl)
8
julia> take!(chnl)
"stop"
```
One way to think of this behavior is that `producer` was able to return multiple times. Between calls to [`put!`](#), the producer's execution is suspended and the consumer has control.
The returned [`Channel`](../../base/parallel/index#Base.Channel) can be used as an iterable object in a `for` loop, in which case the loop variable takes on all the produced values. The loop is terminated when the channel is closed.
```
julia> for x in Channel(producer)
println(x)
end
start
2
4
6
8
stop
```
Note that we did not have to explicitly close the channel in the producer. This is because the act of binding a [`Channel`](../../base/parallel/index#Base.Channel) to a [`Task`](../../base/parallel/index#Core.Task) associates the open lifetime of a channel with that of the bound task. The channel object is closed automatically when the task terminates. Multiple channels can be bound to a task, and vice-versa.
While the [`Task`](../../base/parallel/index#Core.Task) constructor expects a 0-argument function, the [`Channel`](../../base/parallel/index#Base.Channel) method that creates a task-bound channel expects a function that accepts a single argument of type [`Channel`](../../base/parallel/index#Base.Channel). A common pattern is for the producer to be parameterized, in which case a partial function application is needed to create a 0 or 1 argument [anonymous function](../functions/index#man-anonymous-functions).
For [`Task`](../../base/parallel/index#Core.Task) objects this can be done either directly or by use of a convenience macro:
```
function mytask(myarg)
...
end
taskHdl = Task(() -> mytask(7))
# or, equivalently
taskHdl = @task mytask(7)
```
To orchestrate more advanced work distribution patterns, [`bind`](../../stdlib/sockets/index#Base.bind) and [`schedule`](../../base/parallel/index#Base.schedule) can be used in conjunction with [`Task`](../../base/parallel/index#Core.Task) and [`Channel`](../../base/parallel/index#Base.Channel) constructors to explicitly link a set of channels with a set of producer/consumer tasks.
###
[More on Channels](#More-on-Channels)
A channel can be visualized as a pipe, i.e., it has a write end and a read end :
* Multiple writers in different tasks can write to the same channel concurrently via [`put!`](#) calls.
* Multiple readers in different tasks can read data concurrently via [`take!`](#) calls.
* As an example:
```
# Given Channels c1 and c2,
c1 = Channel(32)
c2 = Channel(32)
# and a function `foo` which reads items from c1, processes the item read
# and writes a result to c2,
function foo()
while true
data = take!(c1)
[...] # process data
put!(c2, result) # write out result
end
end
# we can schedule `n` instances of `foo` to be active concurrently.
for _ in 1:n
errormonitor(@async foo())
end
```
* Channels are created via the `Channel{T}(sz)` constructor. The channel will only hold objects of type `T`. If the type is not specified, the channel can hold objects of any type. `sz` refers to the maximum number of elements that can be held in the channel at any time. For example, `Channel(32)` creates a channel that can hold a maximum of 32 objects of any type. A `Channel{MyType}(64)` can hold up to 64 objects of `MyType` at any time.
* If a [`Channel`](../../base/parallel/index#Base.Channel) is empty, readers (on a [`take!`](#) call) will block until data is available.
* If a [`Channel`](../../base/parallel/index#Base.Channel) is full, writers (on a [`put!`](#) call) will block until space becomes available.
* [`isready`](#) tests for the presence of any object in the channel, while [`wait`](../../base/parallel/index#Base.wait) waits for an object to become available.
* A [`Channel`](../../base/parallel/index#Base.Channel) is in an open state initially. This means that it can be read from and written to freely via [`take!`](#) and [`put!`](#) calls. [`close`](../../base/io-network/index#Base.close) closes a [`Channel`](../../base/parallel/index#Base.Channel). On a closed [`Channel`](../../base/parallel/index#Base.Channel), [`put!`](#) will fail. For example:
```
julia> c = Channel(2);
julia> put!(c, 1) # `put!` on an open channel succeeds
1
julia> close(c);
julia> put!(c, 2) # `put!` on a closed channel throws an exception.
ERROR: InvalidStateException: Channel is closed.
Stacktrace:
[...]
```
* [`take!`](#) and [`fetch`](#) (which retrieves but does not remove the value) on a closed channel successfully return any existing values until it is emptied. Continuing the above example:
```
julia> fetch(c) # Any number of `fetch` calls succeed.
1
julia> fetch(c)
1
julia> take!(c) # The first `take!` removes the value.
1
julia> take!(c) # No more data available on a closed channel.
ERROR: InvalidStateException: Channel is closed.
Stacktrace:
[...]
```
Consider a simple example using channels for inter-task communication. We start 4 tasks to process data from a single `jobs` channel. Jobs, identified by an id (`job_id`), are written to the channel. Each task in this simulation reads a `job_id`, waits for a random amount of time and writes back a tuple of `job_id` and the simulated time to the results channel. Finally all the `results` are printed out.
```
julia> const jobs = Channel{Int}(32);
julia> const results = Channel{Tuple}(32);
julia> function do_work()
for job_id in jobs
exec_time = rand()
sleep(exec_time) # simulates elapsed time doing actual work
# typically performed externally.
put!(results, (job_id, exec_time))
end
end;
julia> function make_jobs(n)
for i in 1:n
put!(jobs, i)
end
end;
julia> n = 12;
julia> errormonitor(@async make_jobs(n)); # feed the jobs channel with "n" jobs
julia> for i in 1:4 # start 4 tasks to process requests in parallel
errormonitor(@async do_work())
end
julia> @elapsed while n > 0 # print out results
job_id, exec_time = take!(results)
println("$job_id finished in $(round(exec_time; digits=2)) seconds")
global n = n - 1
end
4 finished in 0.22 seconds
3 finished in 0.45 seconds
1 finished in 0.5 seconds
7 finished in 0.14 seconds
2 finished in 0.78 seconds
5 finished in 0.9 seconds
9 finished in 0.36 seconds
6 finished in 0.87 seconds
8 finished in 0.79 seconds
10 finished in 0.64 seconds
12 finished in 0.5 seconds
11 finished in 0.97 seconds
0.029772311
```
Instead of `errormonitor(t)`, a more robust solution may be use use `bind(results, t)`, as that will not only log any unexpected failures, but also force the associated resources to close and propagate the exception everywhere.
[More task operations](#More-task-operations)
----------------------------------------------
Task operations are built on a low-level primitive called [`yieldto`](../../base/parallel/index#Base.yieldto). `yieldto(task, value)` suspends the current task, switches to the specified `task`, and causes that task's last [`yieldto`](../../base/parallel/index#Base.yieldto) call to return the specified `value`. Notice that [`yieldto`](../../base/parallel/index#Base.yieldto) is the only operation required to use task-style control flow; instead of calling and returning we are always just switching to a different task. This is why this feature is also called "symmetric coroutines"; each task is switched to and from using the same mechanism.
[`yieldto`](../../base/parallel/index#Base.yieldto) is powerful, but most uses of tasks do not invoke it directly. Consider why this might be. If you switch away from the current task, you will probably want to switch back to it at some point, but knowing when to switch back, and knowing which task has the responsibility of switching back, can require considerable coordination. For example, [`put!`](#) and [`take!`](#) are blocking operations, which, when used in the context of channels maintain state to remember who the consumers are. Not needing to manually keep track of the consuming task is what makes [`put!`](#) easier to use than the low-level [`yieldto`](../../base/parallel/index#Base.yieldto).
In addition to [`yieldto`](../../base/parallel/index#Base.yieldto), a few other basic functions are needed to use tasks effectively.
* [`current_task`](../../base/parallel/index#Base.current_task) gets a reference to the currently-running task.
* [`istaskdone`](../../base/parallel/index#Base.istaskdone) queries whether a task has exited.
* [`istaskstarted`](../../base/parallel/index#Base.istaskstarted) queries whether a task has run yet.
* [`task_local_storage`](#) manipulates a key-value store specific to the current task.
[Tasks and events](#Tasks-and-events)
--------------------------------------
Most task switches occur as a result of waiting for events such as I/O requests, and are performed by a scheduler included in Julia Base. The scheduler maintains a queue of runnable tasks, and executes an event loop that restarts tasks based on external events such as message arrival.
The basic function for waiting for an event is [`wait`](../../base/parallel/index#Base.wait). Several objects implement [`wait`](../../base/parallel/index#Base.wait); for example, given a `Process` object, [`wait`](../../base/parallel/index#Base.wait) will wait for it to exit. [`wait`](../../base/parallel/index#Base.wait) is often implicit; for example, a [`wait`](../../base/parallel/index#Base.wait) can happen inside a call to [`read`](../../base/io-network/index#Base.read) to wait for data to be available.
In all of these cases, [`wait`](../../base/parallel/index#Base.wait) ultimately operates on a [`Condition`](../../base/parallel/index#Base.Condition) object, which is in charge of queueing and restarting tasks. When a task calls [`wait`](../../base/parallel/index#Base.wait) on a [`Condition`](../../base/parallel/index#Base.Condition), the task is marked as non-runnable, added to the condition's queue, and switches to the scheduler. The scheduler will then pick another task to run, or block waiting for external events. If all goes well, eventually an event handler will call [`notify`](../../base/parallel/index#Base.notify) on the condition, which causes tasks waiting for that condition to become runnable again.
A task created explicitly by calling [`Task`](../../base/parallel/index#Core.Task) is initially not known to the scheduler. This allows you to manage tasks manually using [`yieldto`](../../base/parallel/index#Base.yieldto) if you wish. However, when such a task waits for an event, it still gets restarted automatically when the event happens, as you would expect.
julia Types Types
=====
Type systems have traditionally fallen into two quite different camps: static type systems, where every program expression must have a type computable before the execution of the program, and dynamic type systems, where nothing is known about types until run time, when the actual values manipulated by the program are available. Object orientation allows some flexibility in statically typed languages by letting code be written without the precise types of values being known at compile time. The ability to write code that can operate on different types is called polymorphism. All code in classic dynamically typed languages is polymorphic: only by explicitly checking types, or when objects fail to support operations at run-time, are the types of any values ever restricted.
Julia's type system is dynamic, but gains some of the advantages of static type systems by making it possible to indicate that certain values are of specific types. This can be of great assistance in generating efficient code, but even more significantly, it allows method dispatch on the types of function arguments to be deeply integrated with the language. Method dispatch is explored in detail in [Methods](../methods/index#Methods), but is rooted in the type system presented here.
The default behavior in Julia when types are omitted is to allow values to be of any type. Thus, one can write many useful Julia functions without ever explicitly using types. When additional expressiveness is needed, however, it is easy to gradually introduce explicit type annotations into previously "untyped" code. Adding annotations serves three primary purposes: to take advantage of Julia's powerful multiple-dispatch mechanism, to improve human readability, and to catch programmer errors.
Describing Julia in the lingo of [type systems](https://en.wikipedia.org/wiki/Type_system), it is: dynamic, nominative and parametric. Generic types can be parameterized, and the hierarchical relationships between types are [explicitly declared](https://en.wikipedia.org/wiki/Nominal_type_system), rather than [implied by compatible structure](https://en.wikipedia.org/wiki/Structural_type_system). One particularly distinctive feature of Julia's type system is that concrete types may not subtype each other: all concrete types are final and may only have abstract types as their supertypes. While this might at first seem unduly restrictive, it has many beneficial consequences with surprisingly few drawbacks. It turns out that being able to inherit behavior is much more important than being able to inherit structure, and inheriting both causes significant difficulties in traditional object-oriented languages. Other high-level aspects of Julia's type system that should be mentioned up front are:
* There is no division between object and non-object values: all values in Julia are true objects having a type that belongs to a single, fully connected type graph, all nodes of which are equally first-class as types.
* There is no meaningful concept of a "compile-time type": the only type a value has is its actual type when the program is running. This is called a "run-time type" in object-oriented languages where the combination of static compilation with polymorphism makes this distinction significant.
* Only values, not variables, have types – variables are simply names bound to values, although for simplicity we may say "type of a variable" as shorthand for "type of the value to which a variable refers".
* Both abstract and concrete types can be parameterized by other types. They can also be parameterized by symbols, by values of any type for which [`isbits`](../../base/base/index#Base.isbits) returns true (essentially, things like numbers and bools that are stored like C types or `struct`s with no pointers to other objects), and also by tuples thereof. Type parameters may be omitted when they do not need to be referenced or restricted.
Julia's type system is designed to be powerful and expressive, yet clear, intuitive and unobtrusive. Many Julia programmers may never feel the need to write code that explicitly uses types. Some kinds of programming, however, become clearer, simpler, faster and more robust with declared types.
[Type Declarations](#Type-Declarations)
----------------------------------------
The `::` operator can be used to attach type annotations to expressions and variables in programs. There are two primary reasons to do this:
1. As an assertion to help confirm that your program works the way you expect,
2. To provide extra type information to the compiler, which can then improve performance in some cases
When appended to an expression computing a value, the `::` operator is read as "is an instance of". It can be used anywhere to assert that the value of the expression on the left is an instance of the type on the right. When the type on the right is concrete, the value on the left must have that type as its implementation – recall that all concrete types are final, so no implementation is a subtype of any other. When the type is abstract, it suffices for the value to be implemented by a concrete type that is a subtype of the abstract type. If the type assertion is not true, an exception is thrown, otherwise, the left-hand value is returned:
```
julia> (1+2)::AbstractFloat
ERROR: TypeError: in typeassert, expected AbstractFloat, got a value of type Int64
julia> (1+2)::Int
3
```
This allows a type assertion to be attached to any expression in-place.
When appended to a variable on the left-hand side of an assignment, or as part of a `local` declaration, the `::` operator means something a bit different: it declares the variable to always have the specified type, like a type declaration in a statically-typed language such as C. Every value assigned to the variable will be converted to the declared type using [`convert`](../../base/base/index#Base.convert):
```
julia> function foo()
x::Int8 = 100
x
end
foo (generic function with 1 method)
julia> x = foo()
100
julia> typeof(x)
Int8
```
This feature is useful for avoiding performance "gotchas" that could occur if one of the assignments to a variable changed its type unexpectedly.
This "declaration" behavior only occurs in specific contexts:
```
local x::Int8 # in a local declaration
x::Int8 = 10 # as the left-hand side of an assignment
```
and applies to the whole current scope, even before the declaration. Currently, type declarations cannot be used in global scope, e.g. in the REPL, since Julia does not yet have constant-type globals.
Declarations can also be attached to function definitions:
```
function sinc(x)::Float64
if x == 0
return 1
end
return sin(pi*x)/(pi*x)
end
```
Returning from this function behaves just like an assignment to a variable with a declared type: the value is always converted to `Float64`.
[Abstract Types](#man-abstract-types)
--------------------------------------
Abstract types cannot be instantiated, and serve only as nodes in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. We begin with abstract types even though they have no instantiation because they are the backbone of the type system: they form the conceptual hierarchy which makes Julia's type system more than just a collection of object implementations.
Recall that in [Integers and Floating-Point Numbers](../integers-and-floating-point-numbers/index#Integers-and-Floating-Point-Numbers), we introduced a variety of concrete types of numeric values: [`Int8`](../../base/numbers/index#Core.Int8), [`UInt8`](../../base/numbers/index#Core.UInt8), [`Int16`](../../base/numbers/index#Core.Int16), [`UInt16`](../../base/numbers/index#Core.UInt16), [`Int32`](../../base/numbers/index#Core.Int32), [`UInt32`](../../base/numbers/index#Core.UInt32), [`Int64`](../../base/numbers/index#Core.Int64), [`UInt64`](../../base/numbers/index#Core.UInt64), [`Int128`](../../base/numbers/index#Core.Int128), [`UInt128`](../../base/numbers/index#Core.UInt128), [`Float16`](../../base/numbers/index#Core.Float16), [`Float32`](../../base/numbers/index#Core.Float32), and [`Float64`](../../base/numbers/index#Core.Float64). Although they have different representation sizes, `Int8`, `Int16`, `Int32`, `Int64` and `Int128` all have in common that they are signed integer types. Likewise `UInt8`, `UInt16`, `UInt32`, `UInt64` and `UInt128` are all unsigned integer types, while `Float16`, `Float32` and `Float64` are distinct in being floating-point types rather than integers. It is common for a piece of code to make sense, for example, only if its arguments are some kind of integer, but not really depend on what particular *kind* of integer. For example, the greatest common denominator algorithm works for all kinds of integers, but will not work for floating-point numbers. Abstract types allow the construction of a hierarchy of types, providing a context into which concrete types can fit. This allows you, for example, to easily program to any type that is an integer, without restricting an algorithm to a specific type of integer.
Abstract types are declared using the [`abstract type`](../../base/base/index#abstract%20type) keyword. The general syntaxes for declaring an abstract type are:
```
abstract type «name» end
abstract type «name» <: «supertype» end
```
The `abstract type` keyword introduces a new abstract type, whose name is given by `«name»`. This name can be optionally followed by [`<:`](#) and an already-existing type, indicating that the newly declared abstract type is a subtype of this "parent" type.
When no supertype is given, the default supertype is `Any` – a predefined abstract type that all objects are instances of and all types are subtypes of. In type theory, `Any` is commonly called "top" because it is at the apex of the type graph. Julia also has a predefined abstract "bottom" type, at the nadir of the type graph, which is written as `Union{}`. It is the exact opposite of `Any`: no object is an instance of `Union{}` and all types are supertypes of `Union{}`.
Let's consider some of the abstract types that make up Julia's numerical hierarchy:
```
abstract type Number end
abstract type Real <: Number end
abstract type AbstractFloat <: Real end
abstract type Integer <: Real end
abstract type Signed <: Integer end
abstract type Unsigned <: Integer end
```
The [`Number`](../../base/numbers/index#Core.Number) type is a direct child type of `Any`, and [`Real`](../../base/numbers/index#Core.Real) is its child. In turn, `Real` has two children (it has more, but only two are shown here; we'll get to the others later): [`Integer`](../../base/numbers/index#Core.Integer) and [`AbstractFloat`](../../base/numbers/index#Core.AbstractFloat), separating the world into representations of integers and representations of real numbers. Representations of real numbers include, of course, floating-point types, but also include other types, such as rationals. Hence, `AbstractFloat` is a proper subtype of `Real`, including only floating-point representations of real numbers. Integers are further subdivided into [`Signed`](../../base/numbers/index#Core.Signed) and [`Unsigned`](../../base/numbers/index#Core.Unsigned) varieties.
The `<:` operator in general means "is a subtype of", and, used in declarations like this, declares the right-hand type to be an immediate supertype of the newly declared type. It can also be used in expressions as a subtype operator which returns `true` when its left operand is a subtype of its right operand:
```
julia> Integer <: Number
true
julia> Integer <: AbstractFloat
false
```
An important use of abstract types is to provide default implementations for concrete types. To give a simple example, consider:
```
function myplus(x,y)
x+y
end
```
The first thing to note is that the above argument declarations are equivalent to `x::Any` and `y::Any`. When this function is invoked, say as `myplus(2,5)`, the dispatcher chooses the most specific method named `myplus` that matches the given arguments. (See [Methods](../methods/index#Methods) for more information on multiple dispatch.)
Assuming no method more specific than the above is found, Julia next internally defines and compiles a method called `myplus` specifically for two `Int` arguments based on the generic function given above, i.e., it implicitly defines and compiles:
```
function myplus(x::Int,y::Int)
x+y
end
```
and finally, it invokes this specific method.
Thus, abstract types allow programmers to write generic functions that can later be used as the default method by many combinations of concrete types. Thanks to multiple dispatch, the programmer has full control over whether the default or more specific method is used.
An important point to note is that there is no loss in performance if the programmer relies on a function whose arguments are abstract types, because it is recompiled for each tuple of argument concrete types with which it is invoked. (There may be a performance issue, however, in the case of function arguments that are containers of abstract types; see [Performance Tips](../performance-tips/index#man-performance-abstract-container).)
[Primitive Types](#Primitive-Types)
------------------------------------
It is almost always preferable to wrap an existing primitive type in a new composite type than to define your own primitive type.
This functionality exists to allow Julia to bootstrap the standard primitive types that LLVM supports. Once they are defined, there is very little reason to define more.
A primitive type is a concrete type whose data consists of plain old bits. Classic examples of primitive types are integers and floating-point values. Unlike most languages, Julia lets you declare your own primitive types, rather than providing only a fixed set of built-in ones. In fact, the standard primitive types are all defined in the language itself:
```
primitive type Float16 <: AbstractFloat 16 end
primitive type Float32 <: AbstractFloat 32 end
primitive type Float64 <: AbstractFloat 64 end
primitive type Bool <: Integer 8 end
primitive type Char <: AbstractChar 32 end
primitive type Int8 <: Signed 8 end
primitive type UInt8 <: Unsigned 8 end
primitive type Int16 <: Signed 16 end
primitive type UInt16 <: Unsigned 16 end
primitive type Int32 <: Signed 32 end
primitive type UInt32 <: Unsigned 32 end
primitive type Int64 <: Signed 64 end
primitive type UInt64 <: Unsigned 64 end
primitive type Int128 <: Signed 128 end
primitive type UInt128 <: Unsigned 128 end
```
The general syntaxes for declaring a primitive type are:
```
primitive type «name» «bits» end
primitive type «name» <: «supertype» «bits» end
```
The number of bits indicates how much storage the type requires and the name gives the new type a name. A primitive type can optionally be declared to be a subtype of some supertype. If a supertype is omitted, then the type defaults to having `Any` as its immediate supertype. The declaration of [`Bool`](../../base/numbers/index#Core.Bool) above therefore means that a boolean value takes eight bits to store, and has [`Integer`](../../base/numbers/index#Core.Integer) as its immediate supertype. Currently, only sizes that are multiples of 8 bits are supported and you are likely to experience LLVM bugs with sizes other than those used above. Therefore, boolean values, although they really need just a single bit, cannot be declared to be any smaller than eight bits.
The types [`Bool`](../../base/numbers/index#Core.Bool), [`Int8`](../../base/numbers/index#Core.Int8) and [`UInt8`](../../base/numbers/index#Core.UInt8) all have identical representations: they are eight-bit chunks of memory. Since Julia's type system is nominative, however, they are not interchangeable despite having identical structure. A fundamental difference between them is that they have different supertypes: [`Bool`](../../base/numbers/index#Core.Bool)'s direct supertype is [`Integer`](../../base/numbers/index#Core.Integer), [`Int8`](../../base/numbers/index#Core.Int8)'s is [`Signed`](../../base/numbers/index#Core.Signed), and [`UInt8`](../../base/numbers/index#Core.UInt8)'s is [`Unsigned`](../../base/numbers/index#Core.Unsigned). All other differences between [`Bool`](../../base/numbers/index#Core.Bool), [`Int8`](../../base/numbers/index#Core.Int8), and [`UInt8`](../../base/numbers/index#Core.UInt8) are matters of behavior – the way functions are defined to act when given objects of these types as arguments. This is why a nominative type system is necessary: if structure determined type, which in turn dictates behavior, then it would be impossible to make [`Bool`](../../base/numbers/index#Core.Bool) behave any differently than [`Int8`](../../base/numbers/index#Core.Int8) or [`UInt8`](../../base/numbers/index#Core.UInt8).
[Composite Types](#Composite-Types)
------------------------------------
[Composite types](https://en.wikipedia.org/wiki/Composite_data_type) are called records, structs, or objects in various languages. A composite type is a collection of named fields, an instance of which can be treated as a single value. In many languages, composite types are the only kind of user-definable type, and they are by far the most commonly used user-defined type in Julia as well.
In mainstream object oriented languages, such as C++, Java, Python and Ruby, composite types also have named functions associated with them, and the combination is called an "object". In purer object-oriented languages, such as Ruby or Smalltalk, all values are objects whether they are composites or not. In less pure object oriented languages, including C++ and Java, some values, such as integers and floating-point values, are not objects, while instances of user-defined composite types are true objects with associated methods. In Julia, all values are objects, but functions are not bundled with the objects they operate on. This is necessary since Julia chooses which method of a function to use by multiple dispatch, meaning that the types of *all* of a function's arguments are considered when selecting a method, rather than just the first one (see [Methods](../methods/index#Methods) for more information on methods and dispatch). Thus, it would be inappropriate for functions to "belong" to only their first argument. Organizing methods into function objects rather than having named bags of methods "inside" each object ends up being a highly beneficial aspect of the language design.
Composite types are introduced with the [`struct`](../../base/base/index#struct) keyword followed by a block of field names, optionally annotated with types using the `::` operator:
```
julia> struct Foo
bar
baz::Int
qux::Float64
end
```
Fields with no type annotation default to `Any`, and can accordingly hold any type of value.
New objects of type `Foo` are created by applying the `Foo` type object like a function to values for its fields:
```
julia> foo = Foo("Hello, world.", 23, 1.5)
Foo("Hello, world.", 23, 1.5)
julia> typeof(foo)
Foo
```
When a type is applied like a function it is called a *constructor*. Two constructors are generated automatically (these are called *default constructors*). One accepts any arguments and calls [`convert`](../../base/base/index#Base.convert) to convert them to the types of the fields, and the other accepts arguments that match the field types exactly. The reason both of these are generated is that this makes it easier to add new definitions without inadvertently replacing a default constructor.
Since the `bar` field is unconstrained in type, any value will do. However, the value for `baz` must be convertible to `Int`:
```
julia> Foo((), 23.5, 1)
ERROR: InexactError: Int64(23.5)
Stacktrace:
[...]
```
You may find a list of field names using the [`fieldnames`](../../base/base/index#Base.fieldnames) function.
```
julia> fieldnames(Foo)
(:bar, :baz, :qux)
```
You can access the field values of a composite object using the traditional `foo.bar` notation:
```
julia> foo.bar
"Hello, world."
julia> foo.baz
23
julia> foo.qux
1.5
```
Composite objects declared with `struct` are *immutable*; they cannot be modified after construction. This may seem odd at first, but it has several advantages:
* It can be more efficient. Some structs can be packed efficiently into arrays, and in some cases the compiler is able to avoid allocating immutable objects entirely.
* It is not possible to violate the invariants provided by the type's constructors.
* Code using immutable objects can be easier to reason about.
An immutable object might contain mutable objects, such as arrays, as fields. Those contained objects will remain mutable; only the fields of the immutable object itself cannot be changed to point to different objects.
Where required, mutable composite objects can be declared with the keyword [`mutable struct`](../../base/base/index#mutable%20struct), to be discussed in the next section.
If all the fields of an immutable structure are indistinguishable (`===`) then two immutable values containing those fields are also indistinguishable:
```
julia> struct X
a::Int
b::Float64
end
julia> X(1, 2) === X(1, 2)
true
```
There is much more to say about how instances of composite types are created, but that discussion depends on both [Parametric Types](#Parametric-Types) and on [Methods](../methods/index#Methods), and is sufficiently important to be addressed in its own section: [Constructors](../constructors/index#man-constructors).
[Mutable Composite Types](#Mutable-Composite-Types)
----------------------------------------------------
If a composite type is declared with `mutable struct` instead of `struct`, then instances of it can be modified:
```
julia> mutable struct Bar
baz
qux::Float64
end
julia> bar = Bar("Hello", 1.5);
julia> bar.qux = 2.0
2.0
julia> bar.baz = 1//2
1//2
```
In order to support mutation, such objects are generally allocated on the heap, and have stable memory addresses. A mutable object is like a little container that might hold different values over time, and so can only be reliably identified with its address. In contrast, an instance of an immutable type is associated with specific field values –- the field values alone tell you everything about the object. In deciding whether to make a type mutable, ask whether two instances with the same field values would be considered identical, or if they might need to change independently over time. If they would be considered identical, the type should probably be immutable.
To recap, two essential properties define immutability in Julia:
* It is not permitted to modify the value of an immutable type.
+ For bits types this means that the bit pattern of a value once set will never change and that value is the identity of a bits type.
+ For composite types, this means that the identity of the values of its fields will never change. When the fields are bits types, that means their bits will never change, for fields whose values are mutable types like arrays, that means the fields will always refer to the same mutable value even though that mutable value's content may itself be modified.
* An object with an immutable type may be copied freely by the compiler since its immutability makes it impossible to programmatically distinguish between the original object and a copy.
+ In particular, this means that small enough immutable values like integers and floats are typically passed to functions in registers (or stack allocated).
+ Mutable values, on the other hand are heap-allocated and passed to functions as pointers to heap-allocated values except in cases where the compiler is sure that there's no way to tell that this is not what is happening.
In cases where one or more fields of an otherwise mutable struct is known to be immutable, one can declare these fields as such using `const` as shown below. This enables some, but not all of the optimizations of immutable structs, and can be used to enforce invariants on the particular fields marked as `const`.
`const` annotating fields of mutable structs requires at least Julia 1.8.
```
julia> mutable struct Baz
a::Int
const b::Float64
end
julia> baz = Baz(1, 1.5);
julia> baz.a = 2
2
julia> baz.b = 2.0
ERROR: setfield!: const field .b of type Baz cannot be changed
[...]
```
[Declared Types](#man-declared-types)
--------------------------------------
The three kinds of types (abstract, primitive, composite) discussed in the previous sections are actually all closely related. They share the same key properties:
* They are explicitly declared.
* They have names.
* They have explicitly declared supertypes.
* They may have parameters.
Because of these shared properties, these types are internally represented as instances of the same concept, `DataType`, which is the type of any of these types:
```
julia> typeof(Real)
DataType
julia> typeof(Int)
DataType
```
A `DataType` may be abstract or concrete. If it is concrete, it has a specified size, storage layout, and (optionally) field names. Thus a primitive type is a `DataType` with nonzero size, but no field names. A composite type is a `DataType` that has field names or is empty (zero size).
Every concrete value in the system is an instance of some `DataType`.
[Type Unions](#Type-Unions)
----------------------------
A type union is a special abstract type which includes as objects all instances of any of its argument types, constructed using the special [`Union`](../../base/base/index#Core.Union) keyword:
```
julia> IntOrString = Union{Int,AbstractString}
Union{Int64, AbstractString}
julia> 1 :: IntOrString
1
julia> "Hello!" :: IntOrString
"Hello!"
julia> 1.0 :: IntOrString
ERROR: TypeError: in typeassert, expected Union{Int64, AbstractString}, got a value of type Float64
```
The compilers for many languages have an internal union construct for reasoning about types; Julia simply exposes it to the programmer. The Julia compiler is able to generate efficient code in the presence of `Union` types with a small number of types [[1]](#footnote-1), by generating specialized code in separate branches for each possible type.
A particularly useful case of a `Union` type is `Union{T, Nothing}`, where `T` can be any type and [`Nothing`](../../base/base/index#Core.Nothing) is the singleton type whose only instance is the object [`nothing`](../../base/constants/index#Core.nothing). This pattern is the Julia equivalent of [`Nullable`, `Option` or `Maybe`](https://en.wikipedia.org/wiki/Nullable_type) types in other languages. Declaring a function argument or a field as `Union{T, Nothing}` allows setting it either to a value of type `T`, or to `nothing` to indicate that there is no value. See [this FAQ entry](../faq/index#faq-nothing) for more information.
[Parametric Types](#Parametric-Types)
--------------------------------------
An important and powerful feature of Julia's type system is that it is parametric: types can take parameters, so that type declarations actually introduce a whole family of new types – one for each possible combination of parameter values. There are many languages that support some version of [generic programming](https://en.wikipedia.org/wiki/Generic_programming), wherein data structures and algorithms to manipulate them may be specified without specifying the exact types involved. For example, some form of generic programming exists in ML, Haskell, Ada, Eiffel, C++, Java, C#, F#, and Scala, just to name a few. Some of these languages support true parametric polymorphism (e.g. ML, Haskell, Scala), while others support ad-hoc, template-based styles of generic programming (e.g. C++, Java). With so many different varieties of generic programming and parametric types in various languages, we won't even attempt to compare Julia's parametric types to other languages, but will instead focus on explaining Julia's system in its own right. We will note, however, that because Julia is a dynamically typed language and doesn't need to make all type decisions at compile time, many traditional difficulties encountered in static parametric type systems can be relatively easily handled.
All declared types (the `DataType` variety) can be parameterized, with the same syntax in each case. We will discuss them in the following order: first, parametric composite types, then parametric abstract types, and finally parametric primitive types.
###
[Parametric Composite Types](#man-parametric-composite-types)
Type parameters are introduced immediately after the type name, surrounded by curly braces:
```
julia> struct Point{T}
x::T
y::T
end
```
This declaration defines a new parametric type, `Point{T}`, holding two "coordinates" of type `T`. What, one may ask, is `T`? Well, that's precisely the point of parametric types: it can be any type at all (or a value of any bits type, actually, although here it's clearly used as a type). `Point{Float64}` is a concrete type equivalent to the type defined by replacing `T` in the definition of `Point` with [`Float64`](../../base/numbers/index#Core.Float64). Thus, this single declaration actually declares an unlimited number of types: `Point{Float64}`, `Point{AbstractString}`, `Point{Int64}`, etc. Each of these is now a usable concrete type:
```
julia> Point{Float64}
Point{Float64}
julia> Point{AbstractString}
Point{AbstractString}
```
The type `Point{Float64}` is a point whose coordinates are 64-bit floating-point values, while the type `Point{AbstractString}` is a "point" whose "coordinates" are string objects (see [Strings](https://docs.julialang.org/en/v1.8/devdocs/ast/#Strings)).
`Point` itself is also a valid type object, containing all instances `Point{Float64}`, `Point{AbstractString}`, etc. as subtypes:
```
julia> Point{Float64} <: Point
true
julia> Point{AbstractString} <: Point
true
```
Other types, of course, are not subtypes of it:
```
julia> Float64 <: Point
false
julia> AbstractString <: Point
false
```
Concrete `Point` types with different values of `T` are never subtypes of each other:
```
julia> Point{Float64} <: Point{Int64}
false
julia> Point{Float64} <: Point{Real}
false
```
This last point is *very* important: even though `Float64 <: Real` we **DO NOT** have `Point{Float64} <: Point{Real}`.
In other words, in the parlance of type theory, Julia's type parameters are *invariant*, rather than being [covariant (or even contravariant)](https://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29). This is for practical reasons: while any instance of `Point{Float64}` may conceptually be like an instance of `Point{Real}` as well, the two types have different representations in memory:
* An instance of `Point{Float64}` can be represented compactly and efficiently as an immediate pair of 64-bit values;
* An instance of `Point{Real}` must be able to hold any pair of instances of [`Real`](../../base/numbers/index#Core.Real). Since objects that are instances of `Real` can be of arbitrary size and structure, in practice an instance of `Point{Real}` must be represented as a pair of pointers to individually allocated `Real` objects.
The efficiency gained by being able to store `Point{Float64}` objects with immediate values is magnified enormously in the case of arrays: an `Array{Float64}` can be stored as a contiguous memory block of 64-bit floating-point values, whereas an `Array{Real}` must be an array of pointers to individually allocated [`Real`](../../base/numbers/index#Core.Real) objects – which may well be [boxed](https://en.wikipedia.org/wiki/Object_type_%28object-oriented_programming%29#Boxing) 64-bit floating-point values, but also might be arbitrarily large, complex objects, which are declared to be implementations of the `Real` abstract type.
Since `Point{Float64}` is not a subtype of `Point{Real}`, the following method can't be applied to arguments of type `Point{Float64}`:
```
function norm(p::Point{Real})
sqrt(p.x^2 + p.y^2)
end
```
A correct way to define a method that accepts all arguments of type `Point{T}` where `T` is a subtype of [`Real`](../../base/numbers/index#Core.Real) is:
```
function norm(p::Point{<:Real})
sqrt(p.x^2 + p.y^2)
end
```
(Equivalently, one could define `function norm(p::Point{T} where T<:Real)` or `function norm(p::Point{T}) where T<:Real`; see [UnionAll Types](#UnionAll-Types).)
More examples will be discussed later in [Methods](../methods/index#Methods).
How does one construct a `Point` object? It is possible to define custom constructors for composite types, which will be discussed in detail in [Constructors](../constructors/index#man-constructors), but in the absence of any special constructor declarations, there are two default ways of creating new composite objects, one in which the type parameters are explicitly given and the other in which they are implied by the arguments to the object constructor.
Since the type `Point{Float64}` is a concrete type equivalent to `Point` declared with [`Float64`](../../base/numbers/index#Core.Float64) in place of `T`, it can be applied as a constructor accordingly:
```
julia> p = Point{Float64}(1.0, 2.0)
Point{Float64}(1.0, 2.0)
julia> typeof(p)
Point{Float64}
```
For the default constructor, exactly one argument must be supplied for each field:
```
julia> Point{Float64}(1.0)
ERROR: MethodError: no method matching Point{Float64}(::Float64)
[...]
julia> Point{Float64}(1.0,2.0,3.0)
ERROR: MethodError: no method matching Point{Float64}(::Float64, ::Float64, ::Float64)
[...]
```
Only one default constructor is generated for parametric types, since overriding it is not possible. This constructor accepts any arguments and converts them to the field types.
In many cases, it is redundant to provide the type of `Point` object one wants to construct, since the types of arguments to the constructor call already implicitly provide type information. For that reason, you can also apply `Point` itself as a constructor, provided that the implied value of the parameter type `T` is unambiguous:
```
julia> p1 = Point(1.0,2.0)
Point{Float64}(1.0, 2.0)
julia> typeof(p1)
Point{Float64}
julia> p2 = Point(1,2)
Point{Int64}(1, 2)
julia> typeof(p2)
Point{Int64}
```
In the case of `Point`, the type of `T` is unambiguously implied if and only if the two arguments to `Point` have the same type. When this isn't the case, the constructor will fail with a [`MethodError`](../../base/base/index#Core.MethodError):
```
julia> Point(1,2.5)
ERROR: MethodError: no method matching Point(::Int64, ::Float64)
Closest candidates are:
Point(::T, !Matched::T) where T at none:2
```
Constructor methods to appropriately handle such mixed cases can be defined, but that will not be discussed until later on in [Constructors](../constructors/index#man-constructors).
###
[Parametric Abstract Types](#Parametric-Abstract-Types)
Parametric abstract type declarations declare a collection of abstract types, in much the same way:
```
julia> abstract type Pointy{T} end
```
With this declaration, `Pointy{T}` is a distinct abstract type for each type or integer value of `T`. As with parametric composite types, each such instance is a subtype of `Pointy`:
```
julia> Pointy{Int64} <: Pointy
true
julia> Pointy{1} <: Pointy
true
```
Parametric abstract types are invariant, much as parametric composite types are:
```
julia> Pointy{Float64} <: Pointy{Real}
false
julia> Pointy{Real} <: Pointy{Float64}
false
```
The notation `Pointy{<:Real}` can be used to express the Julia analogue of a *covariant* type, while `Pointy{>:Int}` the analogue of a *contravariant* type, but technically these represent *sets* of types (see [UnionAll Types](#UnionAll-Types)).
```
julia> Pointy{Float64} <: Pointy{<:Real}
true
julia> Pointy{Real} <: Pointy{>:Int}
true
```
Much as plain old abstract types serve to create a useful hierarchy of types over concrete types, parametric abstract types serve the same purpose with respect to parametric composite types. We could, for example, have declared `Point{T}` to be a subtype of `Pointy{T}` as follows:
```
julia> struct Point{T} <: Pointy{T}
x::T
y::T
end
```
Given such a declaration, for each choice of `T`, we have `Point{T}` as a subtype of `Pointy{T}`:
```
julia> Point{Float64} <: Pointy{Float64}
true
julia> Point{Real} <: Pointy{Real}
true
julia> Point{AbstractString} <: Pointy{AbstractString}
true
```
This relationship is also invariant:
```
julia> Point{Float64} <: Pointy{Real}
false
julia> Point{Float64} <: Pointy{<:Real}
true
```
What purpose do parametric abstract types like `Pointy` serve? Consider if we create a point-like implementation that only requires a single coordinate because the point is on the diagonal line *x = y*:
```
julia> struct DiagPoint{T} <: Pointy{T}
x::T
end
```
Now both `Point{Float64}` and `DiagPoint{Float64}` are implementations of the `Pointy{Float64}` abstraction, and similarly for every other possible choice of type `T`. This allows programming to a common interface shared by all `Pointy` objects, implemented for both `Point` and `DiagPoint`. This cannot be fully demonstrated, however, until we have introduced methods and dispatch in the next section, [Methods](../methods/index#Methods).
There are situations where it may not make sense for type parameters to range freely over all possible types. In such situations, one can constrain the range of `T` like so:
```
julia> abstract type Pointy{T<:Real} end
```
With such a declaration, it is acceptable to use any type that is a subtype of [`Real`](../../base/numbers/index#Core.Real) in place of `T`, but not types that are not subtypes of `Real`:
```
julia> Pointy{Float64}
Pointy{Float64}
julia> Pointy{Real}
Pointy{Real}
julia> Pointy{AbstractString}
ERROR: TypeError: in Pointy, in T, expected T<:Real, got Type{AbstractString}
julia> Pointy{1}
ERROR: TypeError: in Pointy, in T, expected T<:Real, got a value of type Int64
```
Type parameters for parametric composite types can be restricted in the same manner:
```
struct Point{T<:Real} <: Pointy{T}
x::T
y::T
end
```
To give a real-world example of how all this parametric type machinery can be useful, here is the actual definition of Julia's [`Rational`](../../base/numbers/index#Base.Rational) immutable type (except that we omit the constructor here for simplicity), representing an exact ratio of integers:
```
struct Rational{T<:Integer} <: Real
num::T
den::T
end
```
It only makes sense to take ratios of integer values, so the parameter type `T` is restricted to being a subtype of [`Integer`](../../base/numbers/index#Core.Integer), and a ratio of integers represents a value on the real number line, so any [`Rational`](../../base/numbers/index#Base.Rational) is an instance of the [`Real`](../../base/numbers/index#Core.Real) abstraction.
###
[Tuple Types](#Tuple-Types)
Tuples are an abstraction of the arguments of a function – without the function itself. The salient aspects of a function's arguments are their order and their types. Therefore a tuple type is similar to a parameterized immutable type where each parameter is the type of one field. For example, a 2-element tuple type resembles the following immutable type:
```
struct Tuple2{A,B}
a::A
b::B
end
```
However, there are three key differences:
* Tuple types may have any number of parameters.
* Tuple types are *covariant* in their parameters: `Tuple{Int}` is a subtype of `Tuple{Any}`. Therefore `Tuple{Any}` is considered an abstract type, and tuple types are only concrete if their parameters are.
* Tuples do not have field names; fields are only accessed by index.
Tuple values are written with parentheses and commas. When a tuple is constructed, an appropriate tuple type is generated on demand:
```
julia> typeof((1,"foo",2.5))
Tuple{Int64, String, Float64}
```
Note the implications of covariance:
```
julia> Tuple{Int,AbstractString} <: Tuple{Real,Any}
true
julia> Tuple{Int,AbstractString} <: Tuple{Real,Real}
false
julia> Tuple{Int,AbstractString} <: Tuple{Real,}
false
```
Intuitively, this corresponds to the type of a function's arguments being a subtype of the function's signature (when the signature matches).
###
[Vararg Tuple Types](#Vararg-Tuple-Types)
The last parameter of a tuple type can be the special value [`Vararg`](../../base/base/index#Core.Vararg), which denotes any number of trailing elements:
```
julia> mytupletype = Tuple{AbstractString,Vararg{Int}}
Tuple{AbstractString, Vararg{Int64}}
julia> isa(("1",), mytupletype)
true
julia> isa(("1",1), mytupletype)
true
julia> isa(("1",1,2), mytupletype)
true
julia> isa(("1",1,2,3.0), mytupletype)
false
```
Moreover `Vararg{T}` corresponds to zero or more elements of type `T`. Vararg tuple types are used to represent the arguments accepted by varargs methods (see [Varargs Functions](../functions/index#Varargs-Functions)).
The special value `Vararg{T,N}` (when used as the last parameter of a tuple type) corresponds to exactly `N` elements of type `T`. `NTuple{N,T}` is a convenient alias for `Tuple{Vararg{T,N}}`, i.e. a tuple type containing exactly `N` elements of type `T`.
###
[Named Tuple Types](#Named-Tuple-Types)
Named tuples are instances of the [`NamedTuple`](../../base/base/index#Core.NamedTuple) type, which has two parameters: a tuple of symbols giving the field names, and a tuple type giving the field types.
```
julia> typeof((a=1,b="hello"))
NamedTuple{(:a, :b), Tuple{Int64, String}}
```
The [`@NamedTuple`](../../base/base/index#Base.@NamedTuple) macro provides a more convenient `struct`-like syntax for declaring `NamedTuple` types via `key::Type` declarations, where an omitted `::Type` corresponds to `::Any`.
```
julia> @NamedTuple{a::Int, b::String}
NamedTuple{(:a, :b), Tuple{Int64, String}}
julia> @NamedTuple begin
a::Int
b::String
end
NamedTuple{(:a, :b), Tuple{Int64, String}}
```
A `NamedTuple` type can be used as a constructor, accepting a single tuple argument. The constructed `NamedTuple` type can be either a concrete type, with both parameters specified, or a type that specifies only field names:
```
julia> @NamedTuple{a::Float32,b::String}((1,""))
(a = 1.0f0, b = "")
julia> NamedTuple{(:a, :b)}((1,""))
(a = 1, b = "")
```
If field types are specified, the arguments are converted. Otherwise the types of the arguments are used directly.
###
[Parametric Primitive Types](#Parametric-Primitive-Types)
Primitive types can also be declared parametrically. For example, pointers are represented as primitive types which would be declared in Julia like this:
```
# 32-bit system:
primitive type Ptr{T} 32 end
# 64-bit system:
primitive type Ptr{T} 64 end
```
The slightly odd feature of these declarations as compared to typical parametric composite types, is that the type parameter `T` is not used in the definition of the type itself – it is just an abstract tag, essentially defining an entire family of types with identical structure, differentiated only by their type parameter. Thus, `Ptr{Float64}` and `Ptr{Int64}` are distinct types, even though they have identical representations. And of course, all specific pointer types are subtypes of the umbrella [`Ptr`](../../base/c/index#Core.Ptr) type:
```
julia> Ptr{Float64} <: Ptr
true
julia> Ptr{Int64} <: Ptr
true
```
[UnionAll Types](#UnionAll-Types)
----------------------------------
We have said that a parametric type like `Ptr` acts as a supertype of all its instances (`Ptr{Int64}` etc.). How does this work? `Ptr` itself cannot be a normal data type, since without knowing the type of the referenced data the type clearly cannot be used for memory operations. The answer is that `Ptr` (or other parametric types like `Array`) is a different kind of type called a [`UnionAll`](../../base/base/index#Core.UnionAll) type. Such a type expresses the *iterated union* of types for all values of some parameter.
`UnionAll` types are usually written using the keyword `where`. For example `Ptr` could be more accurately written as `Ptr{T} where T`, meaning all values whose type is `Ptr{T}` for some value of `T`. In this context, the parameter `T` is also often called a "type variable" since it is like a variable that ranges over types. Each `where` introduces a single type variable, so these expressions are nested for types with multiple parameters, for example `Array{T,N} where N where T`.
The type application syntax `A{B,C}` requires `A` to be a `UnionAll` type, and first substitutes `B` for the outermost type variable in `A`. The result is expected to be another `UnionAll` type, into which `C` is then substituted. So `A{B,C}` is equivalent to `A{B}{C}`. This explains why it is possible to partially instantiate a type, as in `Array{Float64}`: the first parameter value has been fixed, but the second still ranges over all possible values. Using explicit `where` syntax, any subset of parameters can be fixed. For example, the type of all 1-dimensional arrays can be written as `Array{T,1} where T`.
Type variables can be restricted with subtype relations. `Array{T} where T<:Integer` refers to all arrays whose element type is some kind of [`Integer`](../../base/numbers/index#Core.Integer). The syntax `Array{<:Integer}` is a convenient shorthand for `Array{T} where T<:Integer`. Type variables can have both lower and upper bounds. `Array{T} where Int<:T<:Number` refers to all arrays of [`Number`](../../base/numbers/index#Core.Number)s that are able to contain `Int`s (since `T` must be at least as big as `Int`). The syntax `where T>:Int` also works to specify only the lower bound of a type variable, and `Array{>:Int}` is equivalent to `Array{T} where T>:Int`.
Since `where` expressions nest, type variable bounds can refer to outer type variables. For example `Tuple{T,Array{S}} where S<:AbstractArray{T} where T<:Real` refers to 2-tuples whose first element is some [`Real`](../../base/numbers/index#Core.Real), and whose second element is an `Array` of any kind of array whose element type contains the type of the first tuple element.
The `where` keyword itself can be nested inside a more complex declaration. For example, consider the two types created by the following declarations:
```
julia> const T1 = Array{Array{T, 1} where T, 1}
Vector{Vector} (alias for Array{Array{T, 1} where T, 1})
julia> const T2 = Array{Array{T, 1}, 1} where T
Array{Vector{T}, 1} where T
```
Type `T1` defines a 1-dimensional array of 1-dimensional arrays; each of the inner arrays consists of objects of the same type, but this type may vary from one inner array to the next. On the other hand, type `T2` defines a 1-dimensional array of 1-dimensional arrays all of whose inner arrays must have the same type. Note that `T2` is an abstract type, e.g., `Array{Array{Int,1},1} <: T2`, whereas `T1` is a concrete type. As a consequence, `T1` can be constructed with a zero-argument constructor `a=T1()` but `T2` cannot.
There is a convenient syntax for naming such types, similar to the short form of function definition syntax:
```
Vector{T} = Array{T, 1}
```
This is equivalent to `const Vector = Array{T,1} where T`. Writing `Vector{Float64}` is equivalent to writing `Array{Float64,1}`, and the umbrella type `Vector` has as instances all `Array` objects where the second parameter – the number of array dimensions – is 1, regardless of what the element type is. In languages where parametric types must always be specified in full, this is not especially helpful, but in Julia, this allows one to write just `Vector` for the abstract type including all one-dimensional dense arrays of any element type.
[Singleton types](#man-singleton-types)
----------------------------------------
Immutable composite types with no fields are called *singletons*. Formally, if
1. `T` is an immutable composite type (i.e. defined with `struct`),
2. `a isa T && b isa T` implies `a === b`,
then `T` is a singleton type.[[2]](#footnote-2) [`Base.issingletontype`](../../base/base/index#Base.issingletontype) can be used to check if a type is a singleton type. [Abstract types](#man-abstract-types) cannot be singleton types by construction.
From the definition, it follows that there can be only one instance of such types:
```
julia> struct NoFields
end
julia> NoFields() === NoFields()
true
julia> Base.issingletontype(NoFields)
true
```
The [`===`](../../base/base/index#Core.:===) function confirms that the constructed instances of `NoFields` are actually one and the same.
Parametric types can be singleton types when the above condition holds. For example,
```
julia> struct NoFieldsParam{T}
end
julia> Base.issingletontype(NoFieldsParam) # can't be a singleton type ...
false
julia> NoFieldsParam{Int}() isa NoFieldsParam # ... because it has ...
true
julia> NoFieldsParam{Bool}() isa NoFieldsParam # ... multiple instances
true
julia> Base.issingletontype(NoFieldsParam{Int}) # parametrized, it is a singleton
true
julia> NoFieldsParam{Int}() === NoFieldsParam{Int}()
true
```
[Types of functions](#Types-of-functions)
------------------------------------------
Each function has its own type, which is a subtype of `Function`.
```
julia> foo41(x) = x + 1
foo41 (generic function with 1 method)
julia> typeof(foo41)
typeof(foo41) (singleton type of function foo41, subtype of Function)
```
Note how `typeof(foo41)` prints as itself. This is merely a convention for printing, as it is a first-class object that can be used like any other value:
```
julia> T = typeof(foo41)
typeof(foo41) (singleton type of function foo41, subtype of Function)
julia> T <: Function
true
```
Types of functions defined at top-level are singletons. When necessary, you can compare them with [`===`](../../base/base/index#Core.:===).
[Closures](../functions/index#man-anonymous-functions) also have their own type, which is usually printed with names that end in `#<number>`. Names and types for functions defined at different locations are distinct, but not guaranteed to be printed the same way across sessions.
```
julia> typeof(x -> x + 1)
var"#9#10"
```
Types of closures are not necessarily singletons.
```
julia> addy(y) = x -> x + y
addy (generic function with 1 method)
julia> Base.issingletontype(addy(1))
false
julia> addy(1) === addy(2)
false
```
[`Type{T}` type selectors](#man-typet-type)
--------------------------------------------
For each type `T`, `Type{T}` is an abstract parametric type whose only instance is the object `T`. Until we discuss [Parametric Methods](../methods/index#Parametric-Methods) and [conversions](../conversion-and-promotion/index#conversion-and-promotion), it is difficult to explain the utility of this construct, but in short, it allows one to specialize function behavior on specific types as *values*. This is useful for writing methods (especially parametric ones) whose behavior depends on a type that is given as an explicit argument rather than implied by the type of one of its arguments.
Since the definition is a little difficult to parse, let's look at some examples:
```
julia> isa(Float64, Type{Float64})
true
julia> isa(Real, Type{Float64})
false
julia> isa(Real, Type{Real})
true
julia> isa(Float64, Type{Real})
false
```
In other words, [`isa(A, Type{B})`](../../base/base/index#Core.isa) is true if and only if `A` and `B` are the same object and that object is a type.
In particular, since parametric types are [invariant](#man-parametric-composite-types), we have
```
julia> struct TypeParamExample{T}
x::T
end
julia> TypeParamExample isa Type{TypeParamExample}
true
julia> TypeParamExample{Int} isa Type{TypeParamExample}
false
julia> TypeParamExample{Int} isa Type{TypeParamExample{Int}}
true
```
Without the parameter, `Type` is simply an abstract type which has all type objects as its instances:
```
julia> isa(Type{Float64}, Type)
true
julia> isa(Float64, Type)
true
julia> isa(Real, Type)
true
```
Any object that is not a type is not an instance of `Type`:
```
julia> isa(1, Type)
false
julia> isa("foo", Type)
false
```
While `Type` is part of Julia's type hierarchy like any other abstract parametric type, it is not commonly used outside method signatures except in some special cases. Another important use case for `Type` is sharpening field types which would otherwise be captured less precisely, e.g. as [`DataType`](#man-declared-types) in the example below where the default constructor could lead to performance problems in code relying on the precise wrapped type (similarly to [abstract type parameters](../performance-tips/index#man-performance-abstract-container)).
```
julia> struct WrapType{T}
value::T
end
julia> WrapType(Float64) # default constructor, note DataType
WrapType{DataType}(Float64)
julia> WrapType(::Type{T}) where T = WrapType{Type{T}}(T)
WrapType
julia> WrapType(Float64) # sharpened constructor, note more precise Type{Float64}
WrapType{Type{Float64}}(Float64)
```
[Type Aliases](#Type-Aliases)
------------------------------
Sometimes it is convenient to introduce a new name for an already expressible type. This can be done with a simple assignment statement. For example, `UInt` is aliased to either [`UInt32`](../../base/numbers/index#Core.UInt32) or [`UInt64`](../../base/numbers/index#Core.UInt64) as is appropriate for the size of pointers on the system:
```
# 32-bit system:
julia> UInt
UInt32
# 64-bit system:
julia> UInt
UInt64
```
This is accomplished via the following code in `base/boot.jl`:
```
if Int === Int64
const UInt = UInt64
else
const UInt = UInt32
end
```
Of course, this depends on what `Int` is aliased to – but that is predefined to be the correct type – either [`Int32`](../../base/numbers/index#Core.Int32) or [`Int64`](../../base/numbers/index#Core.Int64).
(Note that unlike `Int`, `Float` does not exist as a type alias for a specific sized [`AbstractFloat`](../../base/numbers/index#Core.AbstractFloat). Unlike with integer registers, where the size of `Int` reflects the size of a native pointer on that machine, the floating point register sizes are specified by the IEEE-754 standard.)
[Operations on Types](#Operations-on-Types)
--------------------------------------------
Since types in Julia are themselves objects, ordinary functions can operate on them. Some functions that are particularly useful for working with or exploring types have already been introduced, such as the `<:` operator, which indicates whether its left hand operand is a subtype of its right hand operand.
The [`isa`](../../base/base/index#Core.isa) function tests if an object is of a given type and returns true or false:
```
julia> isa(1, Int)
true
julia> isa(1, AbstractFloat)
false
```
The [`typeof`](../../base/base/index#Core.typeof) function, already used throughout the manual in examples, returns the type of its argument. Since, as noted above, types are objects, they also have types, and we can ask what their types are:
```
julia> typeof(Rational{Int})
DataType
julia> typeof(Union{Real,String})
Union
```
What if we repeat the process? What is the type of a type of a type? As it happens, types are all composite values and thus all have a type of `DataType`:
```
julia> typeof(DataType)
DataType
julia> typeof(Union)
DataType
```
`DataType` is its own type.
Another operation that applies to some types is [`supertype`](../../base/base/index#Base.supertype), which reveals a type's supertype. Only declared types (`DataType`) have unambiguous supertypes:
```
julia> supertype(Float64)
AbstractFloat
julia> supertype(Number)
Any
julia> supertype(AbstractString)
Any
julia> supertype(Any)
Any
```
If you apply [`supertype`](../../base/base/index#Base.supertype) to other type objects (or non-type objects), a [`MethodError`](../../base/base/index#Core.MethodError) is raised:
```
julia> supertype(Union{Float64,Int64})
ERROR: MethodError: no method matching supertype(::Type{Union{Float64, Int64}})
Closest candidates are:
[...]
```
[Custom pretty-printing](#man-custom-pretty-printing)
------------------------------------------------------
Often, one wants to customize how instances of a type are displayed. This is accomplished by overloading the [`show`](#) function. For example, suppose we define a type to represent complex numbers in polar form:
```
julia> struct Polar{T<:Real} <: Number
r::T
Θ::T
end
julia> Polar(r::Real,Θ::Real) = Polar(promote(r,Θ)...)
Polar
```
Here, we've added a custom constructor function so that it can take arguments of different [`Real`](../../base/numbers/index#Core.Real) types and promote them to a common type (see [Constructors](../constructors/index#man-constructors) and [Conversion and Promotion](../conversion-and-promotion/index#conversion-and-promotion)). (Of course, we would have to define lots of other methods, too, to make it act like a [`Number`](../../base/numbers/index#Core.Number), e.g. `+`, `*`, `one`, `zero`, promotion rules and so on.) By default, instances of this type display rather simply, with information about the type name and the field values, as e.g. `Polar{Float64}(3.0,4.0)`.
If we want it to display instead as `3.0 * exp(4.0im)`, we would define the following method to print the object to a given output object `io` (representing a file, terminal, buffer, etcetera; see [Networking and Streams](../networking-and-streams/index#Networking-and-Streams)):
```
julia> Base.show(io::IO, z::Polar) = print(io, z.r, " * exp(", z.Θ, "im)")
```
More fine-grained control over display of `Polar` objects is possible. In particular, sometimes one wants both a verbose multi-line printing format, used for displaying a single object in the REPL and other interactive environments, and also a more compact single-line format used for [`print`](../../base/io-network/index#Base.print) or for displaying the object as part of another object (e.g. in an array). Although by default the `show(io, z)` function is called in both cases, you can define a *different* multi-line format for displaying an object by overloading a three-argument form of `show` that takes the `text/plain` MIME type as its second argument (see [Multimedia I/O](../../base/io-network/index#Multimedia-I/O)), for example:
```
julia> Base.show(io::IO, ::MIME"text/plain", z::Polar{T}) where{T} =
print(io, "Polar{$T} complex number:\n ", z)
```
(Note that `print(..., z)` here will call the 2-argument `show(io, z)` method.) This results in:
```
julia> Polar(3, 4.0)
Polar{Float64} complex number:
3.0 * exp(4.0im)
julia> [Polar(3, 4.0), Polar(4.0,5.3)]
2-element Vector{Polar{Float64}}:
3.0 * exp(4.0im)
4.0 * exp(5.3im)
```
where the single-line `show(io, z)` form is still used for an array of `Polar` values. Technically, the REPL calls `display(z)` to display the result of executing a line, which defaults to `show(stdout, MIME("text/plain"), z)`, which in turn defaults to `show(stdout, z)`, but you should *not* define new [`display`](../../base/io-network/index#Base.Multimedia.display) methods unless you are defining a new multimedia display handler (see [Multimedia I/O](../../base/io-network/index#Multimedia-I/O)).
Moreover, you can also define `show` methods for other MIME types in order to enable richer display (HTML, images, etcetera) of objects in environments that support this (e.g. IJulia). For example, we can define formatted HTML display of `Polar` objects, with superscripts and italics, via:
```
julia> Base.show(io::IO, ::MIME"text/html", z::Polar{T}) where {T} =
println(io, "<code>Polar{$T}</code> complex number: ",
z.r, " <i>e</i><sup>", z.Θ, " <i>i</i></sup>")
```
A `Polar` object will then display automatically using HTML in an environment that supports HTML display, but you can call `show` manually to get HTML output if you want:
```
julia> show(stdout, "text/html", Polar(3.0,4.0))
<code>Polar{Float64}</code> complex number: 3.0 <i>e</i><sup>4.0 <i>i</i></sup>
```
An HTML renderer would display this as: `Polar{Float64}` complex number: 3.0 *e*4.0 *i*
As a rule of thumb, the single-line `show` method should print a valid Julia expression for creating the shown object. When this `show` method contains infix operators, such as the multiplication operator (`*`) in our single-line `show` method for `Polar` above, it may not parse correctly when printed as part of another object. To see this, consider the expression object (see [Program representation](../metaprogramming/index#Program-representation)) which takes the square of a specific instance of our `Polar` type:
```
julia> a = Polar(3, 4.0)
Polar{Float64} complex number:
3.0 * exp(4.0im)
julia> print(:($a^2))
3.0 * exp(4.0im) ^ 2
```
Because the operator `^` has higher precedence than `*` (see [Operator Precedence and Associativity](../mathematical-operations/index#Operator-Precedence-and-Associativity)), this output does not faithfully represent the expression `a ^ 2` which should be equal to `(3.0 * exp(4.0im)) ^ 2`. To solve this issue, we must make a custom method for `Base.show_unquoted(io::IO, z::Polar, indent::Int, precedence::Int)`, which is called internally by the expression object when printing:
```
julia> function Base.show_unquoted(io::IO, z::Polar, ::Int, precedence::Int)
if Base.operator_precedence(:*) <= precedence
print(io, "(")
show(io, z)
print(io, ")")
else
show(io, z)
end
end
julia> :($a^2)
:((3.0 * exp(4.0im)) ^ 2)
```
The method defined above adds parentheses around the call to `show` when the precedence of the calling operator is higher than or equal to the precedence of multiplication. This check allows expressions which parse correctly without the parentheses (such as `:($a + 2)` and `:($a == 2)`) to omit them when printing:
```
julia> :($a + 2)
:(3.0 * exp(4.0im) + 2)
julia> :($a == 2)
:(3.0 * exp(4.0im) == 2)
```
In some cases, it is useful to adjust the behavior of `show` methods depending on the context. This can be achieved via the [`IOContext`](../../base/io-network/index#Base.IOContext) type, which allows passing contextual properties together with a wrapped IO stream. For example, we can build a shorter representation in our `show` method when the `:compact` property is set to `true`, falling back to the long representation if the property is `false` or absent:
```
julia> function Base.show(io::IO, z::Polar)
if get(io, :compact, false)
print(io, z.r, "ℯ", z.Θ, "im")
else
print(io, z.r, " * exp(", z.Θ, "im)")
end
end
```
This new compact representation will be used when the passed IO stream is an `IOContext` object with the `:compact` property set. In particular, this is the case when printing arrays with multiple columns (where horizontal space is limited):
```
julia> show(IOContext(stdout, :compact=>true), Polar(3, 4.0))
3.0ℯ4.0im
julia> [Polar(3, 4.0) Polar(4.0,5.3)]
1×2 Matrix{Polar{Float64}}:
3.0ℯ4.0im 4.0ℯ5.3im
```
See the [`IOContext`](../../base/io-network/index#Base.IOContext) documentation for a list of common properties which can be used to adjust printing.
["Value types"](#%22Value-types%22)
------------------------------------
In Julia, you can't dispatch on a *value* such as `true` or `false`. However, you can dispatch on parametric types, and Julia allows you to include "plain bits" values (Types, Symbols, Integers, floating-point numbers, tuples, etc.) as type parameters. A common example is the dimensionality parameter in `Array{T,N}`, where `T` is a type (e.g., [`Float64`](../../base/numbers/index#Core.Float64)) but `N` is just an `Int`.
You can create your own custom types that take values as parameters, and use them to control dispatch of custom types. By way of illustration of this idea, let's introduce a parametric type, `Val{x}`, and a constructor `Val(x) = Val{x}()`, which serves as a customary way to exploit this technique for cases where you don't need a more elaborate hierarchy.
[`Val`](../../base/base/index#Base.Val) is defined as:
```
julia> struct Val{x}
end
julia> Val(x) = Val{x}()
Val
```
There is no more to the implementation of `Val` than this. Some functions in Julia's standard library accept `Val` instances as arguments, and you can also use it to write your own functions. For example:
```
julia> firstlast(::Val{true}) = "First"
firstlast (generic function with 1 method)
julia> firstlast(::Val{false}) = "Last"
firstlast (generic function with 2 methods)
julia> firstlast(Val(true))
"First"
julia> firstlast(Val(false))
"Last"
```
For consistency across Julia, the call site should always pass a `Val` *instance* rather than using a *type*, i.e., use `foo(Val(:bar))` rather than `foo(Val{:bar})`.
It's worth noting that it's extremely easy to mis-use parametric "value" types, including `Val`; in unfavorable cases, you can easily end up making the performance of your code much *worse*. In particular, you would never want to write actual code as illustrated above. For more information about the proper (and improper) uses of `Val`, please read [the more extensive discussion in the performance tips](../performance-tips/index#man-performance-value-type).
* [1](#citeref-1)"Small" is defined by the `MAX_UNION_SPLITTING` constant, which is currently set to 4.
* [2](#citeref-2)A few popular languages have singleton types, including Haskell, Scala and Ruby.
| programming_docs |
julia Environment Variables Environment Variables
=====================
Julia can be configured with a number of environment variables, set either in the usual way for each operating system, or in a portable way from within Julia. Supposing that you want to set the environment variable `JULIA_EDITOR` to `vim`, you can type `ENV["JULIA_EDITOR"] = "vim"` (for instance, in the REPL) to make this change on a case by case basis, or add the same to the user configuration file `~/.julia/config/startup.jl` in the user's home directory to have a permanent effect. The current value of the same environment variable can be determined by evaluating `ENV["JULIA_EDITOR"]`.
The environment variables that Julia uses generally start with `JULIA`. If [`InteractiveUtils.versioninfo`](../../stdlib/interactiveutils/index#InteractiveUtils.versioninfo) is called with the keyword `verbose=true`, then the output will list any defined environment variables relevant for Julia, including those which include `JULIA` in their names.
Some variables, such as `JULIA_NUM_THREADS` and `JULIA_PROJECT`, need to be set before Julia starts, therefore adding these to `~/.julia/config/startup.jl` is too late in the startup process. In Bash, environment variables can either be set manually by running, e.g., `export JULIA_NUM_THREADS=4` before starting Julia, or by adding the same command to `~/.bashrc` or `~/.bash_profile` to set the variable each time Bash is started.
[File locations](#File-locations)
----------------------------------
###
[`JULIA_BINDIR`](#JULIA_BINDIR)
The absolute path of the directory containing the Julia executable, which sets the global variable [`Sys.BINDIR`](../../base/constants/index#Base.Sys.BINDIR). If `$JULIA_BINDIR` is not set, then Julia determines the value `Sys.BINDIR` at run-time.
The executable itself is one of
```
$JULIA_BINDIR/julia
$JULIA_BINDIR/julia-debug
```
by default.
The global variable `Base.DATAROOTDIR` determines a relative path from `Sys.BINDIR` to the data directory associated with Julia. Then the path
```
$JULIA_BINDIR/$DATAROOTDIR/julia/base
```
determines the directory in which Julia initially searches for source files (via `Base.find_source_file()`).
Likewise, the global variable `Base.SYSCONFDIR` determines a relative path to the configuration file directory. Then Julia searches for a `startup.jl` file at
```
$JULIA_BINDIR/$SYSCONFDIR/julia/startup.jl
$JULIA_BINDIR/../etc/julia/startup.jl
```
by default (via `Base.load_julia_startup()`).
For example, a Linux installation with a Julia executable located at `/bin/julia`, a `DATAROOTDIR` of `../share`, and a `SYSCONFDIR` of `../etc` will have `JULIA_BINDIR` set to `/bin`, a source-file search path of
```
/share/julia/base
```
and a global configuration search path of
```
/etc/julia/startup.jl
```
###
[`JULIA_PROJECT`](#JULIA_PROJECT)
A directory path that indicates which project should be the initial active project. Setting this environment variable has the same effect as specifying the `--project` start-up option, but `--project` has higher precedence. If the variable is set to `@.` then Julia tries to find a project directory that contains `Project.toml` or `JuliaProject.toml` file from the current directory and its parents. See also the chapter on [Code Loading](../code-loading/index#code-loading).
`JULIA_PROJECT` must be defined before starting julia; defining it in `startup.jl` is too late in the startup process.
###
[`JULIA_LOAD_PATH`](#JULIA_LOAD_PATH)
The `JULIA_LOAD_PATH` environment variable is used to populate the global Julia [`LOAD_PATH`](../../base/constants/index#Base.LOAD_PATH) variable, which determines which packages can be loaded via `import` and `using` (see [Code Loading](../code-loading/index#code-loading)).
Unlike the shell `PATH` variable, empty entries in `JULIA_LOAD_PATH` are expanded to the default value of `LOAD_PATH`, `["@", "@v#.#", "@stdlib"]` when populating `LOAD_PATH`. This allows easy appending, prepending, etc. of the load path value in shell scripts regardless of whether `JULIA_LOAD_PATH` is already set or not. For example, to prepend the directory `/foo/bar` to `LOAD_PATH` just do
```
export JULIA_LOAD_PATH="/foo/bar:$JULIA_LOAD_PATH"
```
If the `JULIA_LOAD_PATH` environment variable is already set, its old value will be prepended with `/foo/bar`. On the other hand, if `JULIA_LOAD_PATH` is not set, then it will be set to `/foo/bar:` which will expand to a `LOAD_PATH` value of `["/foo/bar", "@", "@v#.#", "@stdlib"]`. If `JULIA_LOAD_PATH` is set to the empty string, it expands to an empty `LOAD_PATH` array. In other words, the empty string is interpreted as a zero-element array, not a one-element array of the empty string. This behavior was chosen so that it would be possible to set an empty load path via the environment variable. If you want the default load path, either unset the environment variable or if it must have a value, set it to the string `:`.
On Windows, path elements are separated by the `;` character, as is the case with most path lists on Windows. Replace `:` with `;` in the above paragraph.
###
[`JULIA_DEPOT_PATH`](#JULIA_DEPOT_PATH)
The `JULIA_DEPOT_PATH` environment variable is used to populate the global Julia [`DEPOT_PATH`](../../base/constants/index#Base.DEPOT_PATH) variable, which controls where the package manager, as well as Julia's code loading mechanisms, look for package registries, installed packages, named environments, repo clones, cached compiled package images, configuration files, and the default location of the REPL's history file.
Unlike the shell `PATH` variable but similar to `JULIA_LOAD_PATH`, empty entries in `JULIA_DEPOT_PATH` are expanded to the default value of `DEPOT_PATH`. This allows easy appending, prepending, etc. of the depot path value in shell scripts regardless of whether `JULIA_DEPOT_PATH` is already set or not. For example, to prepend the directory `/foo/bar` to `DEPOT_PATH` just do
```
export JULIA_DEPOT_PATH="/foo/bar:$JULIA_DEPOT_PATH"
```
If the `JULIA_DEPOT_PATH` environment variable is already set, its old value will be prepended with `/foo/bar`. On the other hand, if `JULIA_DEPOT_PATH` is not set, then it will be set to `/foo/bar:` which will have the effect of prepending `/foo/bar` to the default depot path. If `JULIA_DEPOT_PATH` is set to the empty string, it expands to an empty `DEPOT_PATH` array. In other words, the empty string is interpreted as a zero-element array, not a one-element array of the empty string. This behavior was chosen so that it would be possible to set an empty depot path via the environment variable. If you want the default depot path, either unset the environment variable or if it must have a value, set it to the string `:`.
On Windows, path elements are separated by the `;` character, as is the case with most path lists on Windows. Replace `:` with `;` in the above paragraph.
###
[`JULIA_HISTORY`](#JULIA_HISTORY)
The absolute path `REPL.find_hist_file()` of the REPL's history file. If `$JULIA_HISTORY` is not set, then `REPL.find_hist_file()` defaults to
```
$(DEPOT_PATH[1])/logs/repl_history.jl
```
###
[`JULIA_MAX_NUM_PRECOMPILE_FILES`](#JULIA_MAX_NUM_PRECOMPILE_FILES)
Sets the maximum number of different instances of a single package that are to be stored in the precompile cache (default = 10).
[Pkg.jl](#Pkg.jl)
------------------
###
[`JULIA_CI`](#JULIA_CI)
If set to `true`, this indicates to the package server that any package operations are part of a continuous integration (CI) system for the purposes of gathering package usage statistics.
###
[`JULIA_NUM_PRECOMPILE_TASKS`](#JULIA_NUM_PRECOMPILE_TASKS)
The number of parallel tasks to use when precompiling packages. See [`Pkg.precompile`](https://pkgdocs.julialang.org/v1/api/#Pkg.precompile).
###
[`JULIA_PKG_DEVDIR`](#JULIA_PKG_DEVDIR)
The default directory used by [`Pkg.develop`](https://pkgdocs.julialang.org/v1/api/#Pkg.develop) for downloading packages.
###
[`JULIA_PKG_IGNORE_HASHES`](#JULIA_PKG_IGNORE_HASHES)
If set to `1`, this will ignore incorrect hashes in artifacts. This should be used carefully, as it disables verification of downloads, but can resolve issues when moving files across different types of file systems. See [Pkg.jl issue #2317](https://github.com/JuliaLang/Pkg.jl/issues/2317) for more details.
This is only supported in Julia 1.6 and above.
###
[`JULIA_PKG_OFFLINE`](#JULIA_PKG_OFFLINE)
If set to `true`, this will enable offline mode: see [`Pkg.offline`](https://pkgdocs.julialang.org/v1/api/#Pkg.offline).
Pkg's offline mode requires Julia 1.5 or later.
###
[`JULIA_PKG_PRECOMPILE_AUTO`](#JULIA_PKG_PRECOMPILE_AUTO)
If set to `0`, this will disable automatic precompilation by package actions which change the manifest. See [`Pkg.precompile`](https://pkgdocs.julialang.org/v1/api/#Pkg.precompile).
###
[`JULIA_PKG_SERVER`](#JULIA_PKG_SERVER)
Specifies the URL of the package registry to use. By default, `Pkg` uses `https://pkg.julialang.org` to fetch Julia packages. In addition, you can disable the use of the PkgServer protocol, and instead access the packages directly from their hosts (GitHub, GitLab, etc.) by setting: `export JULIA_PKG_SERVER=""`
###
[`JULIA_PKG_SERVER_REGISTRY_PREFERENCE`](#JULIA_PKG_SERVER_REGISTRY_PREFERENCE)
Specifies the preferred registry flavor. Currently supported values are `conservative` (the default), which will only publish resources that have been processed by the storage server (and thereby have a higher probability of being available from the PkgServers), whereas `eager` will publish registries whose resources have not necessarily been processed by the storage servers. Users behind restrictive firewalls that do not allow downloading from arbitrary servers should not use the `eager` flavor.
This only affects Julia 1.7 and above.
###
[`JULIA_PKG_UNPACK_REGISTRY`](#JULIA_PKG_UNPACK_REGISTRY)
If set to `true`, this will unpack the registry instead of storing it as a compressed tarball.
This only affects Julia 1.7 and above. Earlier versions will always unpack the registry.
###
[`JULIA_PKG_USE_CLI_GIT`](#JULIA_PKG_USE_CLI_GIT)
If set to `true`, Pkg operations which use the git protocol will use an external `git` executable instead of the default libgit2 library.
Use of the `git` executable is only supported on Julia 1.7 and above.
###
[`JULIA_PKGRESOLVE_ACCURACY`](#JULIA_PKGRESOLVE_ACCURACY)
The accuracy of the package resolver. This should be a positive integer, the default is `1`.
[Network transport](#Network-transport)
----------------------------------------
###
[`JULIA_NO_VERIFY_HOSTS` / `JULIA_SSL_NO_VERIFY_HOSTS` / `JULIA_SSH_NO_VERIFY_HOSTS` / `JULIA_ALWAYS_VERIFY_HOSTS`](#JULIA_NO_VERIFY_HOSTS-/-JULIA_SSL_NO_VERIFY_HOSTS-/-JULIA_SSH_NO_VERIFY_HOSTS-/-JULIA_ALWAYS_VERIFY_HOSTS)
Specify hosts whose identity should or should not be verified for specific transport layers. See [`NetworkOptions.verify_host`](https://github.com/JuliaLang/NetworkOptions.jl#verify_host)
###
[`JULIA_SSL_CA_ROOTS_PATH`](#JULIA_SSL_CA_ROOTS_PATH)
Specify the file or directory containing the certificate authority roots. See [`NetworkOptions.ca_roots`](https://github.com/JuliaLang/NetworkOptions.jl#ca_roots)
[External applications](#External-applications)
------------------------------------------------
###
[`JULIA_SHELL`](#JULIA_SHELL)
The absolute path of the shell with which Julia should execute external commands (via `Base.repl_cmd()`). Defaults to the environment variable `$SHELL`, and falls back to `/bin/sh` if `$SHELL` is unset.
On Windows, this environment variable is ignored, and external commands are executed directly.
###
[`JULIA_EDITOR`](#JULIA_EDITOR)
The editor returned by `InteractiveUtils.editor()` and used in, e.g., [`InteractiveUtils.edit`](#), referring to the command of the preferred editor, for instance `vim`.
`$JULIA_EDITOR` takes precedence over `$VISUAL`, which in turn takes precedence over `$EDITOR`. If none of these environment variables is set, then the editor is taken to be `open` on Windows and OS X, or `/etc/alternatives/editor` if it exists, or `emacs` otherwise.
To use Visual Studio Code on Windows, set `$JULIA_EDITOR` to `code.cmd`.
[Parallelization](#Parallelization)
------------------------------------
###
[`JULIA_CPU_THREADS`](#JULIA_CPU_THREADS)
Overrides the global variable [`Base.Sys.CPU_THREADS`](../../base/constants/index#Base.Sys.CPU_THREADS), the number of logical CPU cores available.
###
[`JULIA_WORKER_TIMEOUT`](#JULIA_WORKER_TIMEOUT)
A [`Float64`](../../base/numbers/index#Core.Float64) that sets the value of `Distributed.worker_timeout()` (default: `60.0`). This function gives the number of seconds a worker process will wait for a master process to establish a connection before dying.
###
[`JULIA_NUM_THREADS`](#JULIA_NUM_THREADS)
An unsigned 64-bit integer (`uint64_t`) that sets the maximum number of threads available to Julia. If `$JULIA_NUM_THREADS` is not positive or is not set, or if the number of CPU threads cannot be determined through system calls, then the number of threads is set to `1`.
If `$JULIA_NUM_THREADS` is set to `auto`, then the number of threads will be set to the number of CPU threads.
`JULIA_NUM_THREADS` must be defined before starting julia; defining it in `startup.jl` is too late in the startup process.
In Julia 1.5 and above the number of threads can also be specified on startup using the `-t`/`--threads` command line argument.
The `auto` value for `$JULIA_NUM_THREADS` requires Julia 1.7 or above.
###
[`JULIA_THREAD_SLEEP_THRESHOLD`](#JULIA_THREAD_SLEEP_THRESHOLD)
If set to a string that starts with the case-insensitive substring `"infinite"`, then spinning threads never sleep. Otherwise, `$JULIA_THREAD_SLEEP_THRESHOLD` is interpreted as an unsigned 64-bit integer (`uint64_t`) and gives, in nanoseconds, the amount of time after which spinning threads should sleep.
###
[`JULIA_EXCLUSIVE`](#JULIA_EXCLUSIVE)
If set to anything besides `0`, then Julia's thread policy is consistent with running on a dedicated machine: the master thread is on proc 0, and threads are affinitized. Otherwise, Julia lets the operating system handle thread policy.
[REPL formatting](#REPL-formatting)
------------------------------------
Environment variables that determine how REPL output should be formatted at the terminal. Generally, these variables should be set to [ANSI terminal escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code). Julia provides a high-level interface with much of the same functionality; see the section on [The Julia REPL](../../stdlib/repl/index#The-Julia-REPL).
###
[`JULIA_ERROR_COLOR`](#JULIA_ERROR_COLOR)
The formatting `Base.error_color()` (default: light red, `"\033[91m"`) that errors should have at the terminal.
###
[`JULIA_WARN_COLOR`](#JULIA_WARN_COLOR)
The formatting `Base.warn_color()` (default: yellow, `"\033[93m"`) that warnings should have at the terminal.
###
[`JULIA_INFO_COLOR`](#JULIA_INFO_COLOR)
The formatting `Base.info_color()` (default: cyan, `"\033[36m"`) that info should have at the terminal.
###
[`JULIA_INPUT_COLOR`](#JULIA_INPUT_COLOR)
The formatting `Base.input_color()` (default: normal, `"\033[0m"`) that input should have at the terminal.
###
[`JULIA_ANSWER_COLOR`](#JULIA_ANSWER_COLOR)
The formatting `Base.answer_color()` (default: normal, `"\033[0m"`) that output should have at the terminal.
[Debugging and profiling](#Debugging-and-profiling)
----------------------------------------------------
###
[`JULIA_DEBUG`](#JULIA_DEBUG)
Enable debug logging for a file or module, see [`Logging`](../../stdlib/logging/index#man-logging) for more information.
###
[`JULIA_GC_ALLOC_POOL`, `JULIA_GC_ALLOC_OTHER`, `JULIA_GC_ALLOC_PRINT`](#JULIA_GC_ALLOC_POOL,-JULIA_GC_ALLOC_OTHER,-JULIA_GC_ALLOC_PRINT)
If set, these environment variables take strings that optionally start with the character `'r'`, followed by a string interpolation of a colon-separated list of three signed 64-bit integers (`int64_t`). This triple of integers `a:b:c` represents the arithmetic sequence `a`, `a + b`, `a + 2*b`, ... `c`.
* If it's the `n`th time that `jl_gc_pool_alloc()` has been called, and `n` belongs to the arithmetic sequence represented by `$JULIA_GC_ALLOC_POOL`, then garbage collection is forced.
* If it's the `n`th time that `maybe_collect()` has been called, and `n` belongs to the arithmetic sequence represented by `$JULIA_GC_ALLOC_OTHER`, then garbage collection is forced.
* If it's the `n`th time that `jl_gc_collect()` has been called, and `n` belongs to the arithmetic sequence represented by `$JULIA_GC_ALLOC_PRINT`, then counts for the number of calls to `jl_gc_pool_alloc()` and `maybe_collect()` are printed.
If the value of the environment variable begins with the character `'r'`, then the interval between garbage collection events is randomized.
These environment variables only have an effect if Julia was compiled with garbage-collection debugging (that is, if `WITH_GC_DEBUG_ENV` is set to `1` in the build configuration).
###
[`JULIA_GC_NO_GENERATIONAL`](#JULIA_GC_NO_GENERATIONAL)
If set to anything besides `0`, then the Julia garbage collector never performs "quick sweeps" of memory.
This environment variable only has an effect if Julia was compiled with garbage-collection debugging (that is, if `WITH_GC_DEBUG_ENV` is set to `1` in the build configuration).
###
[`JULIA_GC_WAIT_FOR_DEBUGGER`](#JULIA_GC_WAIT_FOR_DEBUGGER)
If set to anything besides `0`, then the Julia garbage collector will wait for a debugger to attach instead of aborting whenever there's a critical error.
This environment variable only has an effect if Julia was compiled with garbage-collection debugging (that is, if `WITH_GC_DEBUG_ENV` is set to `1` in the build configuration).
###
[`ENABLE_JITPROFILING`](#ENABLE_JITPROFILING)
If set to anything besides `0`, then the compiler will create and register an event listener for just-in-time (JIT) profiling.
This environment variable only has an effect if Julia was compiled with JIT profiling support, using either
* Intel's [VTune™ Amplifier](https://software.intel.com/en-us/vtune) (`USE_INTEL_JITEVENTS` set to `1` in the build configuration), or
* [OProfile](https://oprofile.sourceforge.io/news/) (`USE_OPROFILE_JITEVENTS` set to `1` in the build configuration).
* [Perf](https://perf.wiki.kernel.org) (`USE_PERF_JITEVENTS` set to `1` in the build configuration). This integration is enabled by default.
###
[`ENABLE_GDBLISTENER`](#ENABLE_GDBLISTENER)
If set to anything besides `0` enables GDB registration of Julia code on release builds. On debug builds of Julia this is always enabled. Recommended to use with `-g 2`.
###
[`JULIA_LLVM_ARGS`](#JULIA_LLVM_ARGS)
Arguments to be passed to the LLVM backend.
julia Methods Methods
=======
Recall from [Functions](../functions/index#man-functions) that a function is an object that maps a tuple of arguments to a return value, or throws an exception if no appropriate value can be returned. It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding two floating-point numbers, both of which are distinct from adding an integer to a floating-point number. Despite their implementation differences, these operations all fall under the general concept of "addition". Accordingly, in Julia, these behaviors all belong to a single object: the `+` function.
To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a function is called a *method*. Thus far, we have presented only examples of functions defined with a single method, applicable to all types of arguments. However, the signatures of method definitions can be annotated to indicate the types of arguments in addition to their number, and more than a single method definition may be provided. When a function is applied to a particular tuple of arguments, the most specific method applicable to those arguments is applied. Thus, the overall behavior of a function is a patchwork of the behaviors of its various method definitions. If the patchwork is well designed, even though the implementations of the methods may be quite different, the outward behavior of the function will appear seamless and consistent.
The choice of which method to execute when a function is applied is called *dispatch*. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. [[1]](#footnote-1) Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as [multiple dispatch](https://en.wikipedia.org/wiki/Multiple_dispatch). Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to "belong" to one argument more than any of the others: does the addition operation in `x + y` belong to `x` any more than it does to `y`? The implementation of a mathematical operator generally depends on the types of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a powerful and convenient paradigm for structuring and organizing programs.
All the examples in this chapter assume that you are defining methods for a function in the *same* module. If you want to add methods to a function in *another* module, you have to `import` it or use the name qualified with module names. See the section on [namespace management](../modules/index#namespace-management).
[Defining Methods](#Defining-Methods)
--------------------------------------
Until now, we have, in our examples, defined only functions with a single method having unconstrained argument types. Such functions behave just like they would in traditional dynamically typed languages. Nevertheless, we have used multiple dispatch and methods almost continually without being aware of it: all of Julia's standard functions and operators, like the aforementioned `+` function, have many methods defining their behavior over various possible combinations of argument type and count.
When defining a function, one can optionally constrain the types of parameters it is applicable to, using the `::` type-assertion operator, introduced in the section on [Composite Types](../types/index#Composite-Types):
```
julia> f(x::Float64, y::Float64) = 2x + y
f (generic function with 1 method)
```
This function definition applies only to calls where `x` and `y` are both values of type [`Float64`](../../base/numbers/index#Core.Float64):
```
julia> f(2.0, 3.0)
7.0
```
Applying it to any other types of arguments will result in a [`MethodError`](../../base/base/index#Core.MethodError):
```
julia> f(2.0, 3)
ERROR: MethodError: no method matching f(::Float64, ::Int64)
Closest candidates are:
f(::Float64, !Matched::Float64) at none:1
julia> f(Float32(2.0), 3.0)
ERROR: MethodError: no method matching f(::Float32, ::Float64)
Closest candidates are:
f(!Matched::Float64, ::Float64) at none:1
julia> f(2.0, "3.0")
ERROR: MethodError: no method matching f(::Float64, ::String)
Closest candidates are:
f(::Float64, !Matched::Float64) at none:1
julia> f("2.0", "3.0")
ERROR: MethodError: no method matching f(::String, ::String)
```
As you can see, the arguments must be precisely of type [`Float64`](../../base/numbers/index#Core.Float64). Other numeric types, such as integers or 32-bit floating-point values, are not automatically converted to 64-bit floating-point, nor are strings parsed as numbers. Because `Float64` is a concrete type and concrete types cannot be subclassed in Julia, such a definition can only be applied to arguments that are exactly of type `Float64`. It may often be useful, however, to write more general methods where the declared parameter types are abstract:
```
julia> f(x::Number, y::Number) = 2x - y
f (generic function with 2 methods)
julia> f(2.0, 3)
1.0
```
This method definition applies to any pair of arguments that are instances of [`Number`](../../base/numbers/index#Core.Number). They need not be of the same type, so long as they are each numeric values. The problem of handling disparate numeric types is delegated to the arithmetic operations in the expression `2x - y`.
To define a function with multiple methods, one simply defines the function multiple times, with different numbers and types of arguments. The first method definition for a function creates the function object, and subsequent method definitions add new methods to the existing function object. The most specific method definition matching the number and types of the arguments will be executed when the function is applied. Thus, the two method definitions above, taken together, define the behavior for `f` over all pairs of instances of the abstract type `Number` – but with a different behavior specific to pairs of [`Float64`](../../base/numbers/index#Core.Float64) values. If one of the arguments is a 64-bit float but the other one is not, then the `f(Float64,Float64)` method cannot be called and the more general `f(Number,Number)` method must be used:
```
julia> f(2.0, 3.0)
7.0
julia> f(2, 3.0)
1.0
julia> f(2.0, 3)
1.0
julia> f(2, 3)
1
```
The `2x + y` definition is only used in the first case, while the `2x - y` definition is used in the others. No automatic casting or conversion of function arguments is ever performed: all conversion in Julia is non-magical and completely explicit. [Conversion and Promotion](../conversion-and-promotion/index#conversion-and-promotion), however, shows how clever application of sufficiently advanced technology can be indistinguishable from magic. [[Clarke61]](#footnote-Clarke61)
For non-numeric values, and for fewer or more than two arguments, the function `f` remains undefined, and applying it will still result in a [`MethodError`](../../base/base/index#Core.MethodError):
```
julia> f("foo", 3)
ERROR: MethodError: no method matching f(::String, ::Int64)
Closest candidates are:
f(!Matched::Number, ::Number) at none:1
julia> f()
ERROR: MethodError: no method matching f()
Closest candidates are:
f(!Matched::Float64, !Matched::Float64) at none:1
f(!Matched::Number, !Matched::Number) at none:1
```
You can easily see which methods exist for a function by entering the function object itself in an interactive session:
```
julia> f
f (generic function with 2 methods)
```
This output tells us that `f` is a function object with two methods. To find out what the signatures of those methods are, use the [`methods`](../../base/base/index#Base.methods) function:
```
julia> methods(f)
# 2 methods for generic function "f":
[1] f(x::Float64, y::Float64) in Main at none:1
[2] f(x::Number, y::Number) in Main at none:1
```
which shows that `f` has two methods, one taking two `Float64` arguments and one taking arguments of type `Number`. It also indicates the file and line number where the methods were defined: because these methods were defined at the REPL, we get the apparent line number `none:1`.
In the absence of a type declaration with `::`, the type of a method parameter is `Any` by default, meaning that it is unconstrained since all values in Julia are instances of the abstract type `Any`. Thus, we can define a catch-all method for `f` like so:
```
julia> f(x,y) = println("Whoa there, Nelly.")
f (generic function with 3 methods)
julia> methods(f)
# 3 methods for generic function "f":
[1] f(x::Float64, y::Float64) in Main at none:1
[2] f(x::Number, y::Number) in Main at none:1
[3] f(x, y) in Main at none:1
julia> f("foo", 1)
Whoa there, Nelly.
```
This catch-all is less specific than any other possible method definition for a pair of parameter values, so it will only be called on pairs of arguments to which no other method definition applies.
Note that in the signature of the third method, there is no type specified for the arguments `x` and `y`. This is a shortened way of expressing `f(x::Any, y::Any)`.
Although it seems a simple concept, multiple dispatch on the types of values is perhaps the single most powerful and central feature of the Julia language. Core operations typically have dozens of methods:
```
julia> methods(+)
# 180 methods for generic function "+":
[1] +(x::Bool, z::Complex{Bool}) in Base at complex.jl:227
[2] +(x::Bool, y::Bool) in Base at bool.jl:89
[3] +(x::Bool) in Base at bool.jl:86
[4] +(x::Bool, y::T) where T<:AbstractFloat in Base at bool.jl:96
[5] +(x::Bool, z::Complex) in Base at complex.jl:234
[6] +(a::Float16, b::Float16) in Base at float.jl:373
[7] +(x::Float32, y::Float32) in Base at float.jl:375
[8] +(x::Float64, y::Float64) in Base at float.jl:376
[9] +(z::Complex{Bool}, x::Bool) in Base at complex.jl:228
[10] +(z::Complex{Bool}, x::Real) in Base at complex.jl:242
[11] +(x::Char, y::Integer) in Base at char.jl:40
[12] +(c::BigInt, x::BigFloat) in Base.MPFR at mpfr.jl:307
[13] +(a::BigInt, b::BigInt, c::BigInt, d::BigInt, e::BigInt) in Base.GMP at gmp.jl:392
[14] +(a::BigInt, b::BigInt, c::BigInt, d::BigInt) in Base.GMP at gmp.jl:391
[15] +(a::BigInt, b::BigInt, c::BigInt) in Base.GMP at gmp.jl:390
[16] +(x::BigInt, y::BigInt) in Base.GMP at gmp.jl:361
[17] +(x::BigInt, c::Union{UInt16, UInt32, UInt64, UInt8}) in Base.GMP at gmp.jl:398
...
[180] +(a, b, c, xs...) in Base at operators.jl:424
```
Multiple dispatch together with the flexible parametric type system give Julia its ability to abstractly express high-level algorithms decoupled from implementation details, yet generate efficient, specialized code to handle each case at run time.
[Method Ambiguities](#man-ambiguities)
---------------------------------------
It is possible to define a set of function methods such that there is no unique most specific method applicable to some combinations of arguments:
```
julia> g(x::Float64, y) = 2x + y
g (generic function with 1 method)
julia> g(x, y::Float64) = x + 2y
g (generic function with 2 methods)
julia> g(2.0, 3)
7.0
julia> g(2, 3.0)
8.0
julia> g(2.0, 3.0)
ERROR: MethodError: g(::Float64, ::Float64) is ambiguous. Candidates:
g(x::Float64, y) in Main at none:1
g(x, y::Float64) in Main at none:1
Possible fix, define
g(::Float64, ::Float64)
```
Here the call `g(2.0, 3.0)` could be handled by either the `g(Float64, Any)` or the `g(Any, Float64)` method, and neither is more specific than the other. In such cases, Julia raises a [`MethodError`](../../base/base/index#Core.MethodError) rather than arbitrarily picking a method. You can avoid method ambiguities by specifying an appropriate method for the intersection case:
```
julia> g(x::Float64, y::Float64) = 2x + 2y
g (generic function with 3 methods)
julia> g(2.0, 3)
7.0
julia> g(2, 3.0)
8.0
julia> g(2.0, 3.0)
10.0
```
It is recommended that the disambiguating method be defined first, since otherwise the ambiguity exists, if transiently, until the more specific method is defined.
In more complex cases, resolving method ambiguities involves a certain element of design; this topic is explored further [below](#man-method-design-ambiguities).
[Parametric Methods](#Parametric-Methods)
------------------------------------------
Method definitions can optionally have type parameters qualifying the signature:
```
julia> same_type(x::T, y::T) where {T} = true
same_type (generic function with 1 method)
julia> same_type(x,y) = false
same_type (generic function with 2 methods)
```
The first method applies whenever both arguments are of the same concrete type, regardless of what type that is, while the second method acts as a catch-all, covering all other cases. Thus, overall, this defines a boolean function that checks whether its two arguments are of the same type:
```
julia> same_type(1, 2)
true
julia> same_type(1, 2.0)
false
julia> same_type(1.0, 2.0)
true
julia> same_type("foo", 2.0)
false
julia> same_type("foo", "bar")
true
julia> same_type(Int32(1), Int64(2))
false
```
Such definitions correspond to methods whose type signatures are `UnionAll` types (see [UnionAll Types](../types/index#UnionAll-Types)).
This kind of definition of function behavior by dispatch is quite common – idiomatic, even – in Julia. Method type parameters are not restricted to being used as the types of arguments: they can be used anywhere a value would be in the signature of the function or body of the function. Here's an example where the method type parameter `T` is used as the type parameter to the parametric type `Vector{T}` in the method signature:
```
julia> myappend(v::Vector{T}, x::T) where {T} = [v..., x]
myappend (generic function with 1 method)
julia> myappend([1,2,3],4)
4-element Vector{Int64}:
1
2
3
4
julia> myappend([1,2,3],2.5)
ERROR: MethodError: no method matching myappend(::Vector{Int64}, ::Float64)
Closest candidates are:
myappend(::Vector{T}, !Matched::T) where T at none:1
Stacktrace:
[...]
julia> myappend([1.0,2.0,3.0],4.0)
4-element Vector{Float64}:
1.0
2.0
3.0
4.0
julia> myappend([1.0,2.0,3.0],4)
ERROR: MethodError: no method matching myappend(::Vector{Float64}, ::Int64)
Closest candidates are:
myappend(::Vector{T}, !Matched::T) where T at none:1
Stacktrace:
[...]
```
As you can see, the type of the appended element must match the element type of the vector it is appended to, or else a [`MethodError`](../../base/base/index#Core.MethodError) is raised. In the following example, the method type parameter `T` is used as the return value:
```
julia> mytypeof(x::T) where {T} = T
mytypeof (generic function with 1 method)
julia> mytypeof(1)
Int64
julia> mytypeof(1.0)
Float64
```
Just as you can put subtype constraints on type parameters in type declarations (see [Parametric Types](../types/index#Parametric-Types)), you can also constrain type parameters of methods:
```
julia> same_type_numeric(x::T, y::T) where {T<:Number} = true
same_type_numeric (generic function with 1 method)
julia> same_type_numeric(x::Number, y::Number) = false
same_type_numeric (generic function with 2 methods)
julia> same_type_numeric(1, 2)
true
julia> same_type_numeric(1, 2.0)
false
julia> same_type_numeric(1.0, 2.0)
true
julia> same_type_numeric("foo", 2.0)
ERROR: MethodError: no method matching same_type_numeric(::String, ::Float64)
Closest candidates are:
same_type_numeric(!Matched::T, ::T) where T<:Number at none:1
same_type_numeric(!Matched::Number, ::Number) at none:1
julia> same_type_numeric("foo", "bar")
ERROR: MethodError: no method matching same_type_numeric(::String, ::String)
julia> same_type_numeric(Int32(1), Int64(2))
false
```
The `same_type_numeric` function behaves much like the `same_type` function defined above, but is only defined for pairs of numbers.
Parametric methods allow the same syntax as `where` expressions used to write types (see [UnionAll Types](../types/index#UnionAll-Types)). If there is only a single parameter, the enclosing curly braces (in `where {T}`) can be omitted, but are often preferred for clarity. Multiple parameters can be separated with commas, e.g. `where {T, S<:Real}`, or written using nested `where`, e.g. `where S<:Real where T`.
[Redefining Methods](#Redefining-Methods)
------------------------------------------
When redefining a method or adding new methods, it is important to realize that these changes don't take effect immediately. This is key to Julia's ability to statically infer and compile code to run fast, without the usual JIT tricks and overhead. Indeed, any new method definition won't be visible to the current runtime environment, including Tasks and Threads (and any previously defined `@generated` functions). Let's start with an example to see what this means:
```
julia> function tryeval()
@eval newfun() = 1
newfun()
end
tryeval (generic function with 1 method)
julia> tryeval()
ERROR: MethodError: no method matching newfun()
The applicable method may be too new: running in world age xxxx1, while current world is xxxx2.
Closest candidates are:
newfun() at none:1 (method too new to be called from this world context.)
in tryeval() at none:1
...
julia> newfun()
1
```
In this example, observe that the new definition for `newfun` has been created, but can't be immediately called. The new global is immediately visible to the `tryeval` function, so you could write `return newfun` (without parentheses). But neither you, nor any of your callers, nor the functions they call, or etc. can call this new method definition!
But there's an exception: future calls to `newfun` *from the REPL* work as expected, being able to both see and call the new definition of `newfun`.
However, future calls to `tryeval` will continue to see the definition of `newfun` as it was *at the previous statement at the REPL*, and thus before that call to `tryeval`.
You may want to try this for yourself to see how it works.
The implementation of this behavior is a "world age counter". This monotonically increasing value tracks each method definition operation. This allows describing "the set of method definitions visible to a given runtime environment" as a single number, or "world age". It also allows comparing the methods available in two worlds just by comparing their ordinal value. In the example above, we see that the "current world" (in which the method `newfun` exists), is one greater than the task-local "runtime world" that was fixed when the execution of `tryeval` started.
Sometimes it is necessary to get around this (for example, if you are implementing the above REPL). Fortunately, there is an easy solution: call the function using [`Base.invokelatest`](../../base/base/index#Base.invokelatest):
```
julia> function tryeval2()
@eval newfun2() = 2
Base.invokelatest(newfun2)
end
tryeval2 (generic function with 1 method)
julia> tryeval2()
2
```
Finally, let's take a look at some more complex examples where this rule comes into play. Define a function `f(x)`, which initially has one method:
```
julia> f(x) = "original definition"
f (generic function with 1 method)
```
Start some other operations that use `f(x)`:
```
julia> g(x) = f(x)
g (generic function with 1 method)
julia> t = @async f(wait()); yield();
```
Now we add some new methods to `f(x)`:
```
julia> f(x::Int) = "definition for Int"
f (generic function with 2 methods)
julia> f(x::Type{Int}) = "definition for Type{Int}"
f (generic function with 3 methods)
```
Compare how these results differ:
```
julia> f(1)
"definition for Int"
julia> g(1)
"definition for Int"
julia> fetch(schedule(t, 1))
"original definition"
julia> t = @async f(wait()); yield();
julia> fetch(schedule(t, 1))
"definition for Int"
```
[Design Patterns with Parametric Methods](#Design-Patterns-with-Parametric-Methods)
------------------------------------------------------------------------------------
While complex dispatch logic is not required for performance or usability, sometimes it can be the best way to express some algorithm. Here are a few common design patterns that come up sometimes when using dispatch in this way.
###
[Extracting the type parameter from a super-type](#Extracting-the-type-parameter-from-a-super-type)
Here is a correct code template for returning the element-type `T` of any arbitrary subtype of `AbstractArray` that has well-defined element type:
```
abstract type AbstractArray{T, N} end
eltype(::Type{<:AbstractArray{T}}) where {T} = T
```
using so-called triangular dispatch. Note that `UnionAll` types, for example `eltype(AbstractArray{T} where T <: Integer)`, do not match the above method. The implementation of `eltype` in `Base` adds a fallback method to `Any` for such cases.
One common mistake is to try and get the element-type by using introspection:
```
eltype_wrong(::Type{A}) where {A<:AbstractArray} = A.parameters[1]
```
However, it is not hard to construct cases where this will fail:
```
struct BitVector <: AbstractArray{Bool, 1}; end
```
Here we have created a type `BitVector` which has no parameters, but where the element-type is still fully specified, with `T` equal to `Bool`!
Another mistake is to try to walk up the type hierarchy using `supertype`:
```
eltype_wrong(::Type{AbstractArray{T}}) where {T} = T
eltype_wrong(::Type{AbstractArray{T, N}}) where {T, N} = T
eltype_wrong(::Type{A}) where {A<:AbstractArray} = eltype_wrong(supertype(A))
```
While this works for declared types, it fails for types without supertypes:
```
julia> eltype_wrong(Union{AbstractArray{Int}, AbstractArray{Float64}})
ERROR: MethodError: no method matching supertype(::Type{Union{AbstractArray{Float64,N} where N, AbstractArray{Int64,N} where N}})
Closest candidates are:
supertype(::DataType) at operators.jl:43
supertype(::UnionAll) at operators.jl:48
```
###
[Building a similar type with a different type parameter](#Building-a-similar-type-with-a-different-type-parameter)
When building generic code, there is often a need for constructing a similar object with some change made to the layout of the type, also necessitating a change of the type parameters. For instance, you might have some sort of abstract array with an arbitrary element type and want to write your computation on it with a specific element type. We must implement a method for each `AbstractArray{T}` subtype that describes how to compute this type transform. There is no general transform of one subtype into another subtype with a different parameter. (Quick review: do you see why this is?)
The subtypes of `AbstractArray` typically implement two methods to achieve this: A method to convert the input array to a subtype of a specific `AbstractArray{T, N}` abstract type; and a method to make a new uninitialized array with a specific element type. Sample implementations of these can be found in Julia Base. Here is a basic example usage of them, guaranteeing that `input` and `output` are of the same type:
```
input = convert(AbstractArray{Eltype}, input)
output = similar(input, Eltype)
```
As an extension of this, in cases where the algorithm needs a copy of the input array, [`convert`](../../base/base/index#Base.convert) is insufficient as the return value may alias the original input. Combining [`similar`](../../base/arrays/index#Base.similar) (to make the output array) and [`copyto!`](../../base/c/index#Base.copyto!) (to fill it with the input data) is a generic way to express the requirement for a mutable copy of the input argument:
```
copy_with_eltype(input, Eltype) = copyto!(similar(input, Eltype), input)
```
###
[Iterated dispatch](#Iterated-dispatch)
In order to dispatch a multi-level parametric argument list, often it is best to separate each level of dispatch into distinct functions. This may sound similar in approach to single-dispatch, but as we shall see below, it is still more flexible.
For example, trying to dispatch on the element-type of an array will often run into ambiguous situations. Instead, commonly code will dispatch first on the container type, then recurse down to a more specific method based on eltype. In most cases, the algorithms lend themselves conveniently to this hierarchical approach, while in other cases, this rigor must be resolved manually. This dispatching branching can be observed, for example, in the logic to sum two matrices:
```
# First dispatch selects the map algorithm for element-wise summation.
+(a::Matrix, b::Matrix) = map(+, a, b)
# Then dispatch handles each element and selects the appropriate
# common element type for the computation.
+(a, b) = +(promote(a, b)...)
# Once the elements have the same type, they can be added.
# For example, via primitive operations exposed by the processor.
+(a::Float64, b::Float64) = Core.add(a, b)
```
###
[Trait-based dispatch](#Trait-based-dispatch)
A natural extension to the iterated dispatch above is to add a layer to method selection that allows to dispatch on sets of types which are independent from the sets defined by the type hierarchy. We could construct such a set by writing out a `Union` of the types in question, but then this set would not be extensible as `Union`-types cannot be altered after creation. However, such an extensible set can be programmed with a design pattern often referred to as a ["Holy-trait"](https://github.com/JuliaLang/julia/issues/2345#issuecomment-54537633).
This pattern is implemented by defining a generic function which computes a different singleton value (or type) for each trait-set to which the function arguments may belong to. If this function is pure there is no impact on performance compared to normal dispatch.
The example in the previous section glossed over the implementation details of [`map`](../../base/collections/index#Base.map) and [`promote`](../../base/base/index#Base.promote), which both operate in terms of these traits. When iterating over a matrix, such as in the implementation of `map`, one important question is what order to use to traverse the data. When `AbstractArray` subtypes implement the [`Base.IndexStyle`](../../base/arrays/index#Base.IndexStyle) trait, other functions such as `map` can dispatch on this information to pick the best algorithm (see [Abstract Array Interface](../interfaces/index#man-interface-array)). This means that each subtype does not need to implement a custom version of `map`, since the generic definitions + trait classes will enable the system to select the fastest version. Here is a toy implementation of `map` illustrating the trait-based dispatch:
```
map(f, a::AbstractArray, b::AbstractArray) = map(Base.IndexStyle(a, b), f, a, b)
# generic implementation:
map(::Base.IndexCartesian, f, a::AbstractArray, b::AbstractArray) = ...
# linear-indexing implementation (faster)
map(::Base.IndexLinear, f, a::AbstractArray, b::AbstractArray) = ...
```
This trait-based approach is also present in the [`promote`](../../base/base/index#Base.promote) mechanism employed by the scalar `+`. It uses [`promote_type`](../../base/base/index#Base.promote_type), which returns the optimal common type to compute the operation given the two types of the operands. This makes it possible to reduce the problem of implementing every function for every pair of possible type arguments, to the much smaller problem of implementing a conversion operation from each type to a common type, plus a table of preferred pair-wise promotion rules.
###
[Output-type computation](#Output-type-computation)
The discussion of trait-based promotion provides a transition into our next design pattern: computing the output element type for a matrix operation.
For implementing primitive operations, such as addition, we use the [`promote_type`](../../base/base/index#Base.promote_type) function to compute the desired output type. (As before, we saw this at work in the `promote` call in the call to `+`).
For more complex functions on matrices, it may be necessary to compute the expected return type for a more complex sequence of operations. This is often performed by the following steps:
1. Write a small function `op` that expresses the set of operations performed by the kernel of the algorithm.
2. Compute the element type `R` of the result matrix as `promote_op(op, argument_types...)`, where `argument_types` is computed from `eltype` applied to each input array.
3. Build the output matrix as `similar(R, dims)`, where `dims` are the desired dimensions of the output array.
For a more specific example, a generic square-matrix multiply pseudo-code might look like:
```
function matmul(a::AbstractMatrix, b::AbstractMatrix)
op = (ai, bi) -> ai * bi + ai * bi
## this is insufficient because it assumes `one(eltype(a))` is constructable:
# R = typeof(op(one(eltype(a)), one(eltype(b))))
## this fails because it assumes `a[1]` exists and is representative of all elements of the array
# R = typeof(op(a[1], b[1]))
## this is incorrect because it assumes that `+` calls `promote_type`
## but this is not true for some types, such as Bool:
# R = promote_type(ai, bi)
# this is wrong, since depending on the return value
# of type-inference is very brittle (as well as not being optimizable):
# R = Base.return_types(op, (eltype(a), eltype(b)))
## but, finally, this works:
R = promote_op(op, eltype(a), eltype(b))
## although sometimes it may give a larger type than desired
## it will always give a correct type
output = similar(b, R, (size(a, 1), size(b, 2)))
if size(a, 2) > 0
for j in 1:size(b, 2)
for i in 1:size(a, 1)
## here we don't use `ab = zero(R)`,
## since `R` might be `Any` and `zero(Any)` is not defined
## we also must declare `ab::R` to make the type of `ab` constant in the loop,
## since it is possible that typeof(a * b) != typeof(a * b + a * b) == R
ab::R = a[i, 1] * b[1, j]
for k in 2:size(a, 2)
ab += a[i, k] * b[k, j]
end
output[i, j] = ab
end
end
end
return output
end
```
###
[Separate convert and kernel logic](#Separate-convert-and-kernel-logic)
One way to significantly cut down on compile-times and testing complexity is to isolate the logic for converting to the desired type and the computation. This lets the compiler specialize and inline the conversion logic independent from the rest of the body of the larger kernel.
This is a common pattern seen when converting from a larger class of types to the one specific argument type that is actually supported by the algorithm:
```
complexfunction(arg::Int) = ...
complexfunction(arg::Any) = complexfunction(convert(Int, arg))
matmul(a::T, b::T) = ...
matmul(a, b) = matmul(promote(a, b)...)
```
[Parametrically-constrained Varargs methods](#Parametrically-constrained-Varargs-methods)
------------------------------------------------------------------------------------------
Function parameters can also be used to constrain the number of arguments that may be supplied to a "varargs" function ([Varargs Functions](../functions/index#Varargs-Functions)). The notation `Vararg{T,N}` is used to indicate such a constraint. For example:
```
julia> bar(a,b,x::Vararg{Any,2}) = (a,b,x)
bar (generic function with 1 method)
julia> bar(1,2,3)
ERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64)
Closest candidates are:
bar(::Any, ::Any, ::Any, !Matched::Any) at none:1
julia> bar(1,2,3,4)
(1, 2, (3, 4))
julia> bar(1,2,3,4,5)
ERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64, ::Int64, ::Int64)
Closest candidates are:
bar(::Any, ::Any, ::Any, ::Any) at none:1
```
More usefully, it is possible to constrain varargs methods by a parameter. For example:
```
function getindex(A::AbstractArray{T,N}, indices::Vararg{Number,N}) where {T,N}
```
would be called only when the number of `indices` matches the dimensionality of the array.
When only the type of supplied arguments needs to be constrained `Vararg{T}` can be equivalently written as `T...`. For instance `f(x::Int...) = x` is a shorthand for `f(x::Vararg{Int}) = x`.
[Note on Optional and keyword Arguments](#Note-on-Optional-and-keyword-Arguments)
----------------------------------------------------------------------------------
As mentioned briefly in [Functions](../functions/index#man-functions), optional arguments are implemented as syntax for multiple method definitions. For example, this definition:
```
f(a=1,b=2) = a+2b
```
translates to the following three methods:
```
f(a,b) = a+2b
f(a) = f(a,2)
f() = f(1,2)
```
This means that calling `f()` is equivalent to calling `f(1,2)`. In this case the result is `5`, because `f(1,2)` invokes the first method of `f` above. However, this need not always be the case. If you define a fourth method that is more specialized for integers:
```
f(a::Int,b::Int) = a-2b
```
then the result of both `f()` and `f(1,2)` is `-3`. In other words, optional arguments are tied to a function, not to any specific method of that function. It depends on the types of the optional arguments which method is invoked. When optional arguments are defined in terms of a global variable, the type of the optional argument may even change at run-time.
Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.
[Function-like objects](#Function-like-objects)
------------------------------------------------
Methods are associated with types, so it is possible to make any arbitrary Julia object "callable" by adding methods to its type. (Such "callable" objects are sometimes called "functors.")
For example, you can define a type that stores the coefficients of a polynomial, but behaves like a function evaluating the polynomial:
```
julia> struct Polynomial{R}
coeffs::Vector{R}
end
julia> function (p::Polynomial)(x)
v = p.coeffs[end]
for i = (length(p.coeffs)-1):-1:1
v = v*x + p.coeffs[i]
end
return v
end
julia> (p::Polynomial)() = p(5)
```
Notice that the function is specified by type instead of by name. As with normal functions there is a terse syntax form. In the function body, `p` will refer to the object that was called. A `Polynomial` can be used as follows:
```
julia> p = Polynomial([1,10,100])
Polynomial{Int64}([1, 10, 100])
julia> p(3)
931
julia> p()
2551
```
This mechanism is also the key to how type constructors and closures (inner functions that refer to their surrounding environment) work in Julia.
[Empty generic functions](#Empty-generic-functions)
----------------------------------------------------
Occasionally it is useful to introduce a generic function without yet adding methods. This can be used to separate interface definitions from implementations. It might also be done for the purpose of documentation or code readability. The syntax for this is an empty `function` block without a tuple of arguments:
```
function emptyfunc end
```
[Method design and the avoidance of ambiguities](#man-method-design-ambiguities)
---------------------------------------------------------------------------------
Julia's method polymorphism is one of its most powerful features, yet exploiting this power can pose design challenges. In particular, in more complex method hierarchies it is not uncommon for [ambiguities](#man-ambiguities) to arise.
Above, it was pointed out that one can resolve ambiguities like
```
f(x, y::Int) = 1
f(x::Int, y) = 2
```
by defining a method
```
f(x::Int, y::Int) = 3
```
This is often the right strategy; however, there are circumstances where following this advice mindlessly can be counterproductive. In particular, the more methods a generic function has, the more possibilities there are for ambiguities. When your method hierarchies get more complicated than this simple example, it can be worth your while to think carefully about alternative strategies.
Below we discuss particular challenges and some alternative ways to resolve such issues.
###
[Tuple and NTuple arguments](#Tuple-and-NTuple-arguments)
`Tuple` (and `NTuple`) arguments present special challenges. For example,
```
f(x::NTuple{N,Int}) where {N} = 1
f(x::NTuple{N,Float64}) where {N} = 2
```
are ambiguous because of the possibility that `N == 0`: there are no elements to determine whether the `Int` or `Float64` variant should be called. To resolve the ambiguity, one approach is define a method for the empty tuple:
```
f(x::Tuple{}) = 3
```
Alternatively, for all methods but one you can insist that there is at least one element in the tuple:
```
f(x::NTuple{N,Int}) where {N} = 1 # this is the fallback
f(x::Tuple{Float64, Vararg{Float64}}) = 2 # this requires at least one Float64
```
###
[Orthogonalize your design](#man-methods-orthogonalize)
When you might be tempted to dispatch on two or more arguments, consider whether a "wrapper" function might make for a simpler design. For example, instead of writing multiple variants:
```
f(x::A, y::A) = ...
f(x::A, y::B) = ...
f(x::B, y::A) = ...
f(x::B, y::B) = ...
```
you might consider defining
```
f(x::A, y::A) = ...
f(x, y) = f(g(x), g(y))
```
where `g` converts the argument to type `A`. This is a very specific example of the more general principle of [orthogonal design](https://en.wikipedia.org/wiki/Orthogonality_(programming)), in which separate concepts are assigned to separate methods. Here, `g` will most likely need a fallback definition
```
g(x::A) = x
```
A related strategy exploits `promote` to bring `x` and `y` to a common type:
```
f(x::T, y::T) where {T} = ...
f(x, y) = f(promote(x, y)...)
```
One risk with this design is the possibility that if there is no suitable promotion method converting `x` and `y` to the same type, the second method will recurse on itself infinitely and trigger a stack overflow.
###
[Dispatch on one argument at a time](#Dispatch-on-one-argument-at-a-time)
If you need to dispatch on multiple arguments, and there are many fallbacks with too many combinations to make it practical to define all possible variants, then consider introducing a "name cascade" where (for example) you dispatch on the first argument and then call an internal method:
```
f(x::A, y) = _fA(x, y)
f(x::B, y) = _fB(x, y)
```
Then the internal methods `_fA` and `_fB` can dispatch on `y` without concern about ambiguities with each other with respect to `x`.
Be aware that this strategy has at least one major disadvantage: in many cases, it is not possible for users to further customize the behavior of `f` by defining further specializations of your exported function `f`. Instead, they have to define specializations for your internal methods `_fA` and `_fB`, and this blurs the lines between exported and internal methods.
###
[Abstract containers and element types](#Abstract-containers-and-element-types)
Where possible, try to avoid defining methods that dispatch on specific element types of abstract containers. For example,
```
-(A::AbstractArray{T}, b::Date) where {T<:Date}
```
generates ambiguities for anyone who defines a method
```
-(A::MyArrayType{T}, b::T) where {T}
```
The best approach is to avoid defining *either* of these methods: instead, rely on a generic method `-(A::AbstractArray, b)` and make sure this method is implemented with generic calls (like `similar` and `-`) that do the right thing for each container type and element type *separately*. This is just a more complex variant of the advice to [orthogonalize](#man-methods-orthogonalize) your methods.
When this approach is not possible, it may be worth starting a discussion with other developers about resolving the ambiguity; just because one method was defined first does not necessarily mean that it can't be modified or eliminated. As a last resort, one developer can define the "band-aid" method
```
-(A::MyArrayType{T}, b::Date) where {T<:Date} = ...
```
that resolves the ambiguity by brute force.
###
[Complex method "cascades" with default arguments](#Complex-method-%22cascades%22-with-default-arguments)
If you are defining a method "cascade" that supplies defaults, be careful about dropping any arguments that correspond to potential defaults. For example, suppose you're writing a digital filtering algorithm and you have a method that handles the edges of the signal by applying padding:
```
function myfilter(A, kernel, ::Replicate)
Apadded = replicate_edges(A, size(kernel))
myfilter(Apadded, kernel) # now perform the "real" computation
end
```
This will run afoul of a method that supplies default padding:
```
myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # replicate the edge by default
```
Together, these two methods generate an infinite recursion with `A` constantly growing bigger.
The better design would be to define your call hierarchy like this:
```
struct NoPad end # indicate that no padding is desired, or that it's already applied
myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # default boundary conditions
function myfilter(A, kernel, ::Replicate)
Apadded = replicate_edges(A, size(kernel))
myfilter(Apadded, kernel, NoPad()) # indicate the new boundary conditions
end
# other padding methods go here
function myfilter(A, kernel, ::NoPad)
# Here's the "real" implementation of the core computation
end
```
`NoPad` is supplied in the same argument position as any other kind of padding, so it keeps the dispatch hierarchy well organized and with reduced likelihood of ambiguities. Moreover, it extends the "public" `myfilter` interface: a user who wants to control the padding explicitly can call the `NoPad` variant directly.
* [1](#citeref-1)In C++ or Java, for example, in a method call like `obj.meth(arg1,arg2)`, the object obj "receives" the method call and is implicitly passed to the method via the `this` keyword, rather than as an explicit method argument. When the current `this` object is the receiver of a method call, it can be omitted altogether, writing just `meth(arg1,arg2)`, with `this` implied as the receiving object.
* [Clarke61](#citeref-Clarke61)Arthur C. Clarke, *Profiles of the Future* (1961): Clarke's Third Law.
| programming_docs |
julia Unicode Input Unicode Input
=============
The following table lists Unicode characters that can be entered via tab completion of LaTeX-like abbreviations in the Julia REPL (and in various other editing environments). You can also get information on how to type a symbol by entering it in the REPL help, i.e. by typing `?` and then entering the symbol in the REPL (e.g., by copy-paste from somewhere you saw the symbol).
This table may appear to contain missing characters in the second column, or even show characters that are inconsistent with the characters as they are rendered in the Julia REPL. In these cases, users are strongly advised to check their choice of fonts in their browser and REPL environment, as there are known issues with glyphs in many fonts.
| Code point(s) | Character(s) | Tab completion sequence(s) | Unicode name(s) |
| --- | --- | --- | --- |
| U+000A1 | ¡ | \exclamdown | Inverted Exclamation Mark |
| U+000A3 | £ | \sterling | Pound Sign |
| U+000A5 | ¥ | \yen | Yen Sign |
| U+000A6 | ¦ | \brokenbar | Broken Bar / Broken Vertical Bar |
| U+000A7 | § | \S | Section Sign |
| U+000A9 | © | \copyright, \:copyright: | Copyright Sign |
| U+000AA | ª | \ordfeminine | Feminine Ordinal Indicator |
| U+000AC | ¬ | \neg | Not Sign |
| U+000AE | ® | \circledR, \:registered: | Registered Sign / Registered Trade Mark Sign |
| U+000AF | ¯ | \highminus | Macron / Spacing Macron |
| U+000B0 | ° | \degree | Degree Sign |
| U+000B1 | ± | \pm | Plus-Minus Sign / Plus-Or-Minus Sign |
| U+000B2 | ² | \^2 | Superscript Two / Superscript Digit Two |
| U+000B3 | ³ | \^3 | Superscript Three / Superscript Digit Three |
| U+000B6 | ¶ | \P | Pilcrow Sign / Paragraph Sign |
| U+000B7 | · | \cdotp | Middle Dot |
| U+000B9 | ¹ | \^1 | Superscript One / Superscript Digit One |
| U+000BA | º | \ordmasculine | Masculine Ordinal Indicator |
| U+000BC | ¼ | \1/4 | Vulgar Fraction One Quarter / Fraction One Quarter |
| U+000BD | ½ | \1/2 | Vulgar Fraction One Half / Fraction One Half |
| U+000BE | ¾ | \3/4 | Vulgar Fraction Three Quarters / Fraction Three Quarters |
| U+000BF | ¿ | \questiondown | Inverted Question Mark |
| U+000C5 | Å | \AA | Latin Capital Letter A With Ring Above / Latin Capital Letter A Ring |
| U+000C6 | Æ | \AE | Latin Capital Letter Ae / Latin Capital Letter A E |
| U+000D0 | Ð | \DH | Latin Capital Letter Eth |
| U+000D7 | × | \times | Multiplication Sign |
| U+000D8 | Ø | \O | Latin Capital Letter O With Stroke / Latin Capital Letter O Slash |
| U+000DE | Þ | \TH | Latin Capital Letter Thorn |
| U+000DF | ß | \ss | Latin Small Letter Sharp S |
| U+000E5 | å | \aa | Latin Small Letter A With Ring Above / Latin Small Letter A Ring |
| U+000E6 | æ | \ae | Latin Small Letter Ae / Latin Small Letter A E |
| U+000F0 | ð | \eth, \dh | Latin Small Letter Eth |
| U+000F7 | ÷ | \div | Division Sign |
| U+000F8 | ø | \o | Latin Small Letter O With Stroke / Latin Small Letter O Slash |
| U+000FE | þ | \th | Latin Small Letter Thorn |
| U+00110 | Đ | \DJ | Latin Capital Letter D With Stroke / Latin Capital Letter D Bar |
| U+00111 | đ | \dj | Latin Small Letter D With Stroke / Latin Small Letter D Bar |
| U+00127 | ħ | \hbar | Latin Small Letter H With Stroke / Latin Small Letter H Bar |
| U+00131 | ı | \imath | Latin Small Letter Dotless I |
| U+00141 | Ł | \L | Latin Capital Letter L With Stroke / Latin Capital Letter L Slash |
| U+00142 | ł | \l | Latin Small Letter L With Stroke / Latin Small Letter L Slash |
| U+0014A | Ŋ | \NG | Latin Capital Letter Eng |
| U+0014B | ŋ | \ng | Latin Small Letter Eng |
| U+00152 | Œ | \OE | Latin Capital Ligature Oe / Latin Capital Letter O E |
| U+00153 | œ | \oe | Latin Small Ligature Oe / Latin Small Letter O E |
| U+00195 | ƕ | \hvlig | Latin Small Letter Hv / Latin Small Letter H V |
| U+0019E | ƞ | \nrleg | Latin Small Letter N With Long Right Leg |
| U+001B5 | Ƶ | \Zbar | Latin Capital Letter Z With Stroke / Latin Capital Letter Z Bar |
| U+001C2 | ǂ | \doublepipe | Latin Letter Alveolar Click / Latin Letter Pipe Double Bar |
| U+00237 | ȷ | \jmath | Latin Small Letter Dotless J |
| U+00250 | ɐ | \trna | Latin Small Letter Turned A |
| U+00252 | ɒ | \trnsa | Latin Small Letter Turned Alpha / Latin Small Letter Turned Script A |
| U+00254 | ɔ | \openo | Latin Small Letter Open O |
| U+00256 | ɖ | \rtld | Latin Small Letter D With Tail / Latin Small Letter D Retroflex Hook |
| U+00259 | ə | \schwa | Latin Small Letter Schwa |
| U+00263 | ɣ | \pgamma | Latin Small Letter Gamma |
| U+00264 | ɤ | \pbgam | Latin Small Letter Rams Horn / Latin Small Letter Baby Gamma |
| U+00265 | ɥ | \trnh | Latin Small Letter Turned H |
| U+0026C | ɬ | \btdl | Latin Small Letter L With Belt / Latin Small Letter L Belt |
| U+0026D | ɭ | \rtll | Latin Small Letter L With Retroflex Hook / Latin Small Letter L Retroflex Hook |
| U+0026F | ɯ | \trnm | Latin Small Letter Turned M |
| U+00270 | ɰ | \trnmlr | Latin Small Letter Turned M With Long Leg |
| U+00271 | ɱ | \ltlmr | Latin Small Letter M With Hook / Latin Small Letter M Hook |
| U+00272 | ɲ | \ltln | Latin Small Letter N With Left Hook / Latin Small Letter N Hook |
| U+00273 | ɳ | \rtln | Latin Small Letter N With Retroflex Hook / Latin Small Letter N Retroflex Hook |
| U+00277 | ɷ | \clomeg | Latin Small Letter Closed Omega |
| U+00278 | ɸ | \ltphi | Latin Small Letter Phi |
| U+00279 | ɹ | \trnr | Latin Small Letter Turned R |
| U+0027A | ɺ | \trnrl | Latin Small Letter Turned R With Long Leg |
| U+0027B | ɻ | \rttrnr | Latin Small Letter Turned R With Hook / Latin Small Letter Turned R Hook |
| U+0027C | ɼ | \rl | Latin Small Letter R With Long Leg |
| U+0027D | ɽ | \rtlr | Latin Small Letter R With Tail / Latin Small Letter R Hook |
| U+0027E | ɾ | \fhr | Latin Small Letter R With Fishhook / Latin Small Letter Fishhook R |
| U+00282 | ʂ | \rtls | Latin Small Letter S With Hook / Latin Small Letter S Hook |
| U+00283 | ʃ | \esh | Latin Small Letter Esh |
| U+00287 | ʇ | \trnt | Latin Small Letter Turned T |
| U+00288 | ʈ | \rtlt | Latin Small Letter T With Retroflex Hook / Latin Small Letter T Retroflex Hook |
| U+0028A | ʊ | \pupsil | Latin Small Letter Upsilon |
| U+0028B | ʋ | \pscrv | Latin Small Letter V With Hook / Latin Small Letter Script V |
| U+0028C | ʌ | \invv | Latin Small Letter Turned V |
| U+0028D | ʍ | \invw | Latin Small Letter Turned W |
| U+0028E | ʎ | \trny | Latin Small Letter Turned Y |
| U+00290 | ʐ | \rtlz | Latin Small Letter Z With Retroflex Hook / Latin Small Letter Z Retroflex Hook |
| U+00292 | ʒ | \yogh | Latin Small Letter Ezh / Latin Small Letter Yogh |
| U+00294 | ʔ | \glst | Latin Letter Glottal Stop |
| U+00295 | ʕ | \reglst | Latin Letter Pharyngeal Voiced Fricative / Latin Letter Reversed Glottal Stop |
| U+00296 | ʖ | \inglst | Latin Letter Inverted Glottal Stop |
| U+0029E | ʞ | \turnk | Latin Small Letter Turned K |
| U+002A4 | ʤ | \dyogh | Latin Small Letter Dezh Digraph / Latin Small Letter D Yogh |
| U+002A7 | ʧ | \tesh | Latin Small Letter Tesh Digraph / Latin Small Letter T Esh |
| U+002B0 | ʰ | \^h | Modifier Letter Small H |
| U+002B2 | ʲ | \^j | Modifier Letter Small J |
| U+002B3 | ʳ | \^r | Modifier Letter Small R |
| U+002B7 | ʷ | \^w | Modifier Letter Small W |
| U+002B8 | ʸ | \^y | Modifier Letter Small Y |
| U+002BC | ʼ | \rasp | Modifier Letter Apostrophe |
| U+002C8 | ˈ | \verts | Modifier Letter Vertical Line |
| U+002CC | ˌ | \verti | Modifier Letter Low Vertical Line |
| U+002D0 | ː | \lmrk | Modifier Letter Triangular Colon |
| U+002D1 | ˑ | \hlmrk | Modifier Letter Half Triangular Colon |
| U+002D2 | ˒ | \sbrhr | Modifier Letter Centred Right Half Ring / Modifier Letter Centered Right Half Ring |
| U+002D3 | ˓ | \sblhr | Modifier Letter Centred Left Half Ring / Modifier Letter Centered Left Half Ring |
| U+002D4 | ˔ | \rais | Modifier Letter Up Tack |
| U+002D5 | ˕ | \low | Modifier Letter Down Tack |
| U+002D8 | ˘ | \u | Breve / Spacing Breve |
| U+002DC | ˜ | \tildelow | Small Tilde / Spacing Tilde |
| U+002E1 | ˡ | \^l | Modifier Letter Small L |
| U+002E2 | ˢ | \^s | Modifier Letter Small S |
| U+002E3 | ˣ | \^x | Modifier Letter Small X |
| U+00300 | ̀ | \grave | Combining Grave Accent / Non-Spacing Grave |
| U+00301 | ́ | \acute | Combining Acute Accent / Non-Spacing Acute |
| U+00302 | ̂ | \hat | Combining Circumflex Accent / Non-Spacing Circumflex |
| U+00303 | ̃ | \tilde | Combining Tilde / Non-Spacing Tilde |
| U+00304 | ̄ | \bar | Combining Macron / Non-Spacing Macron |
| U+00305 | ̅ | \overbar | Combining Overline / Non-Spacing Overscore |
| U+00306 | ̆ | \breve | Combining Breve / Non-Spacing Breve |
| U+00307 | ̇ | \dot | Combining Dot Above / Non-Spacing Dot Above |
| U+00308 | ̈ | \ddot | Combining Diaeresis / Non-Spacing Diaeresis |
| U+00309 | ̉ | \ovhook | Combining Hook Above / Non-Spacing Hook Above |
| U+0030A | ̊ | \ocirc | Combining Ring Above / Non-Spacing Ring Above |
| U+0030B | ̋ | \H | Combining Double Acute Accent / Non-Spacing Double Acute |
| U+0030C | ̌ | \check | Combining Caron / Non-Spacing Hacek |
| U+00310 | ̐ | \candra | Combining Candrabindu / Non-Spacing Candrabindu |
| U+00312 | ̒ | \oturnedcomma | Combining Turned Comma Above / Non-Spacing Turned Comma Above |
| U+00315 | ̕ | \ocommatopright | Combining Comma Above Right / Non-Spacing Comma Above Right |
| U+0031A | ̚ | \droang | Combining Left Angle Above / Non-Spacing Left Angle Above |
| U+00321 | ̡ | \palh | Combining Palatalized Hook Below / Non-Spacing Palatalized Hook Below |
| U+00322 | ̢ | \rh | Combining Retroflex Hook Below / Non-Spacing Retroflex Hook Below |
| U+00327 | ̧ | \c | Combining Cedilla / Non-Spacing Cedilla |
| U+00328 | ̨ | \k | Combining Ogonek / Non-Spacing Ogonek |
| U+0032A | ̪ | \sbbrg | Combining Bridge Below / Non-Spacing Bridge Below |
| U+00330 | ̰ | \wideutilde | Combining Tilde Below / Non-Spacing Tilde Below |
| U+00332 | ̲ | \underbar | Combining Low Line / Non-Spacing Underscore |
| U+00336 | ̶ | \strike, \sout | Combining Long Stroke Overlay / Non-Spacing Long Bar Overlay |
| U+00338 | ̸ | \not | Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+0034D | ͍ | \underleftrightarrow | Combining Left Right Arrow Below |
| U+00391 | Α | \Alpha | Greek Capital Letter Alpha |
| U+00392 | Β | \Beta | Greek Capital Letter Beta |
| U+00393 | Γ | \Gamma | Greek Capital Letter Gamma |
| U+00394 | Δ | \Delta | Greek Capital Letter Delta |
| U+00395 | Ε | \Epsilon | Greek Capital Letter Epsilon |
| U+00396 | Ζ | \Zeta | Greek Capital Letter Zeta |
| U+00397 | Η | \Eta | Greek Capital Letter Eta |
| U+00398 | Θ | \Theta | Greek Capital Letter Theta |
| U+00399 | Ι | \Iota | Greek Capital Letter Iota |
| U+0039A | Κ | \Kappa | Greek Capital Letter Kappa |
| U+0039B | Λ | \Lambda | Greek Capital Letter Lamda / Greek Capital Letter Lambda |
| U+0039C | Μ | \upMu | Greek Capital Letter Mu |
| U+0039D | Ν | \upNu | Greek Capital Letter Nu |
| U+0039E | Ξ | \Xi | Greek Capital Letter Xi |
| U+0039F | Ο | \upOmicron | Greek Capital Letter Omicron |
| U+003A0 | Π | \Pi | Greek Capital Letter Pi |
| U+003A1 | Ρ | \Rho | Greek Capital Letter Rho |
| U+003A3 | Σ | \Sigma | Greek Capital Letter Sigma |
| U+003A4 | Τ | \Tau | Greek Capital Letter Tau |
| U+003A5 | Υ | \Upsilon | Greek Capital Letter Upsilon |
| U+003A6 | Φ | \Phi | Greek Capital Letter Phi |
| U+003A7 | Χ | \Chi | Greek Capital Letter Chi |
| U+003A8 | Ψ | \Psi | Greek Capital Letter Psi |
| U+003A9 | Ω | \Omega | Greek Capital Letter Omega |
| U+003B1 | α | \alpha | Greek Small Letter Alpha |
| U+003B2 | β | \beta | Greek Small Letter Beta |
| U+003B3 | γ | \gamma | Greek Small Letter Gamma |
| U+003B4 | δ | \delta | Greek Small Letter Delta |
| U+003B5 | ε | \upepsilon, \varepsilon | Greek Small Letter Epsilon |
| U+003B6 | ζ | \zeta | Greek Small Letter Zeta |
| U+003B7 | η | \eta | Greek Small Letter Eta |
| U+003B8 | θ | \theta | Greek Small Letter Theta |
| U+003B9 | ι | \iota | Greek Small Letter Iota |
| U+003BA | κ | \kappa | Greek Small Letter Kappa |
| U+003BB | λ | \lambda | Greek Small Letter Lamda / Greek Small Letter Lambda |
| U+003BC | μ | \mu | Greek Small Letter Mu |
| U+003BD | ν | \nu | Greek Small Letter Nu |
| U+003BE | ξ | \xi | Greek Small Letter Xi |
| U+003BF | ο | \upomicron | Greek Small Letter Omicron |
| U+003C0 | π | \pi | Greek Small Letter Pi |
| U+003C1 | ρ | \rho | Greek Small Letter Rho |
| U+003C2 | ς | \varsigma | Greek Small Letter Final Sigma |
| U+003C3 | σ | \sigma | Greek Small Letter Sigma |
| U+003C4 | τ | \tau | Greek Small Letter Tau |
| U+003C5 | υ | \upsilon | Greek Small Letter Upsilon |
| U+003C6 | φ | \varphi | Greek Small Letter Phi |
| U+003C7 | χ | \chi | Greek Small Letter Chi |
| U+003C8 | ψ | \psi | Greek Small Letter Psi |
| U+003C9 | ω | \omega | Greek Small Letter Omega |
| U+003D0 | ϐ | \upvarbeta | Greek Beta Symbol / Greek Small Letter Curled Beta |
| U+003D1 | ϑ | \vartheta | Greek Theta Symbol / Greek Small Letter Script Theta |
| U+003D5 | ϕ | \phi | Greek Phi Symbol / Greek Small Letter Script Phi |
| U+003D6 | ϖ | \varpi | Greek Pi Symbol / Greek Small Letter Omega Pi |
| U+003D8 | Ϙ | \upoldKoppa | Greek Letter Archaic Koppa |
| U+003D9 | ϙ | \upoldkoppa | Greek Small Letter Archaic Koppa |
| U+003DA | Ϛ | \Stigma | Greek Letter Stigma / Greek Capital Letter Stigma |
| U+003DB | ϛ | \upstigma | Greek Small Letter Stigma |
| U+003DC | Ϝ | \Digamma | Greek Letter Digamma / Greek Capital Letter Digamma |
| U+003DD | ϝ | \digamma | Greek Small Letter Digamma |
| U+003DE | Ϟ | \Koppa | Greek Letter Koppa / Greek Capital Letter Koppa |
| U+003DF | ϟ | \upkoppa | Greek Small Letter Koppa |
| U+003E0 | Ϡ | \Sampi | Greek Letter Sampi / Greek Capital Letter Sampi |
| U+003E1 | ϡ | \upsampi | Greek Small Letter Sampi |
| U+003F0 | ϰ | \varkappa | Greek Kappa Symbol / Greek Small Letter Script Kappa |
| U+003F1 | ϱ | \varrho | Greek Rho Symbol / Greek Small Letter Tailed Rho |
| U+003F4 | ϴ | \varTheta | Greek Capital Theta Symbol |
| U+003F5 | ϵ | \epsilon | Greek Lunate Epsilon Symbol |
| U+003F6 | ϶ | \backepsilon | Greek Reversed Lunate Epsilon Symbol |
| U+01D2C | ᴬ | \^A | Modifier Letter Capital A |
| U+01D2E | ᴮ | \^B | Modifier Letter Capital B |
| U+01D30 | ᴰ | \^D | Modifier Letter Capital D |
| U+01D31 | ᴱ | \^E | Modifier Letter Capital E |
| U+01D33 | ᴳ | \^G | Modifier Letter Capital G |
| U+01D34 | ᴴ | \^H | Modifier Letter Capital H |
| U+01D35 | ᴵ | \^I | Modifier Letter Capital I |
| U+01D36 | ᴶ | \^J | Modifier Letter Capital J |
| U+01D37 | ᴷ | \^K | Modifier Letter Capital K |
| U+01D38 | ᴸ | \^L | Modifier Letter Capital L |
| U+01D39 | ᴹ | \^M | Modifier Letter Capital M |
| U+01D3A | ᴺ | \^N | Modifier Letter Capital N |
| U+01D3C | ᴼ | \^O | Modifier Letter Capital O |
| U+01D3E | ᴾ | \^P | Modifier Letter Capital P |
| U+01D3F | ᴿ | \^R | Modifier Letter Capital R |
| U+01D40 | ᵀ | \^T | Modifier Letter Capital T |
| U+01D41 | ᵁ | \^U | Modifier Letter Capital U |
| U+01D42 | ᵂ | \^W | Modifier Letter Capital W |
| U+01D43 | ᵃ | \^a | Modifier Letter Small A |
| U+01D45 | ᵅ | \^alpha | Modifier Letter Small Alpha |
| U+01D47 | ᵇ | \^b | Modifier Letter Small B |
| U+01D48 | ᵈ | \^d | Modifier Letter Small D |
| U+01D49 | ᵉ | \^e | Modifier Letter Small E |
| U+01D4B | ᵋ | \^epsilon | Modifier Letter Small Open E |
| U+01D4D | ᵍ | \^g | Modifier Letter Small G |
| U+01D4F | ᵏ | \^k | Modifier Letter Small K |
| U+01D50 | ᵐ | \^m | Modifier Letter Small M |
| U+01D52 | ᵒ | \^o | Modifier Letter Small O |
| U+01D56 | ᵖ | \^p | Modifier Letter Small P |
| U+01D57 | ᵗ | \^t | Modifier Letter Small T |
| U+01D58 | ᵘ | \^u | Modifier Letter Small U |
| U+01D5B | ᵛ | \^v | Modifier Letter Small V |
| U+01D5D | ᵝ | \^beta | Modifier Letter Small Beta |
| U+01D5E | ᵞ | \^gamma | Modifier Letter Small Greek Gamma |
| U+01D5F | ᵟ | \^delta | Modifier Letter Small Delta |
| U+01D60 | ᵠ | \^phi | Modifier Letter Small Greek Phi |
| U+01D61 | ᵡ | \^chi | Modifier Letter Small Chi |
| U+01D62 | ᵢ | \\_i | Latin Subscript Small Letter I |
| U+01D63 | ᵣ | \\_r | Latin Subscript Small Letter R |
| U+01D64 | ᵤ | \\_u | Latin Subscript Small Letter U |
| U+01D65 | ᵥ | \\_v | Latin Subscript Small Letter V |
| U+01D66 | ᵦ | \\_beta | Greek Subscript Small Letter Beta |
| U+01D67 | ᵧ | \\_gamma | Greek Subscript Small Letter Gamma |
| U+01D68 | ᵨ | \\_rho | Greek Subscript Small Letter Rho |
| U+01D69 | ᵩ | \\_phi | Greek Subscript Small Letter Phi |
| U+01D6A | ᵪ | \\_chi | Greek Subscript Small Letter Chi |
| U+01D9C | ᶜ | \^c | Modifier Letter Small C |
| U+01DA0 | ᶠ | \^f | Modifier Letter Small F |
| U+01DA5 | ᶥ | \^iota | Modifier Letter Small Iota |
| U+01DB2 | ᶲ | \^ltphi | Modifier Letter Small Phi |
| U+01DBB | ᶻ | \^z | Modifier Letter Small Z |
| U+01DBF | ᶿ | \^theta | Modifier Letter Small Theta |
| U+02002 | | \enspace | En Space |
| U+02003 | | \quad | Em Space |
| U+02005 | | \thickspace | Four-Per-Em Space |
| U+02009 | | \thinspace | Thin Space |
| U+0200A | | \hspace | Hair Space |
| U+02013 | – | \endash | En Dash |
| U+02014 | — | \emdash | Em Dash |
| U+02016 | ‖ | \Vert | Double Vertical Line / Double Vertical Bar |
| U+02018 | ‘ | \lq | Left Single Quotation Mark / Single Turned Comma Quotation Mark |
| U+02019 | ’ | \rq | Right Single Quotation Mark / Single Comma Quotation Mark |
| U+0201B | ‛ | \reapos | Single High-Reversed-9 Quotation Mark / Single Reversed Comma Quotation Mark |
| U+0201C | “ | \ldq | Left Double Quotation Mark / Double Turned Comma Quotation Mark |
| U+0201D | ” | \rdq | Right Double Quotation Mark / Double Comma Quotation Mark |
| U+02020 | † | \dagger | Dagger |
| U+02021 | ‡ | \ddagger | Double Dagger |
| U+02022 | • | \bullet | Bullet |
| U+02026 | … | \dots, \ldots | Horizontal Ellipsis |
| U+02030 | ‰ | \perthousand | Per Mille Sign |
| U+02031 | ‱ | \pertenthousand | Per Ten Thousand Sign |
| U+02032 | ′ | \prime | Prime |
| U+02033 | ″ | \pprime | Double Prime |
| U+02034 | ‴ | \ppprime | Triple Prime |
| U+02035 | ‵ | \backprime | Reversed Prime |
| U+02036 | ‶ | \backpprime | Reversed Double Prime |
| U+02037 | ‷ | \backppprime | Reversed Triple Prime |
| U+02039 | ‹ | \guilsinglleft | Single Left-Pointing Angle Quotation Mark / Left Pointing Single Guillemet |
| U+0203A | › | \guilsinglright | Single Right-Pointing Angle Quotation Mark / Right Pointing Single Guillemet |
| U+0203C | ‼ | \:bangbang: | Double Exclamation Mark |
| U+02040 | ⁀ | \tieconcat | Character Tie |
| U+02049 | ⁉ | \:interrobang: | Exclamation Question Mark |
| U+02057 | ⁗ | \pppprime | Quadruple Prime |
| U+0205D | ⁝ | \tricolon | Tricolon |
| U+02060 | | \nolinebreak | Word Joiner |
| U+02070 | ⁰ | \^0 | Superscript Zero / Superscript Digit Zero |
| U+02071 | ⁱ | \^i | Superscript Latin Small Letter I |
| U+02074 | ⁴ | \^4 | Superscript Four / Superscript Digit Four |
| U+02075 | ⁵ | \^5 | Superscript Five / Superscript Digit Five |
| U+02076 | ⁶ | \^6 | Superscript Six / Superscript Digit Six |
| U+02077 | ⁷ | \^7 | Superscript Seven / Superscript Digit Seven |
| U+02078 | ⁸ | \^8 | Superscript Eight / Superscript Digit Eight |
| U+02079 | ⁹ | \^9 | Superscript Nine / Superscript Digit Nine |
| U+0207A | ⁺ | \^+ | Superscript Plus Sign |
| U+0207B | ⁻ | \^- | Superscript Minus / Superscript Hyphen-Minus |
| U+0207C | ⁼ | \^= | Superscript Equals Sign |
| U+0207D | ⁽ | \^( | Superscript Left Parenthesis / Superscript Opening Parenthesis |
| U+0207E | ⁾ | \^) | Superscript Right Parenthesis / Superscript Closing Parenthesis |
| U+0207F | ⁿ | \^n | Superscript Latin Small Letter N |
| U+02080 | ₀ | \\_0 | Subscript Zero / Subscript Digit Zero |
| U+02081 | ₁ | \\_1 | Subscript One / Subscript Digit One |
| U+02082 | ₂ | \\_2 | Subscript Two / Subscript Digit Two |
| U+02083 | ₃ | \\_3 | Subscript Three / Subscript Digit Three |
| U+02084 | ₄ | \\_4 | Subscript Four / Subscript Digit Four |
| U+02085 | ₅ | \\_5 | Subscript Five / Subscript Digit Five |
| U+02086 | ₆ | \\_6 | Subscript Six / Subscript Digit Six |
| U+02087 | ₇ | \\_7 | Subscript Seven / Subscript Digit Seven |
| U+02088 | ₈ | \\_8 | Subscript Eight / Subscript Digit Eight |
| U+02089 | ₉ | \\_9 | Subscript Nine / Subscript Digit Nine |
| U+0208A | ₊ | \\_+ | Subscript Plus Sign |
| U+0208B | ₋ | \\_- | Subscript Minus / Subscript Hyphen-Minus |
| U+0208C | ₌ | \\_= | Subscript Equals Sign |
| U+0208D | ₍ | \\_( | Subscript Left Parenthesis / Subscript Opening Parenthesis |
| U+0208E | ₎ | \\_) | Subscript Right Parenthesis / Subscript Closing Parenthesis |
| U+02090 | ₐ | \\_a | Latin Subscript Small Letter A |
| U+02091 | ₑ | \\_e | Latin Subscript Small Letter E |
| U+02092 | ₒ | \\_o | Latin Subscript Small Letter O |
| U+02093 | ₓ | \\_x | Latin Subscript Small Letter X |
| U+02094 | ₔ | \\_schwa | Latin Subscript Small Letter Schwa |
| U+02095 | ₕ | \\_h | Latin Subscript Small Letter H |
| U+02096 | ₖ | \\_k | Latin Subscript Small Letter K |
| U+02097 | ₗ | \\_l | Latin Subscript Small Letter L |
| U+02098 | ₘ | \\_m | Latin Subscript Small Letter M |
| U+02099 | ₙ | \\_n | Latin Subscript Small Letter N |
| U+0209A | ₚ | \\_p | Latin Subscript Small Letter P |
| U+0209B | ₛ | \\_s | Latin Subscript Small Letter S |
| U+0209C | ₜ | \\_t | Latin Subscript Small Letter T |
| U+020A7 | ₧ | \pes | Peseta Sign |
| U+020AC | € | \euro | Euro Sign |
| U+020D0 | ⃐ | \leftharpoonaccent | Combining Left Harpoon Above / Non-Spacing Left Harpoon Above |
| U+020D1 | ⃑ | \rightharpoonaccent | Combining Right Harpoon Above / Non-Spacing Right Harpoon Above |
| U+020D2 | ⃒ | \vertoverlay | Combining Long Vertical Line Overlay / Non-Spacing Long Vertical Bar Overlay |
| U+020D6 | ⃖ | \overleftarrow | Combining Left Arrow Above / Non-Spacing Left Arrow Above |
| U+020D7 | ⃗ | \vec | Combining Right Arrow Above / Non-Spacing Right Arrow Above |
| U+020DB | ⃛ | \dddot | Combining Three Dots Above / Non-Spacing Three Dots Above |
| U+020DC | ⃜ | \ddddot | Combining Four Dots Above / Non-Spacing Four Dots Above |
| U+020DD | ⃝ | \enclosecircle | Combining Enclosing Circle / Enclosing Circle |
| U+020DE | ⃞ | \enclosesquare | Combining Enclosing Square / Enclosing Square |
| U+020DF | ⃟ | \enclosediamond | Combining Enclosing Diamond / Enclosing Diamond |
| U+020E1 | ⃡ | \overleftrightarrow | Combining Left Right Arrow Above / Non-Spacing Left Right Arrow Above |
| U+020E4 | ⃤ | \enclosetriangle | Combining Enclosing Upward Pointing Triangle |
| U+020E7 | ⃧ | \annuity | Combining Annuity Symbol |
| U+020E8 | ⃨ | \threeunderdot | Combining Triple Underdot |
| U+020E9 | ⃩ | \widebridgeabove | Combining Wide Bridge Above |
| U+020EC | ⃬ | \underrightharpoondown | Combining Rightwards Harpoon With Barb Downwards |
| U+020ED | ⃭ | \underleftharpoondown | Combining Leftwards Harpoon With Barb Downwards |
| U+020EE | ⃮ | \underleftarrow | Combining Left Arrow Below |
| U+020EF | ⃯ | \underrightarrow | Combining Right Arrow Below |
| U+020F0 | ⃰ | \asteraccent | Combining Asterisk Above |
| U+02102 | ℂ | \bbC | Double-Struck Capital C / Double-Struck C |
| U+02107 | ℇ | \eulermascheroni | Euler Constant / Eulers |
| U+0210A | ℊ | \scrg | Script Small G |
| U+0210B | ℋ | \scrH | Script Capital H / Script H |
| U+0210C | ℌ | \frakH | Black-Letter Capital H / Black-Letter H |
| U+0210D | ℍ | \bbH | Double-Struck Capital H / Double-Struck H |
| U+0210E | ℎ | \ith, \planck | Planck Constant |
| U+0210F | ℏ | \hslash | Planck Constant Over Two Pi / Planck Constant Over 2 Pi |
| U+02110 | ℐ | \scrI | Script Capital I / Script I |
| U+02111 | ℑ | \Im, \frakI | Black-Letter Capital I / Black-Letter I |
| U+02112 | ℒ | \scrL | Script Capital L / Script L |
| U+02113 | ℓ | \ell | Script Small L |
| U+02115 | ℕ | \bbN | Double-Struck Capital N / Double-Struck N |
| U+02116 | № | \numero | Numero Sign / Numero |
| U+02118 | ℘ | \wp | Script Capital P / Script P |
| U+02119 | ℙ | \bbP | Double-Struck Capital P / Double-Struck P |
| U+0211A | ℚ | \bbQ | Double-Struck Capital Q / Double-Struck Q |
| U+0211B | ℛ | \scrR | Script Capital R / Script R |
| U+0211C | ℜ | \Re, \frakR | Black-Letter Capital R / Black-Letter R |
| U+0211D | ℝ | \bbR | Double-Struck Capital R / Double-Struck R |
| U+0211E | ℞ | \xrat | Prescription Take |
| U+02122 | ™ | \trademark, \:tm: | Trade Mark Sign / Trademark |
| U+02124 | ℤ | \bbZ | Double-Struck Capital Z / Double-Struck Z |
| U+02126 | Ω | \ohm | Ohm Sign / Ohm |
| U+02127 | ℧ | \mho | Inverted Ohm Sign / Mho |
| U+02128 | ℨ | \frakZ | Black-Letter Capital Z / Black-Letter Z |
| U+02129 | ℩ | \turnediota | Turned Greek Small Letter Iota |
| U+0212B | Å | \Angstrom | Angstrom Sign / Angstrom Unit |
| U+0212C | ℬ | \scrB | Script Capital B / Script B |
| U+0212D | ℭ | \frakC | Black-Letter Capital C / Black-Letter C |
| U+0212F | ℯ | \scre, \euler | Script Small E |
| U+02130 | ℰ | \scrE | Script Capital E / Script E |
| U+02131 | ℱ | \scrF | Script Capital F / Script F |
| U+02132 | Ⅎ | \Finv | Turned Capital F / Turned F |
| U+02133 | ℳ | \scrM | Script Capital M / Script M |
| U+02134 | ℴ | \scro | Script Small O |
| U+02135 | ℵ | \aleph | Alef Symbol / First Transfinite Cardinal |
| U+02136 | ℶ | \beth | Bet Symbol / Second Transfinite Cardinal |
| U+02137 | ℷ | \gimel | Gimel Symbol / Third Transfinite Cardinal |
| U+02138 | ℸ | \daleth | Dalet Symbol / Fourth Transfinite Cardinal |
| U+02139 | ℹ | \:information\_source: | Information Source |
| U+0213C | ℼ | \bbpi | Double-Struck Small Pi |
| U+0213D | ℽ | \bbgamma | Double-Struck Small Gamma |
| U+0213E | ℾ | \bbGamma | Double-Struck Capital Gamma |
| U+0213F | ℿ | \bbPi | Double-Struck Capital Pi |
| U+02140 | ⅀ | \bbsum | Double-Struck N-Ary Summation |
| U+02141 | ⅁ | \Game | Turned Sans-Serif Capital G |
| U+02142 | ⅂ | \sansLturned | Turned Sans-Serif Capital L |
| U+02143 | ⅃ | \sansLmirrored | Reversed Sans-Serif Capital L |
| U+02144 | ⅄ | \Yup | Turned Sans-Serif Capital Y |
| U+02145 | ⅅ | \bbiD | Double-Struck Italic Capital D |
| U+02146 | ⅆ | \bbid | Double-Struck Italic Small D |
| U+02147 | ⅇ | \bbie | Double-Struck Italic Small E |
| U+02148 | ⅈ | \bbii | Double-Struck Italic Small I |
| U+02149 | ⅉ | \bbij | Double-Struck Italic Small J |
| U+0214A | ⅊ | \PropertyLine | Property Line |
| U+0214B | ⅋ | \upand | Turned Ampersand |
| U+02150 | ⅐ | \1/7 | Vulgar Fraction One Seventh |
| U+02151 | ⅑ | \1/9 | Vulgar Fraction One Ninth |
| U+02152 | ⅒ | \1/10 | Vulgar Fraction One Tenth |
| U+02153 | ⅓ | \1/3 | Vulgar Fraction One Third / Fraction One Third |
| U+02154 | ⅔ | \2/3 | Vulgar Fraction Two Thirds / Fraction Two Thirds |
| U+02155 | ⅕ | \1/5 | Vulgar Fraction One Fifth / Fraction One Fifth |
| U+02156 | ⅖ | \2/5 | Vulgar Fraction Two Fifths / Fraction Two Fifths |
| U+02157 | ⅗ | \3/5 | Vulgar Fraction Three Fifths / Fraction Three Fifths |
| U+02158 | ⅘ | \4/5 | Vulgar Fraction Four Fifths / Fraction Four Fifths |
| U+02159 | ⅙ | \1/6 | Vulgar Fraction One Sixth / Fraction One Sixth |
| U+0215A | ⅚ | \5/6 | Vulgar Fraction Five Sixths / Fraction Five Sixths |
| U+0215B | ⅛ | \1/8 | Vulgar Fraction One Eighth / Fraction One Eighth |
| U+0215C | ⅜ | \3/8 | Vulgar Fraction Three Eighths / Fraction Three Eighths |
| U+0215D | ⅝ | \5/8 | Vulgar Fraction Five Eighths / Fraction Five Eighths |
| U+0215E | ⅞ | \7/8 | Vulgar Fraction Seven Eighths / Fraction Seven Eighths |
| U+0215F | ⅟ | \1/ | Fraction Numerator One |
| U+02189 | ↉ | \0/3 | Vulgar Fraction Zero Thirds |
| U+02190 | ← | \leftarrow | Leftwards Arrow / Left Arrow |
| U+02191 | ↑ | \uparrow | Upwards Arrow / Up Arrow |
| U+02192 | → | \to, \rightarrow | Rightwards Arrow / Right Arrow |
| U+02193 | ↓ | \downarrow | Downwards Arrow / Down Arrow |
| U+02194 | ↔ | \leftrightarrow, \:left\_right\_arrow: | Left Right Arrow |
| U+02195 | ↕ | \updownarrow, \:arrow\_up\_down: | Up Down Arrow |
| U+02196 | ↖ | \nwarrow, \:arrow\_upper\_left: | North West Arrow / Upper Left Arrow |
| U+02197 | ↗ | \nearrow, \:arrow\_upper\_right: | North East Arrow / Upper Right Arrow |
| U+02198 | ↘ | \searrow, \:arrow\_lower\_right: | South East Arrow / Lower Right Arrow |
| U+02199 | ↙ | \swarrow, \:arrow\_lower\_left: | South West Arrow / Lower Left Arrow |
| U+0219A | ↚ | \nleftarrow | Leftwards Arrow With Stroke / Left Arrow With Stroke |
| U+0219B | ↛ | \nrightarrow | Rightwards Arrow With Stroke / Right Arrow With Stroke |
| U+0219C | ↜ | \leftwavearrow | Leftwards Wave Arrow / Left Wave Arrow |
| U+0219D | ↝ | \rightwavearrow | Rightwards Wave Arrow / Right Wave Arrow |
| U+0219E | ↞ | \twoheadleftarrow | Leftwards Two Headed Arrow / Left Two Headed Arrow |
| U+0219F | ↟ | \twoheaduparrow | Upwards Two Headed Arrow / Up Two Headed Arrow |
| U+021A0 | ↠ | \twoheadrightarrow | Rightwards Two Headed Arrow / Right Two Headed Arrow |
| U+021A1 | ↡ | \twoheaddownarrow | Downwards Two Headed Arrow / Down Two Headed Arrow |
| U+021A2 | ↢ | \leftarrowtail | Leftwards Arrow With Tail / Left Arrow With Tail |
| U+021A3 | ↣ | \rightarrowtail | Rightwards Arrow With Tail / Right Arrow With Tail |
| U+021A4 | ↤ | \mapsfrom | Leftwards Arrow From Bar / Left Arrow From Bar |
| U+021A5 | ↥ | \mapsup | Upwards Arrow From Bar / Up Arrow From Bar |
| U+021A6 | ↦ | \mapsto | Rightwards Arrow From Bar / Right Arrow From Bar |
| U+021A7 | ↧ | \mapsdown | Downwards Arrow From Bar / Down Arrow From Bar |
| U+021A8 | ↨ | \updownarrowbar | Up Down Arrow With Base |
| U+021A9 | ↩ | \hookleftarrow, \:leftwards\_arrow\_with\_hook: | Leftwards Arrow With Hook / Left Arrow With Hook |
| U+021AA | ↪ | \hookrightarrow, \:arrow\_right\_hook: | Rightwards Arrow With Hook / Right Arrow With Hook |
| U+021AB | ↫ | \looparrowleft | Leftwards Arrow With Loop / Left Arrow With Loop |
| U+021AC | ↬ | \looparrowright | Rightwards Arrow With Loop / Right Arrow With Loop |
| U+021AD | ↭ | \leftrightsquigarrow | Left Right Wave Arrow |
| U+021AE | ↮ | \nleftrightarrow | Left Right Arrow With Stroke |
| U+021AF | ↯ | \downzigzagarrow | Downwards Zigzag Arrow / Down Zigzag Arrow |
| U+021B0 | ↰ | \Lsh | Upwards Arrow With Tip Leftwards / Up Arrow With Tip Left |
| U+021B1 | ↱ | \Rsh | Upwards Arrow With Tip Rightwards / Up Arrow With Tip Right |
| U+021B2 | ↲ | \Ldsh | Downwards Arrow With Tip Leftwards / Down Arrow With Tip Left |
| U+021B3 | ↳ | \Rdsh | Downwards Arrow With Tip Rightwards / Down Arrow With Tip Right |
| U+021B4 | ↴ | \linefeed | Rightwards Arrow With Corner Downwards / Right Arrow With Corner Down |
| U+021B5 | ↵ | \carriagereturn | Downwards Arrow With Corner Leftwards / Down Arrow With Corner Left |
| U+021B6 | ↶ | \curvearrowleft | Anticlockwise Top Semicircle Arrow |
| U+021B7 | ↷ | \curvearrowright | Clockwise Top Semicircle Arrow |
| U+021B8 | ↸ | \barovernorthwestarrow | North West Arrow To Long Bar / Upper Left Arrow To Long Bar |
| U+021B9 | ↹ | \barleftarrowrightarrowbar | Leftwards Arrow To Bar Over Rightwards Arrow To Bar / Left Arrow To Bar Over Right Arrow To Bar |
| U+021BA | ↺ | \circlearrowleft | Anticlockwise Open Circle Arrow |
| U+021BB | ↻ | \circlearrowright | Clockwise Open Circle Arrow |
| U+021BC | ↼ | \leftharpoonup | Leftwards Harpoon With Barb Upwards / Left Harpoon With Barb Up |
| U+021BD | ↽ | \leftharpoondown | Leftwards Harpoon With Barb Downwards / Left Harpoon With Barb Down |
| U+021BE | ↾ | \upharpoonright | Upwards Harpoon With Barb Rightwards / Up Harpoon With Barb Right |
| U+021BF | ↿ | \upharpoonleft | Upwards Harpoon With Barb Leftwards / Up Harpoon With Barb Left |
| U+021C0 | ⇀ | \rightharpoonup | Rightwards Harpoon With Barb Upwards / Right Harpoon With Barb Up |
| U+021C1 | ⇁ | \rightharpoondown | Rightwards Harpoon With Barb Downwards / Right Harpoon With Barb Down |
| U+021C2 | ⇂ | \downharpoonright | Downwards Harpoon With Barb Rightwards / Down Harpoon With Barb Right |
| U+021C3 | ⇃ | \downharpoonleft | Downwards Harpoon With Barb Leftwards / Down Harpoon With Barb Left |
| U+021C4 | ⇄ | \rightleftarrows | Rightwards Arrow Over Leftwards Arrow / Right Arrow Over Left Arrow |
| U+021C5 | ⇅ | \dblarrowupdown | Upwards Arrow Leftwards Of Downwards Arrow / Up Arrow Left Of Down Arrow |
| U+021C6 | ⇆ | \leftrightarrows | Leftwards Arrow Over Rightwards Arrow / Left Arrow Over Right Arrow |
| U+021C7 | ⇇ | \leftleftarrows | Leftwards Paired Arrows / Left Paired Arrows |
| U+021C8 | ⇈ | \upuparrows | Upwards Paired Arrows / Up Paired Arrows |
| U+021C9 | ⇉ | \rightrightarrows | Rightwards Paired Arrows / Right Paired Arrows |
| U+021CA | ⇊ | \downdownarrows | Downwards Paired Arrows / Down Paired Arrows |
| U+021CB | ⇋ | \leftrightharpoons | Leftwards Harpoon Over Rightwards Harpoon / Left Harpoon Over Right Harpoon |
| U+021CC | ⇌ | \rightleftharpoons | Rightwards Harpoon Over Leftwards Harpoon / Right Harpoon Over Left Harpoon |
| U+021CD | ⇍ | \nLeftarrow | Leftwards Double Arrow With Stroke / Left Double Arrow With Stroke |
| U+021CE | ⇎ | \nLeftrightarrow | Left Right Double Arrow With Stroke |
| U+021CF | ⇏ | \nRightarrow | Rightwards Double Arrow With Stroke / Right Double Arrow With Stroke |
| U+021D0 | ⇐ | \Leftarrow | Leftwards Double Arrow / Left Double Arrow |
| U+021D1 | ⇑ | \Uparrow | Upwards Double Arrow / Up Double Arrow |
| U+021D2 | ⇒ | \Rightarrow | Rightwards Double Arrow / Right Double Arrow |
| U+021D3 | ⇓ | \Downarrow | Downwards Double Arrow / Down Double Arrow |
| U+021D4 | ⇔ | \Leftrightarrow | Left Right Double Arrow |
| U+021D5 | ⇕ | \Updownarrow | Up Down Double Arrow |
| U+021D6 | ⇖ | \Nwarrow | North West Double Arrow / Upper Left Double Arrow |
| U+021D7 | ⇗ | \Nearrow | North East Double Arrow / Upper Right Double Arrow |
| U+021D8 | ⇘ | \Searrow | South East Double Arrow / Lower Right Double Arrow |
| U+021D9 | ⇙ | \Swarrow | South West Double Arrow / Lower Left Double Arrow |
| U+021DA | ⇚ | \Lleftarrow | Leftwards Triple Arrow / Left Triple Arrow |
| U+021DB | ⇛ | \Rrightarrow | Rightwards Triple Arrow / Right Triple Arrow |
| U+021DC | ⇜ | \leftsquigarrow | Leftwards Squiggle Arrow / Left Squiggle Arrow |
| U+021DD | ⇝ | \rightsquigarrow | Rightwards Squiggle Arrow / Right Squiggle Arrow |
| U+021DE | ⇞ | \nHuparrow | Upwards Arrow With Double Stroke / Up Arrow With Double Stroke |
| U+021DF | ⇟ | \nHdownarrow | Downwards Arrow With Double Stroke / Down Arrow With Double Stroke |
| U+021E0 | ⇠ | \leftdasharrow | Leftwards Dashed Arrow / Left Dashed Arrow |
| U+021E1 | ⇡ | \updasharrow | Upwards Dashed Arrow / Up Dashed Arrow |
| U+021E2 | ⇢ | \rightdasharrow | Rightwards Dashed Arrow / Right Dashed Arrow |
| U+021E3 | ⇣ | \downdasharrow | Downwards Dashed Arrow / Down Dashed Arrow |
| U+021E4 | ⇤ | \barleftarrow | Leftwards Arrow To Bar / Left Arrow To Bar |
| U+021E5 | ⇥ | \rightarrowbar | Rightwards Arrow To Bar / Right Arrow To Bar |
| U+021E6 | ⇦ | \leftwhitearrow | Leftwards White Arrow / White Left Arrow |
| U+021E7 | ⇧ | \upwhitearrow | Upwards White Arrow / White Up Arrow |
| U+021E8 | ⇨ | \rightwhitearrow | Rightwards White Arrow / White Right Arrow |
| U+021E9 | ⇩ | \downwhitearrow | Downwards White Arrow / White Down Arrow |
| U+021EA | ⇪ | \whitearrowupfrombar | Upwards White Arrow From Bar / White Up Arrow From Bar |
| U+021F4 | ⇴ | \circleonrightarrow | Right Arrow With Small Circle |
| U+021F5 | ⇵ | \DownArrowUpArrow | Downwards Arrow Leftwards Of Upwards Arrow |
| U+021F6 | ⇶ | \rightthreearrows | Three Rightwards Arrows |
| U+021F7 | ⇷ | \nvleftarrow | Leftwards Arrow With Vertical Stroke |
| U+021F8 | ⇸ | \nvrightarrow | Rightwards Arrow With Vertical Stroke |
| U+021F9 | ⇹ | \nvleftrightarrow | Left Right Arrow With Vertical Stroke |
| U+021FA | ⇺ | \nVleftarrow | Leftwards Arrow With Double Vertical Stroke |
| U+021FB | ⇻ | \nVrightarrow | Rightwards Arrow With Double Vertical Stroke |
| U+021FC | ⇼ | \nVleftrightarrow | Left Right Arrow With Double Vertical Stroke |
| U+021FD | ⇽ | \leftarrowtriangle | Leftwards Open-Headed Arrow |
| U+021FE | ⇾ | \rightarrowtriangle | Rightwards Open-Headed Arrow |
| U+021FF | ⇿ | \leftrightarrowtriangle | Left Right Open-Headed Arrow |
| U+02200 | ∀ | \forall | For All |
| U+02201 | ∁ | \complement | Complement |
| U+02202 | ∂ | \partial | Partial Differential |
| U+02203 | ∃ | \exists | There Exists |
| U+02204 | ∄ | \nexists | There Does Not Exist |
| U+02205 | ∅ | \varnothing, \emptyset | Empty Set |
| U+02206 | ∆ | \increment | Increment |
| U+02207 | ∇ | \del, \nabla | Nabla |
| U+02208 | ∈ | \in | Element Of |
| U+02209 | ∉ | \notin | Not An Element Of |
| U+0220A | ∊ | \smallin | Small Element Of |
| U+0220B | ∋ | \ni | Contains As Member |
| U+0220C | ∌ | \nni | Does Not Contain As Member |
| U+0220D | ∍ | \smallni | Small Contains As Member |
| U+0220E | ∎ | \QED | End Of Proof |
| U+0220F | ∏ | \prod | N-Ary Product |
| U+02210 | ∐ | \coprod | N-Ary Coproduct |
| U+02211 | ∑ | \sum | N-Ary Summation |
| U+02212 | − | \minus | Minus Sign |
| U+02213 | ∓ | \mp | Minus-Or-Plus Sign |
| U+02214 | ∔ | \dotplus | Dot Plus |
| U+02216 | ∖ | \setminus | Set Minus |
| U+02217 | ∗ | \ast | Asterisk Operator |
| U+02218 | ∘ | \circ | Ring Operator |
| U+02219 | ∙ | \vysmblkcircle | Bullet Operator |
| U+0221A | √ | \surd, \sqrt | Square Root |
| U+0221B | ∛ | \cbrt | Cube Root |
| U+0221C | ∜ | \fourthroot | Fourth Root |
| U+0221D | ∝ | \propto | Proportional To |
| U+0221E | ∞ | \infty | Infinity |
| U+0221F | ∟ | \rightangle | Right Angle |
| U+02220 | ∠ | \angle | Angle |
| U+02221 | ∡ | \measuredangle | Measured Angle |
| U+02222 | ∢ | \sphericalangle | Spherical Angle |
| U+02223 | ∣ | \mid | Divides |
| U+02224 | ∤ | \nmid | Does Not Divide |
| U+02225 | ∥ | \parallel | Parallel To |
| U+02226 | ∦ | \nparallel | Not Parallel To |
| U+02227 | ∧ | \wedge | Logical And |
| U+02228 | ∨ | \vee | Logical Or |
| U+02229 | ∩ | \cap | Intersection |
| U+0222A | ∪ | \cup | Union |
| U+0222B | ∫ | \int | Integral |
| U+0222C | ∬ | \iint | Double Integral |
| U+0222D | ∭ | \iiint | Triple Integral |
| U+0222E | ∮ | \oint | Contour Integral |
| U+0222F | ∯ | \oiint | Surface Integral |
| U+02230 | ∰ | \oiiint | Volume Integral |
| U+02231 | ∱ | \clwintegral | Clockwise Integral |
| U+02232 | ∲ | \varointclockwise | Clockwise Contour Integral |
| U+02233 | ∳ | \ointctrclockwise | Anticlockwise Contour Integral |
| U+02234 | ∴ | \therefore | Therefore |
| U+02235 | ∵ | \because | Because |
| U+02237 | ∷ | \Colon | Proportion |
| U+02238 | ∸ | \dotminus | Dot Minus |
| U+0223A | ∺ | \dotsminusdots | Geometric Proportion |
| U+0223B | ∻ | \kernelcontraction | Homothetic |
| U+0223C | ∼ | \sim | Tilde Operator |
| U+0223D | ∽ | \backsim | Reversed Tilde |
| U+0223E | ∾ | \lazysinv | Inverted Lazy S |
| U+0223F | ∿ | \sinewave | Sine Wave |
| U+02240 | ≀ | \wr | Wreath Product |
| U+02241 | ≁ | \nsim | Not Tilde |
| U+02242 | ≂ | \eqsim | Minus Tilde |
| U+02242 + U+00338 | ≂̸ | \neqsim | Minus Tilde + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02243 | ≃ | \simeq | Asymptotically Equal To |
| U+02244 | ≄ | \nsime | Not Asymptotically Equal To |
| U+02245 | ≅ | \cong | Approximately Equal To |
| U+02246 | ≆ | \approxnotequal | Approximately But Not Actually Equal To |
| U+02247 | ≇ | \ncong | Neither Approximately Nor Actually Equal To |
| U+02248 | ≈ | \approx | Almost Equal To |
| U+02249 | ≉ | \napprox | Not Almost Equal To |
| U+0224A | ≊ | \approxeq | Almost Equal Or Equal To |
| U+0224B | ≋ | \tildetrpl | Triple Tilde |
| U+0224C | ≌ | \allequal | All Equal To |
| U+0224D | ≍ | \asymp | Equivalent To |
| U+0224E | ≎ | \Bumpeq | Geometrically Equivalent To |
| U+0224E + U+00338 | ≎̸ | \nBumpeq | Geometrically Equivalent To + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+0224F | ≏ | \bumpeq | Difference Between |
| U+0224F + U+00338 | ≏̸ | \nbumpeq | Difference Between + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02250 | ≐ | \doteq | Approaches The Limit |
| U+02251 | ≑ | \Doteq | Geometrically Equal To |
| U+02252 | ≒ | \fallingdotseq | Approximately Equal To Or The Image Of |
| U+02253 | ≓ | \risingdotseq | Image Of Or Approximately Equal To |
| U+02254 | ≔ | \coloneq | Colon Equals / Colon Equal |
| U+02255 | ≕ | \eqcolon | Equals Colon / Equal Colon |
| U+02256 | ≖ | \eqcirc | Ring In Equal To |
| U+02257 | ≗ | \circeq | Ring Equal To |
| U+02258 | ≘ | \arceq | Corresponds To |
| U+02259 | ≙ | \wedgeq | Estimates |
| U+0225A | ≚ | \veeeq | Equiangular To |
| U+0225B | ≛ | \starequal | Star Equals |
| U+0225C | ≜ | \triangleq | Delta Equal To |
| U+0225D | ≝ | \eqdef | Equal To By Definition |
| U+0225E | ≞ | \measeq | Measured By |
| U+0225F | ≟ | \questeq | Questioned Equal To |
| U+02260 | ≠ | \ne | Not Equal To |
| U+02261 | ≡ | \equiv | Identical To |
| U+02262 | ≢ | \nequiv | Not Identical To |
| U+02263 | ≣ | \Equiv | Strictly Equivalent To |
| U+02264 | ≤ | \le, \leq | Less-Than Or Equal To / Less Than Or Equal To |
| U+02265 | ≥ | \ge, \geq | Greater-Than Or Equal To / Greater Than Or Equal To |
| U+02266 | ≦ | \leqq | Less-Than Over Equal To / Less Than Over Equal To |
| U+02267 | ≧ | \geqq | Greater-Than Over Equal To / Greater Than Over Equal To |
| U+02268 | ≨ | \lneqq | Less-Than But Not Equal To / Less Than But Not Equal To |
| U+02268 + U+0FE00 | ≨︀ | \lvertneqq | Less-Than But Not Equal To / Less Than But Not Equal To + Variation Selector-1 |
| U+02269 | ≩ | \gneqq | Greater-Than But Not Equal To / Greater Than But Not Equal To |
| U+02269 + U+0FE00 | ≩︀ | \gvertneqq | Greater-Than But Not Equal To / Greater Than But Not Equal To + Variation Selector-1 |
| U+0226A | ≪ | \ll | Much Less-Than / Much Less Than |
| U+0226A + U+00338 | ≪̸ | \NotLessLess | Much Less-Than / Much Less Than + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+0226B | ≫ | \gg | Much Greater-Than / Much Greater Than |
| U+0226B + U+00338 | ≫̸ | \NotGreaterGreater | Much Greater-Than / Much Greater Than + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+0226C | ≬ | \between | Between |
| U+0226D | ≭ | \nasymp | Not Equivalent To |
| U+0226E | ≮ | \nless | Not Less-Than / Not Less Than |
| U+0226F | ≯ | \ngtr | Not Greater-Than / Not Greater Than |
| U+02270 | ≰ | \nleq | Neither Less-Than Nor Equal To / Neither Less Than Nor Equal To |
| U+02271 | ≱ | \ngeq | Neither Greater-Than Nor Equal To / Neither Greater Than Nor Equal To |
| U+02272 | ≲ | \lesssim | Less-Than Or Equivalent To / Less Than Or Equivalent To |
| U+02273 | ≳ | \gtrsim | Greater-Than Or Equivalent To / Greater Than Or Equivalent To |
| U+02274 | ≴ | \nlesssim | Neither Less-Than Nor Equivalent To / Neither Less Than Nor Equivalent To |
| U+02275 | ≵ | \ngtrsim | Neither Greater-Than Nor Equivalent To / Neither Greater Than Nor Equivalent To |
| U+02276 | ≶ | \lessgtr | Less-Than Or Greater-Than / Less Than Or Greater Than |
| U+02277 | ≷ | \gtrless | Greater-Than Or Less-Than / Greater Than Or Less Than |
| U+02278 | ≸ | \notlessgreater | Neither Less-Than Nor Greater-Than / Neither Less Than Nor Greater Than |
| U+02279 | ≹ | \notgreaterless | Neither Greater-Than Nor Less-Than / Neither Greater Than Nor Less Than |
| U+0227A | ≺ | \prec | Precedes |
| U+0227B | ≻ | \succ | Succeeds |
| U+0227C | ≼ | \preccurlyeq | Precedes Or Equal To |
| U+0227D | ≽ | \succcurlyeq | Succeeds Or Equal To |
| U+0227E | ≾ | \precsim | Precedes Or Equivalent To |
| U+0227E + U+00338 | ≾̸ | \nprecsim | Precedes Or Equivalent To + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+0227F | ≿ | \succsim | Succeeds Or Equivalent To |
| U+0227F + U+00338 | ≿̸ | \nsuccsim | Succeeds Or Equivalent To + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02280 | ⊀ | \nprec | Does Not Precede |
| U+02281 | ⊁ | \nsucc | Does Not Succeed |
| U+02282 | ⊂ | \subset | Subset Of |
| U+02283 | ⊃ | \supset | Superset Of |
| U+02284 | ⊄ | \nsubset | Not A Subset Of |
| U+02285 | ⊅ | \nsupset | Not A Superset Of |
| U+02286 | ⊆ | \subseteq | Subset Of Or Equal To |
| U+02287 | ⊇ | \supseteq | Superset Of Or Equal To |
| U+02288 | ⊈ | \nsubseteq | Neither A Subset Of Nor Equal To |
| U+02289 | ⊉ | \nsupseteq | Neither A Superset Of Nor Equal To |
| U+0228A | ⊊ | \subsetneq | Subset Of With Not Equal To / Subset Of Or Not Equal To |
| U+0228A + U+0FE00 | ⊊︀ | \varsubsetneqq | Subset Of With Not Equal To / Subset Of Or Not Equal To + Variation Selector-1 |
| U+0228B | ⊋ | \supsetneq | Superset Of With Not Equal To / Superset Of Or Not Equal To |
| U+0228B + U+0FE00 | ⊋︀ | \varsupsetneq | Superset Of With Not Equal To / Superset Of Or Not Equal To + Variation Selector-1 |
| U+0228D | ⊍ | \cupdot | Multiset Multiplication |
| U+0228E | ⊎ | \uplus | Multiset Union |
| U+0228F | ⊏ | \sqsubset | Square Image Of |
| U+0228F + U+00338 | ⊏̸ | \NotSquareSubset | Square Image Of + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02290 | ⊐ | \sqsupset | Square Original Of |
| U+02290 + U+00338 | ⊐̸ | \NotSquareSuperset | Square Original Of + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02291 | ⊑ | \sqsubseteq | Square Image Of Or Equal To |
| U+02292 | ⊒ | \sqsupseteq | Square Original Of Or Equal To |
| U+02293 | ⊓ | \sqcap | Square Cap |
| U+02294 | ⊔ | \sqcup | Square Cup |
| U+02295 | ⊕ | \oplus | Circled Plus |
| U+02296 | ⊖ | \ominus | Circled Minus |
| U+02297 | ⊗ | \otimes | Circled Times |
| U+02298 | ⊘ | \oslash | Circled Division Slash |
| U+02299 | ⊙ | \odot | Circled Dot Operator |
| U+0229A | ⊚ | \circledcirc | Circled Ring Operator |
| U+0229B | ⊛ | \circledast | Circled Asterisk Operator |
| U+0229C | ⊜ | \circledequal | Circled Equals |
| U+0229D | ⊝ | \circleddash | Circled Dash |
| U+0229E | ⊞ | \boxplus | Squared Plus |
| U+0229F | ⊟ | \boxminus | Squared Minus |
| U+022A0 | ⊠ | \boxtimes | Squared Times |
| U+022A1 | ⊡ | \boxdot | Squared Dot Operator |
| U+022A2 | ⊢ | \vdash | Right Tack |
| U+022A3 | ⊣ | \dashv | Left Tack |
| U+022A4 | ⊤ | \top | Down Tack |
| U+022A5 | ⊥ | \bot | Up Tack |
| U+022A7 | ⊧ | \models | Models |
| U+022A8 | ⊨ | \vDash | True |
| U+022A9 | ⊩ | \Vdash | Forces |
| U+022AA | ⊪ | \Vvdash | Triple Vertical Bar Right Turnstile |
| U+022AB | ⊫ | \VDash | Double Vertical Bar Double Right Turnstile |
| U+022AC | ⊬ | \nvdash | Does Not Prove |
| U+022AD | ⊭ | \nvDash | Not True |
| U+022AE | ⊮ | \nVdash | Does Not Force |
| U+022AF | ⊯ | \nVDash | Negated Double Vertical Bar Double Right Turnstile |
| U+022B0 | ⊰ | \prurel | Precedes Under Relation |
| U+022B1 | ⊱ | \scurel | Succeeds Under Relation |
| U+022B2 | ⊲ | \vartriangleleft | Normal Subgroup Of |
| U+022B3 | ⊳ | \vartriangleright | Contains As Normal Subgroup |
| U+022B4 | ⊴ | \trianglelefteq | Normal Subgroup Of Or Equal To |
| U+022B5 | ⊵ | \trianglerighteq | Contains As Normal Subgroup Or Equal To |
| U+022B6 | ⊶ | \original | Original Of |
| U+022B7 | ⊷ | \image | Image Of |
| U+022B8 | ⊸ | \multimap | Multimap |
| U+022B9 | ⊹ | \hermitconjmatrix | Hermitian Conjugate Matrix |
| U+022BA | ⊺ | \intercal | Intercalate |
| U+022BB | ⊻ | \veebar, \xor | Xor |
| U+022BC | ⊼ | \barwedge, \nand | Nand |
| U+022BD | ⊽ | \barvee, \nor | Nor |
| U+022BE | ⊾ | \rightanglearc | Right Angle With Arc |
| U+022BF | ⊿ | \varlrtriangle | Right Triangle |
| U+022C0 | ⋀ | \bigwedge | N-Ary Logical And |
| U+022C1 | ⋁ | \bigvee | N-Ary Logical Or |
| U+022C2 | ⋂ | \bigcap | N-Ary Intersection |
| U+022C3 | ⋃ | \bigcup | N-Ary Union |
| U+022C4 | ⋄ | \diamond | Diamond Operator |
| U+022C5 | ⋅ | \cdot | Dot Operator |
| U+022C6 | ⋆ | \star | Star Operator |
| U+022C7 | ⋇ | \divideontimes | Division Times |
| U+022C8 | ⋈ | \bowtie | Bowtie |
| U+022C9 | ⋉ | \ltimes | Left Normal Factor Semidirect Product |
| U+022CA | ⋊ | \rtimes | Right Normal Factor Semidirect Product |
| U+022CB | ⋋ | \leftthreetimes | Left Semidirect Product |
| U+022CC | ⋌ | \rightthreetimes | Right Semidirect Product |
| U+022CD | ⋍ | \backsimeq | Reversed Tilde Equals |
| U+022CE | ⋎ | \curlyvee | Curly Logical Or |
| U+022CF | ⋏ | \curlywedge | Curly Logical And |
| U+022D0 | ⋐ | \Subset | Double Subset |
| U+022D1 | ⋑ | \Supset | Double Superset |
| U+022D2 | ⋒ | \Cap | Double Intersection |
| U+022D3 | ⋓ | \Cup | Double Union |
| U+022D4 | ⋔ | \pitchfork | Pitchfork |
| U+022D5 | ⋕ | \equalparallel | Equal And Parallel To |
| U+022D6 | ⋖ | \lessdot | Less-Than With Dot / Less Than With Dot |
| U+022D7 | ⋗ | \gtrdot | Greater-Than With Dot / Greater Than With Dot |
| U+022D8 | ⋘ | \verymuchless | Very Much Less-Than / Very Much Less Than |
| U+022D9 | ⋙ | \ggg | Very Much Greater-Than / Very Much Greater Than |
| U+022DA | ⋚ | \lesseqgtr | Less-Than Equal To Or Greater-Than / Less Than Equal To Or Greater Than |
| U+022DB | ⋛ | \gtreqless | Greater-Than Equal To Or Less-Than / Greater Than Equal To Or Less Than |
| U+022DC | ⋜ | \eqless | Equal To Or Less-Than / Equal To Or Less Than |
| U+022DD | ⋝ | \eqgtr | Equal To Or Greater-Than / Equal To Or Greater Than |
| U+022DE | ⋞ | \curlyeqprec | Equal To Or Precedes |
| U+022DF | ⋟ | \curlyeqsucc | Equal To Or Succeeds |
| U+022E0 | ⋠ | \npreccurlyeq | Does Not Precede Or Equal |
| U+022E1 | ⋡ | \nsucccurlyeq | Does Not Succeed Or Equal |
| U+022E2 | ⋢ | \nsqsubseteq | Not Square Image Of Or Equal To |
| U+022E3 | ⋣ | \nsqsupseteq | Not Square Original Of Or Equal To |
| U+022E4 | ⋤ | \sqsubsetneq | Square Image Of Or Not Equal To |
| U+022E5 | ⋥ | \sqspne | Square Original Of Or Not Equal To |
| U+022E6 | ⋦ | \lnsim | Less-Than But Not Equivalent To / Less Than But Not Equivalent To |
| U+022E7 | ⋧ | \gnsim | Greater-Than But Not Equivalent To / Greater Than But Not Equivalent To |
| U+022E8 | ⋨ | \precnsim | Precedes But Not Equivalent To |
| U+022E9 | ⋩ | \succnsim | Succeeds But Not Equivalent To |
| U+022EA | ⋪ | \ntriangleleft | Not Normal Subgroup Of |
| U+022EB | ⋫ | \ntriangleright | Does Not Contain As Normal Subgroup |
| U+022EC | ⋬ | \ntrianglelefteq | Not Normal Subgroup Of Or Equal To |
| U+022ED | ⋭ | \ntrianglerighteq | Does Not Contain As Normal Subgroup Or Equal |
| U+022EE | ⋮ | \vdots | Vertical Ellipsis |
| U+022EF | ⋯ | \cdots | Midline Horizontal Ellipsis |
| U+022F0 | ⋰ | \adots | Up Right Diagonal Ellipsis |
| U+022F1 | ⋱ | \ddots | Down Right Diagonal Ellipsis |
| U+022F2 | ⋲ | \disin | Element Of With Long Horizontal Stroke |
| U+022F3 | ⋳ | \varisins | Element Of With Vertical Bar At End Of Horizontal Stroke |
| U+022F4 | ⋴ | \isins | Small Element Of With Vertical Bar At End Of Horizontal Stroke |
| U+022F5 | ⋵ | \isindot | Element Of With Dot Above |
| U+022F6 | ⋶ | \varisinobar | Element Of With Overbar |
| U+022F7 | ⋷ | \isinobar | Small Element Of With Overbar |
| U+022F8 | ⋸ | \isinvb | Element Of With Underbar |
| U+022F9 | ⋹ | \isinE | Element Of With Two Horizontal Strokes |
| U+022FA | ⋺ | \nisd | Contains With Long Horizontal Stroke |
| U+022FB | ⋻ | \varnis | Contains With Vertical Bar At End Of Horizontal Stroke |
| U+022FC | ⋼ | \nis | Small Contains With Vertical Bar At End Of Horizontal Stroke |
| U+022FD | ⋽ | \varniobar | Contains With Overbar |
| U+022FE | ⋾ | \niobar | Small Contains With Overbar |
| U+022FF | ⋿ | \bagmember | Z Notation Bag Membership |
| U+02300 | ⌀ | \diameter | Diameter Sign |
| U+02302 | ⌂ | \house | House |
| U+02305 | ⌅ | \varbarwedge | Projective |
| U+02306 | ⌆ | \vardoublebarwedge | Perspective |
| U+02308 | ⌈ | \lceil | Left Ceiling |
| U+02309 | ⌉ | \rceil | Right Ceiling |
| U+0230A | ⌊ | \lfloor | Left Floor |
| U+0230B | ⌋ | \rfloor | Right Floor |
| U+02310 | ⌐ | \invnot | Reversed Not Sign |
| U+02311 | ⌑ | \sqlozenge | Square Lozenge |
| U+02312 | ⌒ | \profline | Arc |
| U+02313 | ⌓ | \profsurf | Segment |
| U+02315 | ⌕ | \recorder | Telephone Recorder |
| U+02317 | ⌗ | \viewdata | Viewdata Square |
| U+02319 | ⌙ | \turnednot | Turned Not Sign |
| U+0231A | ⌚ | \:watch: | Watch |
| U+0231B | ⌛ | \:hourglass: | Hourglass |
| U+0231C | ⌜ | \ulcorner | Top Left Corner |
| U+0231D | ⌝ | \urcorner | Top Right Corner |
| U+0231E | ⌞ | \llcorner | Bottom Left Corner |
| U+0231F | ⌟ | \lrcorner | Bottom Right Corner |
| U+02322 | ⌢ | \frown | Frown |
| U+02323 | ⌣ | \smile | Smile |
| U+0232C | ⌬ | \varhexagonlrbonds | Benzene Ring |
| U+02332 | ⌲ | \conictaper | Conical Taper |
| U+02336 | ⌶ | \topbot | Apl Functional Symbol I-Beam |
| U+0233D | ⌽ | \obar | Apl Functional Symbol Circle Stile |
| U+0233F | ⌿ | \notslash | Apl Functional Symbol Slash Bar |
| U+02340 | ⍀ | \notbackslash | Apl Functional Symbol Backslash Bar |
| U+02353 | ⍓ | \boxupcaret | Apl Functional Symbol Quad Up Caret |
| U+02370 | ⍰ | \boxquestion | Apl Functional Symbol Quad Question |
| U+02394 | ⎔ | \hexagon | Software-Function Symbol |
| U+023A3 | ⎣ | \dlcorn | Left Square Bracket Lower Corner |
| U+023B0 | ⎰ | \lmoustache | Upper Left Or Lower Right Curly Bracket Section |
| U+023B1 | ⎱ | \rmoustache | Upper Right Or Lower Left Curly Bracket Section |
| U+023B4 | ⎴ | \overbracket | Top Square Bracket |
| U+023B5 | ⎵ | \underbracket | Bottom Square Bracket |
| U+023B6 | ⎶ | \bbrktbrk | Bottom Square Bracket Over Top Square Bracket |
| U+023B7 | ⎷ | \sqrtbottom | Radical Symbol Bottom |
| U+023B8 | ⎸ | \lvboxline | Left Vertical Box Line |
| U+023B9 | ⎹ | \rvboxline | Right Vertical Box Line |
| U+023CE | ⏎ | \varcarriagereturn | Return Symbol |
| U+023DE | ⏞ | \overbrace | Top Curly Bracket |
| U+023DF | ⏟ | \underbrace | Bottom Curly Bracket |
| U+023E2 | ⏢ | \trapezium | White Trapezium |
| U+023E3 | ⏣ | \benzenr | Benzene Ring With Circle |
| U+023E4 | ⏤ | \strns | Straightness |
| U+023E5 | ⏥ | \fltns | Flatness |
| U+023E6 | ⏦ | \accurrent | Ac Current |
| U+023E7 | ⏧ | \elinters | Electrical Intersection |
| U+023E9 | ⏩ | \:fast\_forward: | Black Right-Pointing Double Triangle |
| U+023EA | ⏪ | \:rewind: | Black Left-Pointing Double Triangle |
| U+023EB | ⏫ | \:arrow\_double\_up: | Black Up-Pointing Double Triangle |
| U+023EC | ⏬ | \:arrow\_double\_down: | Black Down-Pointing Double Triangle |
| U+023F0 | ⏰ | \:alarm\_clock: | Alarm Clock |
| U+023F3 | ⏳ | \:hourglass\_flowing\_sand: | Hourglass With Flowing Sand |
| U+02422 | ␢ | \blanksymbol | Blank Symbol / Blank |
| U+02423 | ␣ | \visiblespace | Open Box |
| U+024C2 | Ⓜ | \:m: | Circled Latin Capital Letter M |
| U+024C8 | Ⓢ | \circledS | Circled Latin Capital Letter S |
| U+02506 | ┆ | \dshfnc | Box Drawings Light Triple Dash Vertical / Forms Light Triple Dash Vertical |
| U+02519 | ┙ | \sqfnw | Box Drawings Up Light And Left Heavy / Forms Up Light And Left Heavy |
| U+02571 | ╱ | \diagup | Box Drawings Light Diagonal Upper Right To Lower Left / Forms Light Diagonal Upper Right To Lower Left |
| U+02572 | ╲ | \diagdown | Box Drawings Light Diagonal Upper Left To Lower Right / Forms Light Diagonal Upper Left To Lower Right |
| U+02580 | ▀ | \blockuphalf | Upper Half Block |
| U+02584 | ▄ | \blocklowhalf | Lower Half Block |
| U+02588 | █ | \blockfull | Full Block |
| U+0258C | ▌ | \blocklefthalf | Left Half Block |
| U+02590 | ▐ | \blockrighthalf | Right Half Block |
| U+02591 | ░ | \blockqtrshaded | Light Shade |
| U+02592 | ▒ | \blockhalfshaded | Medium Shade |
| U+02593 | ▓ | \blockthreeqtrshaded | Dark Shade |
| U+025A0 | ■ | \blacksquare | Black Square |
| U+025A1 | □ | \square | White Square |
| U+025A2 | ▢ | \squoval | White Square With Rounded Corners |
| U+025A3 | ▣ | \blackinwhitesquare | White Square Containing Black Small Square |
| U+025A4 | ▤ | \squarehfill | Square With Horizontal Fill |
| U+025A5 | ▥ | \squarevfill | Square With Vertical Fill |
| U+025A6 | ▦ | \squarehvfill | Square With Orthogonal Crosshatch Fill |
| U+025A7 | ▧ | \squarenwsefill | Square With Upper Left To Lower Right Fill |
| U+025A8 | ▨ | \squareneswfill | Square With Upper Right To Lower Left Fill |
| U+025A9 | ▩ | \squarecrossfill | Square With Diagonal Crosshatch Fill |
| U+025AA | ▪ | \smblksquare, \:black\_small\_square: | Black Small Square |
| U+025AB | ▫ | \smwhtsquare, \:white\_small\_square: | White Small Square |
| U+025AC | ▬ | \hrectangleblack | Black Rectangle |
| U+025AD | ▭ | \hrectangle | White Rectangle |
| U+025AE | ▮ | \vrectangleblack | Black Vertical Rectangle |
| U+025AF | ▯ | \vrecto | White Vertical Rectangle |
| U+025B0 | ▰ | \parallelogramblack | Black Parallelogram |
| U+025B1 | ▱ | \parallelogram | White Parallelogram |
| U+025B2 | ▲ | \bigblacktriangleup | Black Up-Pointing Triangle / Black Up Pointing Triangle |
| U+025B3 | △ | \bigtriangleup | White Up-Pointing Triangle / White Up Pointing Triangle |
| U+025B4 | ▴ | \blacktriangle | Black Up-Pointing Small Triangle / Black Up Pointing Small Triangle |
| U+025B5 | ▵ | \vartriangle | White Up-Pointing Small Triangle / White Up Pointing Small Triangle |
| U+025B6 | ▶ | \blacktriangleright, \:arrow\_forward: | Black Right-Pointing Triangle / Black Right Pointing Triangle |
| U+025B7 | ▷ | \triangleright | White Right-Pointing Triangle / White Right Pointing Triangle |
| U+025B8 | ▸ | \smallblacktriangleright | Black Right-Pointing Small Triangle / Black Right Pointing Small Triangle |
| U+025B9 | ▹ | \smalltriangleright | White Right-Pointing Small Triangle / White Right Pointing Small Triangle |
| U+025BA | ► | \blackpointerright | Black Right-Pointing Pointer / Black Right Pointing Pointer |
| U+025BB | ▻ | \whitepointerright | White Right-Pointing Pointer / White Right Pointing Pointer |
| U+025BC | ▼ | \bigblacktriangledown | Black Down-Pointing Triangle / Black Down Pointing Triangle |
| U+025BD | ▽ | \bigtriangledown | White Down-Pointing Triangle / White Down Pointing Triangle |
| U+025BE | ▾ | \blacktriangledown | Black Down-Pointing Small Triangle / Black Down Pointing Small Triangle |
| U+025BF | ▿ | \triangledown | White Down-Pointing Small Triangle / White Down Pointing Small Triangle |
| U+025C0 | ◀ | \blacktriangleleft, \:arrow\_backward: | Black Left-Pointing Triangle / Black Left Pointing Triangle |
| U+025C1 | ◁ | \triangleleft | White Left-Pointing Triangle / White Left Pointing Triangle |
| U+025C2 | ◂ | \smallblacktriangleleft | Black Left-Pointing Small Triangle / Black Left Pointing Small Triangle |
| U+025C3 | ◃ | \smalltriangleleft | White Left-Pointing Small Triangle / White Left Pointing Small Triangle |
| U+025C4 | ◄ | \blackpointerleft | Black Left-Pointing Pointer / Black Left Pointing Pointer |
| U+025C5 | ◅ | \whitepointerleft | White Left-Pointing Pointer / White Left Pointing Pointer |
| U+025C6 | ◆ | \mdlgblkdiamond | Black Diamond |
| U+025C7 | ◇ | \mdlgwhtdiamond | White Diamond |
| U+025C8 | ◈ | \blackinwhitediamond | White Diamond Containing Black Small Diamond |
| U+025C9 | ◉ | \fisheye | Fisheye |
| U+025CA | ◊ | \lozenge | Lozenge |
| U+025CB | ○ | \bigcirc | White Circle |
| U+025CC | ◌ | \dottedcircle | Dotted Circle |
| U+025CD | ◍ | \circlevertfill | Circle With Vertical Fill |
| U+025CE | ◎ | \bullseye | Bullseye |
| U+025CF | ● | \mdlgblkcircle | Black Circle |
| U+025D0 | ◐ | \cirfl | Circle With Left Half Black |
| U+025D1 | ◑ | \cirfr | Circle With Right Half Black |
| U+025D2 | ◒ | \cirfb | Circle With Lower Half Black |
| U+025D3 | ◓ | \circletophalfblack | Circle With Upper Half Black |
| U+025D4 | ◔ | \circleurquadblack | Circle With Upper Right Quadrant Black |
| U+025D5 | ◕ | \blackcircleulquadwhite | Circle With All But Upper Left Quadrant Black |
| U+025D6 | ◖ | \blacklefthalfcircle | Left Half Black Circle |
| U+025D7 | ◗ | \blackrighthalfcircle | Right Half Black Circle |
| U+025D8 | ◘ | \rvbull | Inverse Bullet |
| U+025D9 | ◙ | \inversewhitecircle | Inverse White Circle |
| U+025DA | ◚ | \invwhiteupperhalfcircle | Upper Half Inverse White Circle |
| U+025DB | ◛ | \invwhitelowerhalfcircle | Lower Half Inverse White Circle |
| U+025DC | ◜ | \ularc | Upper Left Quadrant Circular Arc |
| U+025DD | ◝ | \urarc | Upper Right Quadrant Circular Arc |
| U+025DE | ◞ | \lrarc | Lower Right Quadrant Circular Arc |
| U+025DF | ◟ | \llarc | Lower Left Quadrant Circular Arc |
| U+025E0 | ◠ | \topsemicircle | Upper Half Circle |
| U+025E1 | ◡ | \botsemicircle | Lower Half Circle |
| U+025E2 | ◢ | \lrblacktriangle | Black Lower Right Triangle |
| U+025E3 | ◣ | \llblacktriangle | Black Lower Left Triangle |
| U+025E4 | ◤ | \ulblacktriangle | Black Upper Left Triangle |
| U+025E5 | ◥ | \urblacktriangle | Black Upper Right Triangle |
| U+025E6 | ◦ | \smwhtcircle | White Bullet |
| U+025E7 | ◧ | \sqfl | Square With Left Half Black |
| U+025E8 | ◨ | \sqfr | Square With Right Half Black |
| U+025E9 | ◩ | \squareulblack | Square With Upper Left Diagonal Half Black |
| U+025EA | ◪ | \sqfse | Square With Lower Right Diagonal Half Black |
| U+025EB | ◫ | \boxbar | White Square With Vertical Bisecting Line |
| U+025EC | ◬ | \trianglecdot | White Up-Pointing Triangle With Dot / White Up Pointing Triangle With Dot |
| U+025ED | ◭ | \triangleleftblack | Up-Pointing Triangle With Left Half Black / Up Pointing Triangle With Left Half Black |
| U+025EE | ◮ | \trianglerightblack | Up-Pointing Triangle With Right Half Black / Up Pointing Triangle With Right Half Black |
| U+025EF | ◯ | \lgwhtcircle | Large Circle |
| U+025F0 | ◰ | \squareulquad | White Square With Upper Left Quadrant |
| U+025F1 | ◱ | \squarellquad | White Square With Lower Left Quadrant |
| U+025F2 | ◲ | \squarelrquad | White Square With Lower Right Quadrant |
| U+025F3 | ◳ | \squareurquad | White Square With Upper Right Quadrant |
| U+025F4 | ◴ | \circleulquad | White Circle With Upper Left Quadrant |
| U+025F5 | ◵ | \circlellquad | White Circle With Lower Left Quadrant |
| U+025F6 | ◶ | \circlelrquad | White Circle With Lower Right Quadrant |
| U+025F7 | ◷ | \circleurquad | White Circle With Upper Right Quadrant |
| U+025F8 | ◸ | \ultriangle | Upper Left Triangle |
| U+025F9 | ◹ | \urtriangle | Upper Right Triangle |
| U+025FA | ◺ | \lltriangle | Lower Left Triangle |
| U+025FB | ◻ | \mdwhtsquare, \:white\_medium\_square: | White Medium Square |
| U+025FC | ◼ | \mdblksquare, \:black\_medium\_square: | Black Medium Square |
| U+025FD | ◽ | \mdsmwhtsquare, \:white\_medium\_small\_square: | White Medium Small Square |
| U+025FE | ◾ | \mdsmblksquare, \:black\_medium\_small\_square: | Black Medium Small Square |
| U+025FF | ◿ | \lrtriangle | Lower Right Triangle |
| U+02600 | ☀ | \:sunny: | Black Sun With Rays |
| U+02601 | ☁ | \:cloud: | Cloud |
| U+02605 | ★ | \bigstar | Black Star |
| U+02606 | ☆ | \bigwhitestar | White Star |
| U+02609 | ☉ | \astrosun | Sun |
| U+0260E | ☎ | \:phone: | Black Telephone |
| U+02611 | ☑ | \:ballot\_box\_with\_check: | Ballot Box With Check |
| U+02614 | ☔ | \:umbrella\_with\_rain\_drops:, \:umbrella: | Umbrella With Rain Drops |
| U+02615 | ☕ | \:coffee: | Hot Beverage |
| U+0261D | ☝ | \:point\_up: | White Up Pointing Index |
| U+02621 | ☡ | \danger | Caution Sign |
| U+0263A | ☺ | \:relaxed: | White Smiling Face |
| U+0263B | ☻ | \blacksmiley | Black Smiling Face |
| U+0263C | ☼ | \sun | White Sun With Rays |
| U+0263D | ☽ | \rightmoon | First Quarter Moon |
| U+0263E | ☾ | \leftmoon | Last Quarter Moon |
| U+0263F | ☿ | \mercury | Mercury |
| U+02640 | ♀ | \venus, \female | Female Sign |
| U+02642 | ♂ | \male, \mars | Male Sign |
| U+02643 | ♃ | \jupiter | Jupiter |
| U+02644 | ♄ | \saturn | Saturn |
| U+02645 | ♅ | \uranus | Uranus |
| U+02646 | ♆ | \neptune | Neptune |
| U+02647 | ♇ | \pluto | Pluto |
| U+02648 | ♈ | \aries, \:aries: | Aries |
| U+02649 | ♉ | \taurus, \:taurus: | Taurus |
| U+0264A | ♊ | \gemini, \:gemini: | Gemini |
| U+0264B | ♋ | \cancer, \:cancer: | Cancer |
| U+0264C | ♌ | \leo, \:leo: | Leo |
| U+0264D | ♍ | \virgo, \:virgo: | Virgo |
| U+0264E | ♎ | \libra, \:libra: | Libra |
| U+0264F | ♏ | \scorpio, \:scorpius: | Scorpius |
| U+02650 | ♐ | \sagittarius, \:sagittarius: | Sagittarius |
| U+02651 | ♑ | \capricornus, \:capricorn: | Capricorn |
| U+02652 | ♒ | \aquarius, \:aquarius: | Aquarius |
| U+02653 | ♓ | \pisces, \:pisces: | Pisces |
| U+02660 | ♠ | \spadesuit, \:spades: | Black Spade Suit |
| U+02661 | ♡ | \heartsuit | White Heart Suit |
| U+02662 | ♢ | \diamondsuit | White Diamond Suit |
| U+02663 | ♣ | \clubsuit, \:clubs: | Black Club Suit |
| U+02664 | ♤ | \varspadesuit | White Spade Suit |
| U+02665 | ♥ | \varheartsuit, \:hearts: | Black Heart Suit |
| U+02666 | ♦ | \vardiamondsuit, \:diamonds: | Black Diamond Suit |
| U+02667 | ♧ | \varclubsuit | White Club Suit |
| U+02668 | ♨ | \:hotsprings: | Hot Springs |
| U+02669 | ♩ | \quarternote | Quarter Note |
| U+0266A | ♪ | \eighthnote | Eighth Note |
| U+0266B | ♫ | \twonotes | Beamed Eighth Notes / Barred Eighth Notes |
| U+0266D | ♭ | \flat | Music Flat Sign / Flat |
| U+0266E | ♮ | \natural | Music Natural Sign / Natural |
| U+0266F | ♯ | \sharp | Music Sharp Sign / Sharp |
| U+0267B | ♻ | \:recycle: | Black Universal Recycling Symbol |
| U+0267E | ♾ | \acidfree | Permanent Paper Sign |
| U+0267F | ♿ | \:wheelchair: | Wheelchair Symbol |
| U+02680 | ⚀ | \dicei | Die Face-1 |
| U+02681 | ⚁ | \diceii | Die Face-2 |
| U+02682 | ⚂ | \diceiii | Die Face-3 |
| U+02683 | ⚃ | \diceiv | Die Face-4 |
| U+02684 | ⚄ | \dicev | Die Face-5 |
| U+02685 | ⚅ | \dicevi | Die Face-6 |
| U+02686 | ⚆ | \circledrightdot | White Circle With Dot Right |
| U+02687 | ⚇ | \circledtwodots | White Circle With Two Dots |
| U+02688 | ⚈ | \blackcircledrightdot | Black Circle With White Dot Right |
| U+02689 | ⚉ | \blackcircledtwodots | Black Circle With Two White Dots |
| U+02693 | ⚓ | \:anchor: | Anchor |
| U+026A0 | ⚠ | \:warning: | Warning Sign |
| U+026A1 | ⚡ | \:zap: | High Voltage Sign |
| U+026A5 | ⚥ | \hermaphrodite | Male And Female Sign |
| U+026AA | ⚪ | \mdwhtcircle, \:white\_circle: | Medium White Circle |
| U+026AB | ⚫ | \mdblkcircle, \:black\_circle: | Medium Black Circle |
| U+026AC | ⚬ | \mdsmwhtcircle | Medium Small White Circle |
| U+026B2 | ⚲ | \neuter | Neuter |
| U+026BD | ⚽ | \:soccer: | Soccer Ball |
| U+026BE | ⚾ | \:baseball: | Baseball |
| U+026C4 | ⛄ | \:snowman:, \:snowman\_without\_snow: | Snowman Without Snow |
| U+026C5 | ⛅ | \:partly\_sunny: | Sun Behind Cloud |
| U+026CE | ⛎ | \:ophiuchus: | Ophiuchus |
| U+026D4 | ⛔ | \:no\_entry: | No Entry |
| U+026EA | ⛪ | \:church: | Church |
| U+026F2 | ⛲ | \:fountain: | Fountain |
| U+026F3 | ⛳ | \:golf: | Flag In Hole |
| U+026F5 | ⛵ | \:boat: | Sailboat |
| U+026FA | ⛺ | \:tent: | Tent |
| U+026FD | ⛽ | \:fuelpump: | Fuel Pump |
| U+02702 | ✂ | \:scissors: | Black Scissors |
| U+02705 | ✅ | \:white\_check\_mark: | White Heavy Check Mark |
| U+02708 | ✈ | \:airplane: | Airplane |
| U+02709 | ✉ | \:email: | Envelope |
| U+0270A | ✊ | \:fist: | Raised Fist |
| U+0270B | ✋ | \:hand: | Raised Hand |
| U+0270C | ✌ | \:v: | Victory Hand |
| U+0270F | ✏ | \:pencil2: | Pencil |
| U+02712 | ✒ | \:black\_nib: | Black Nib |
| U+02713 | ✓ | \checkmark | Check Mark |
| U+02714 | ✔ | \:heavy\_check\_mark: | Heavy Check Mark |
| U+02716 | ✖ | \:heavy\_multiplication\_x: | Heavy Multiplication X |
| U+02720 | ✠ | \maltese | Maltese Cross |
| U+02728 | ✨ | \:sparkles: | Sparkles |
| U+0272A | ✪ | \circledstar | Circled White Star |
| U+02733 | ✳ | \:eight\_spoked\_asterisk: | Eight Spoked Asterisk |
| U+02734 | ✴ | \:eight\_pointed\_black\_star: | Eight Pointed Black Star |
| U+02736 | ✶ | \varstar | Six Pointed Black Star |
| U+0273D | ✽ | \dingasterisk | Heavy Teardrop-Spoked Asterisk |
| U+02744 | ❄ | \:snowflake: | Snowflake |
| U+02747 | ❇ | \:sparkle: | Sparkle |
| U+0274C | ❌ | \:x: | Cross Mark |
| U+0274E | ❎ | \:negative\_squared\_cross\_mark: | Negative Squared Cross Mark |
| U+02753 | ❓ | \:question: | Black Question Mark Ornament |
| U+02754 | ❔ | \:grey\_question: | White Question Mark Ornament |
| U+02755 | ❕ | \:grey\_exclamation: | White Exclamation Mark Ornament |
| U+02757 | ❗ | \:exclamation: | Heavy Exclamation Mark Symbol |
| U+02764 | ❤ | \:heart: | Heavy Black Heart |
| U+02795 | ➕ | \:heavy\_plus\_sign: | Heavy Plus Sign |
| U+02796 | ➖ | \:heavy\_minus\_sign: | Heavy Minus Sign |
| U+02797 | ➗ | \:heavy\_division\_sign: | Heavy Division Sign |
| U+0279B | ➛ | \draftingarrow | Drafting Point Rightwards Arrow / Drafting Point Right Arrow |
| U+027A1 | ➡ | \:arrow\_right: | Black Rightwards Arrow / Black Right Arrow |
| U+027B0 | ➰ | \:curly\_loop: | Curly Loop |
| U+027BF | ➿ | \:loop: | Double Curly Loop |
| U+027C0 | ⟀ | \threedangle | Three Dimensional Angle |
| U+027C1 | ⟁ | \whiteinwhitetriangle | White Triangle Containing Small White Triangle |
| U+027C2 | ⟂ | \perp | Perpendicular |
| U+027C8 | ⟈ | \bsolhsub | Reverse Solidus Preceding Subset |
| U+027C9 | ⟉ | \suphsol | Superset Preceding Solidus |
| U+027D1 | ⟑ | \wedgedot | And With Dot |
| U+027D2 | ⟒ | \upin | Element Of Opening Upwards |
| U+027D5 | ⟕ | \leftouterjoin | Left Outer Join |
| U+027D6 | ⟖ | \rightouterjoin | Right Outer Join |
| U+027D7 | ⟗ | \fullouterjoin | Full Outer Join |
| U+027D8 | ⟘ | \bigbot | Large Up Tack |
| U+027D9 | ⟙ | \bigtop | Large Down Tack |
| U+027E6 | ⟦ | \llbracket, \openbracketleft | Mathematical Left White Square Bracket |
| U+027E7 | ⟧ | \openbracketright, \rrbracket | Mathematical Right White Square Bracket |
| U+027E8 | ⟨ | \langle | Mathematical Left Angle Bracket |
| U+027E9 | ⟩ | \rangle | Mathematical Right Angle Bracket |
| U+027F0 | ⟰ | \UUparrow | Upwards Quadruple Arrow |
| U+027F1 | ⟱ | \DDownarrow | Downwards Quadruple Arrow |
| U+027F5 | ⟵ | \longleftarrow | Long Leftwards Arrow |
| U+027F6 | ⟶ | \longrightarrow | Long Rightwards Arrow |
| U+027F7 | ⟷ | \longleftrightarrow | Long Left Right Arrow |
| U+027F8 | ⟸ | \impliedby, \Longleftarrow | Long Leftwards Double Arrow |
| U+027F9 | ⟹ | \implies, \Longrightarrow | Long Rightwards Double Arrow |
| U+027FA | ⟺ | \Longleftrightarrow, \iff | Long Left Right Double Arrow |
| U+027FB | ⟻ | \longmapsfrom | Long Leftwards Arrow From Bar |
| U+027FC | ⟼ | \longmapsto | Long Rightwards Arrow From Bar |
| U+027FD | ⟽ | \Longmapsfrom | Long Leftwards Double Arrow From Bar |
| U+027FE | ⟾ | \Longmapsto | Long Rightwards Double Arrow From Bar |
| U+027FF | ⟿ | \longrightsquigarrow | Long Rightwards Squiggle Arrow |
| U+02900 | ⤀ | \nvtwoheadrightarrow | Rightwards Two-Headed Arrow With Vertical Stroke |
| U+02901 | ⤁ | \nVtwoheadrightarrow | Rightwards Two-Headed Arrow With Double Vertical Stroke |
| U+02902 | ⤂ | \nvLeftarrow | Leftwards Double Arrow With Vertical Stroke |
| U+02903 | ⤃ | \nvRightarrow | Rightwards Double Arrow With Vertical Stroke |
| U+02904 | ⤄ | \nvLeftrightarrow | Left Right Double Arrow With Vertical Stroke |
| U+02905 | ⤅ | \twoheadmapsto | Rightwards Two-Headed Arrow From Bar |
| U+02906 | ⤆ | \Mapsfrom | Leftwards Double Arrow From Bar |
| U+02907 | ⤇ | \Mapsto | Rightwards Double Arrow From Bar |
| U+02908 | ⤈ | \downarrowbarred | Downwards Arrow With Horizontal Stroke |
| U+02909 | ⤉ | \uparrowbarred | Upwards Arrow With Horizontal Stroke |
| U+0290A | ⤊ | \Uuparrow | Upwards Triple Arrow |
| U+0290B | ⤋ | \Ddownarrow | Downwards Triple Arrow |
| U+0290C | ⤌ | \leftbkarrow | Leftwards Double Dash Arrow |
| U+0290D | ⤍ | \bkarow | Rightwards Double Dash Arrow |
| U+0290E | ⤎ | \leftdbkarrow | Leftwards Triple Dash Arrow |
| U+0290F | ⤏ | \dbkarow | Rightwards Triple Dash Arrow |
| U+02910 | ⤐ | \drbkarrow | Rightwards Two-Headed Triple Dash Arrow |
| U+02911 | ⤑ | \rightdotarrow | Rightwards Arrow With Dotted Stem |
| U+02912 | ⤒ | \UpArrowBar | Upwards Arrow To Bar |
| U+02913 | ⤓ | \DownArrowBar | Downwards Arrow To Bar |
| U+02914 | ⤔ | \nvrightarrowtail | Rightwards Arrow With Tail With Vertical Stroke |
| U+02915 | ⤕ | \nVrightarrowtail | Rightwards Arrow With Tail With Double Vertical Stroke |
| U+02916 | ⤖ | \twoheadrightarrowtail | Rightwards Two-Headed Arrow With Tail |
| U+02917 | ⤗ | \nvtwoheadrightarrowtail | Rightwards Two-Headed Arrow With Tail With Vertical Stroke |
| U+02918 | ⤘ | \nVtwoheadrightarrowtail | Rightwards Two-Headed Arrow With Tail With Double Vertical Stroke |
| U+0291D | ⤝ | \diamondleftarrow | Leftwards Arrow To Black Diamond |
| U+0291E | ⤞ | \rightarrowdiamond | Rightwards Arrow To Black Diamond |
| U+0291F | ⤟ | \diamondleftarrowbar | Leftwards Arrow From Bar To Black Diamond |
| U+02920 | ⤠ | \barrightarrowdiamond | Rightwards Arrow From Bar To Black Diamond |
| U+02925 | ⤥ | \hksearow | South East Arrow With Hook |
| U+02926 | ⤦ | \hkswarow | South West Arrow With Hook |
| U+02927 | ⤧ | \tona | North West Arrow And North East Arrow |
| U+02928 | ⤨ | \toea | North East Arrow And South East Arrow |
| U+02929 | ⤩ | \tosa | South East Arrow And South West Arrow |
| U+0292A | ⤪ | \towa | South West Arrow And North West Arrow |
| U+0292B | ⤫ | \rdiagovfdiag | Rising Diagonal Crossing Falling Diagonal |
| U+0292C | ⤬ | \fdiagovrdiag | Falling Diagonal Crossing Rising Diagonal |
| U+0292D | ⤭ | \seovnearrow | South East Arrow Crossing North East Arrow |
| U+0292E | ⤮ | \neovsearrow | North East Arrow Crossing South East Arrow |
| U+0292F | ⤯ | \fdiagovnearrow | Falling Diagonal Crossing North East Arrow |
| U+02930 | ⤰ | \rdiagovsearrow | Rising Diagonal Crossing South East Arrow |
| U+02931 | ⤱ | \neovnwarrow | North East Arrow Crossing North West Arrow |
| U+02932 | ⤲ | \nwovnearrow | North West Arrow Crossing North East Arrow |
| U+02934 | ⤴ | \:arrow\_heading\_up: | Arrow Pointing Rightwards Then Curving Upwards |
| U+02935 | ⤵ | \:arrow\_heading\_down: | Arrow Pointing Rightwards Then Curving Downwards |
| U+02942 | ⥂ | \Rlarr | Rightwards Arrow Above Short Leftwards Arrow |
| U+02944 | ⥄ | \rLarr | Short Rightwards Arrow Above Leftwards Arrow |
| U+02945 | ⥅ | \rightarrowplus | Rightwards Arrow With Plus Below |
| U+02946 | ⥆ | \leftarrowplus | Leftwards Arrow With Plus Below |
| U+02947 | ⥇ | \rarrx | Rightwards Arrow Through X |
| U+02948 | ⥈ | \leftrightarrowcircle | Left Right Arrow Through Small Circle |
| U+02949 | ⥉ | \twoheaduparrowcircle | Upwards Two-Headed Arrow From Small Circle |
| U+0294A | ⥊ | \leftrightharpoonupdown | Left Barb Up Right Barb Down Harpoon |
| U+0294B | ⥋ | \leftrightharpoondownup | Left Barb Down Right Barb Up Harpoon |
| U+0294C | ⥌ | \updownharpoonrightleft | Up Barb Right Down Barb Left Harpoon |
| U+0294D | ⥍ | \updownharpoonleftright | Up Barb Left Down Barb Right Harpoon |
| U+0294E | ⥎ | \LeftRightVector | Left Barb Up Right Barb Up Harpoon |
| U+0294F | ⥏ | \RightUpDownVector | Up Barb Right Down Barb Right Harpoon |
| U+02950 | ⥐ | \DownLeftRightVector | Left Barb Down Right Barb Down Harpoon |
| U+02951 | ⥑ | \LeftUpDownVector | Up Barb Left Down Barb Left Harpoon |
| U+02952 | ⥒ | \LeftVectorBar | Leftwards Harpoon With Barb Up To Bar |
| U+02953 | ⥓ | \RightVectorBar | Rightwards Harpoon With Barb Up To Bar |
| U+02954 | ⥔ | \RightUpVectorBar | Upwards Harpoon With Barb Right To Bar |
| U+02955 | ⥕ | \RightDownVectorBar | Downwards Harpoon With Barb Right To Bar |
| U+02956 | ⥖ | \DownLeftVectorBar | Leftwards Harpoon With Barb Down To Bar |
| U+02957 | ⥗ | \DownRightVectorBar | Rightwards Harpoon With Barb Down To Bar |
| U+02958 | ⥘ | \LeftUpVectorBar | Upwards Harpoon With Barb Left To Bar |
| U+02959 | ⥙ | \LeftDownVectorBar | Downwards Harpoon With Barb Left To Bar |
| U+0295A | ⥚ | \LeftTeeVector | Leftwards Harpoon With Barb Up From Bar |
| U+0295B | ⥛ | \RightTeeVector | Rightwards Harpoon With Barb Up From Bar |
| U+0295C | ⥜ | \RightUpTeeVector | Upwards Harpoon With Barb Right From Bar |
| U+0295D | ⥝ | \RightDownTeeVector | Downwards Harpoon With Barb Right From Bar |
| U+0295E | ⥞ | \DownLeftTeeVector | Leftwards Harpoon With Barb Down From Bar |
| U+0295F | ⥟ | \DownRightTeeVector | Rightwards Harpoon With Barb Down From Bar |
| U+02960 | ⥠ | \LeftUpTeeVector | Upwards Harpoon With Barb Left From Bar |
| U+02961 | ⥡ | \LeftDownTeeVector | Downwards Harpoon With Barb Left From Bar |
| U+02962 | ⥢ | \leftharpoonsupdown | Leftwards Harpoon With Barb Up Above Leftwards Harpoon With Barb Down |
| U+02963 | ⥣ | \upharpoonsleftright | Upwards Harpoon With Barb Left Beside Upwards Harpoon With Barb Right |
| U+02964 | ⥤ | \rightharpoonsupdown | Rightwards Harpoon With Barb Up Above Rightwards Harpoon With Barb Down |
| U+02965 | ⥥ | \downharpoonsleftright | Downwards Harpoon With Barb Left Beside Downwards Harpoon With Barb Right |
| U+02966 | ⥦ | \leftrightharpoonsup | Leftwards Harpoon With Barb Up Above Rightwards Harpoon With Barb Up |
| U+02967 | ⥧ | \leftrightharpoonsdown | Leftwards Harpoon With Barb Down Above Rightwards Harpoon With Barb Down |
| U+02968 | ⥨ | \rightleftharpoonsup | Rightwards Harpoon With Barb Up Above Leftwards Harpoon With Barb Up |
| U+02969 | ⥩ | \rightleftharpoonsdown | Rightwards Harpoon With Barb Down Above Leftwards Harpoon With Barb Down |
| U+0296A | ⥪ | \leftharpoonupdash | Leftwards Harpoon With Barb Up Above Long Dash |
| U+0296B | ⥫ | \dashleftharpoondown | Leftwards Harpoon With Barb Down Below Long Dash |
| U+0296C | ⥬ | \rightharpoonupdash | Rightwards Harpoon With Barb Up Above Long Dash |
| U+0296D | ⥭ | \dashrightharpoondown | Rightwards Harpoon With Barb Down Below Long Dash |
| U+0296E | ⥮ | \UpEquilibrium | Upwards Harpoon With Barb Left Beside Downwards Harpoon With Barb Right |
| U+0296F | ⥯ | \ReverseUpEquilibrium | Downwards Harpoon With Barb Left Beside Upwards Harpoon With Barb Right |
| U+02970 | ⥰ | \RoundImplies | Right Double Arrow With Rounded Head |
| U+02980 | ⦀ | \Vvert | Triple Vertical Bar Delimiter |
| U+02986 | ⦆ | \Elroang | Right White Parenthesis |
| U+02999 | ⦙ | \ddfnc | Dotted Fence |
| U+0299B | ⦛ | \measuredangleleft | Measured Angle Opening Left |
| U+0299C | ⦜ | \Angle | Right Angle Variant With Square |
| U+0299D | ⦝ | \rightanglemdot | Measured Right Angle With Dot |
| U+0299E | ⦞ | \angles | Angle With S Inside |
| U+0299F | ⦟ | \angdnr | Acute Angle |
| U+029A0 | ⦠ | \lpargt | Spherical Angle Opening Left |
| U+029A1 | ⦡ | \sphericalangleup | Spherical Angle Opening Up |
| U+029A2 | ⦢ | \turnangle | Turned Angle |
| U+029A3 | ⦣ | \revangle | Reversed Angle |
| U+029A4 | ⦤ | \angleubar | Angle With Underbar |
| U+029A5 | ⦥ | \revangleubar | Reversed Angle With Underbar |
| U+029A6 | ⦦ | \wideangledown | Oblique Angle Opening Up |
| U+029A7 | ⦧ | \wideangleup | Oblique Angle Opening Down |
| U+029A8 | ⦨ | \measanglerutone | Measured Angle With Open Arm Ending In Arrow Pointing Up And Right |
| U+029A9 | ⦩ | \measanglelutonw | Measured Angle With Open Arm Ending In Arrow Pointing Up And Left |
| U+029AA | ⦪ | \measanglerdtose | Measured Angle With Open Arm Ending In Arrow Pointing Down And Right |
| U+029AB | ⦫ | \measangleldtosw | Measured Angle With Open Arm Ending In Arrow Pointing Down And Left |
| U+029AC | ⦬ | \measangleurtone | Measured Angle With Open Arm Ending In Arrow Pointing Right And Up |
| U+029AD | ⦭ | \measangleultonw | Measured Angle With Open Arm Ending In Arrow Pointing Left And Up |
| U+029AE | ⦮ | \measangledrtose | Measured Angle With Open Arm Ending In Arrow Pointing Right And Down |
| U+029AF | ⦯ | \measangledltosw | Measured Angle With Open Arm Ending In Arrow Pointing Left And Down |
| U+029B0 | ⦰ | \revemptyset | Reversed Empty Set |
| U+029B1 | ⦱ | \emptysetobar | Empty Set With Overbar |
| U+029B2 | ⦲ | \emptysetocirc | Empty Set With Small Circle Above |
| U+029B3 | ⦳ | \emptysetoarr | Empty Set With Right Arrow Above |
| U+029B4 | ⦴ | \emptysetoarrl | Empty Set With Left Arrow Above |
| U+029B7 | ⦷ | \circledparallel | Circled Parallel |
| U+029B8 | ⦸ | \obslash | Circled Reverse Solidus |
| U+029BC | ⦼ | \odotslashdot | Circled Anticlockwise-Rotated Division Sign |
| U+029BE | ⦾ | \circledwhitebullet | Circled White Bullet |
| U+029BF | ⦿ | \circledbullet | Circled Bullet |
| U+029C0 | ⧀ | \olessthan | Circled Less-Than |
| U+029C1 | ⧁ | \ogreaterthan | Circled Greater-Than |
| U+029C4 | ⧄ | \boxdiag | Squared Rising Diagonal Slash |
| U+029C5 | ⧅ | \boxbslash | Squared Falling Diagonal Slash |
| U+029C6 | ⧆ | \boxast | Squared Asterisk |
| U+029C7 | ⧇ | \boxcircle | Squared Small Circle |
| U+029CA | ⧊ | \Lap | Triangle With Dot Above |
| U+029CB | ⧋ | \defas | Triangle With Underbar |
| U+029CF | ⧏ | \LeftTriangleBar | Left Triangle Beside Vertical Bar |
| U+029CF + U+00338 | ⧏̸ | \NotLeftTriangleBar | Left Triangle Beside Vertical Bar + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+029D0 | ⧐ | \RightTriangleBar | Vertical Bar Beside Right Triangle |
| U+029D0 + U+00338 | ⧐̸ | \NotRightTriangleBar | Vertical Bar Beside Right Triangle + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+029DF | ⧟ | \dualmap | Double-Ended Multimap |
| U+029E1 | ⧡ | \lrtriangleeq | Increases As |
| U+029E2 | ⧢ | \shuffle | Shuffle Product |
| U+029E3 | ⧣ | \eparsl | Equals Sign And Slanted Parallel |
| U+029E4 | ⧤ | \smeparsl | Equals Sign And Slanted Parallel With Tilde Above |
| U+029E5 | ⧥ | \eqvparsl | Identical To And Slanted Parallel |
| U+029EB | ⧫ | \blacklozenge | Black Lozenge |
| U+029F4 | ⧴ | \RuleDelayed | Rule-Delayed |
| U+029F6 | ⧶ | \dsol | Solidus With Overbar |
| U+029F7 | ⧷ | \rsolbar | Reverse Solidus With Horizontal Stroke |
| U+029FA | ⧺ | \doubleplus | Double Plus |
| U+029FB | ⧻ | \tripleplus | Triple Plus |
| U+02A00 | ⨀ | \bigodot | N-Ary Circled Dot Operator |
| U+02A01 | ⨁ | \bigoplus | N-Ary Circled Plus Operator |
| U+02A02 | ⨂ | \bigotimes | N-Ary Circled Times Operator |
| U+02A03 | ⨃ | \bigcupdot | N-Ary Union Operator With Dot |
| U+02A04 | ⨄ | \biguplus | N-Ary Union Operator With Plus |
| U+02A05 | ⨅ | \bigsqcap | N-Ary Square Intersection Operator |
| U+02A06 | ⨆ | \bigsqcup | N-Ary Square Union Operator |
| U+02A07 | ⨇ | \conjquant | Two Logical And Operator |
| U+02A08 | ⨈ | \disjquant | Two Logical Or Operator |
| U+02A09 | ⨉ | \bigtimes | N-Ary Times Operator |
| U+02A0A | ⨊ | \modtwosum | Modulo Two Sum |
| U+02A0B | ⨋ | \sumint | Summation With Integral |
| U+02A0C | ⨌ | \iiiint | Quadruple Integral Operator |
| U+02A0D | ⨍ | \intbar | Finite Part Integral |
| U+02A0E | ⨎ | \intBar | Integral With Double Stroke |
| U+02A0F | ⨏ | \clockoint | Integral Average With Slash |
| U+02A10 | ⨐ | \cirfnint | Circulation Function |
| U+02A11 | ⨑ | \awint | Anticlockwise Integration |
| U+02A12 | ⨒ | \rppolint | Line Integration With Rectangular Path Around Pole |
| U+02A13 | ⨓ | \scpolint | Line Integration With Semicircular Path Around Pole |
| U+02A14 | ⨔ | \npolint | Line Integration Not Including The Pole |
| U+02A15 | ⨕ | \pointint | Integral Around A Point Operator |
| U+02A16 | ⨖ | \sqrint | Quaternion Integral Operator |
| U+02A18 | ⨘ | \intx | Integral With Times Sign |
| U+02A19 | ⨙ | \intcap | Integral With Intersection |
| U+02A1A | ⨚ | \intcup | Integral With Union |
| U+02A1B | ⨛ | \upint | Integral With Overbar |
| U+02A1C | ⨜ | \lowint | Integral With Underbar |
| U+02A1D | ⨝ | \join | Join |
| U+02A1F | ⨟ | \bbsemi | Z Notation Schema Composition |
| U+02A22 | ⨢ | \ringplus | Plus Sign With Small Circle Above |
| U+02A23 | ⨣ | \plushat | Plus Sign With Circumflex Accent Above |
| U+02A24 | ⨤ | \simplus | Plus Sign With Tilde Above |
| U+02A25 | ⨥ | \plusdot | Plus Sign With Dot Below |
| U+02A26 | ⨦ | \plussim | Plus Sign With Tilde Below |
| U+02A27 | ⨧ | \plussubtwo | Plus Sign With Subscript Two |
| U+02A28 | ⨨ | \plustrif | Plus Sign With Black Triangle |
| U+02A29 | ⨩ | \commaminus | Minus Sign With Comma Above |
| U+02A2A | ⨪ | \minusdot | Minus Sign With Dot Below |
| U+02A2B | ⨫ | \minusfdots | Minus Sign With Falling Dots |
| U+02A2C | ⨬ | \minusrdots | Minus Sign With Rising Dots |
| U+02A2D | ⨭ | \opluslhrim | Plus Sign In Left Half Circle |
| U+02A2E | ⨮ | \oplusrhrim | Plus Sign In Right Half Circle |
| U+02A2F | ⨯ | \Times | Vector Or Cross Product |
| U+02A30 | ⨰ | \dottimes | Multiplication Sign With Dot Above |
| U+02A31 | ⨱ | \timesbar | Multiplication Sign With Underbar |
| U+02A32 | ⨲ | \btimes | Semidirect Product With Bottom Closed |
| U+02A33 | ⨳ | \smashtimes | Smash Product |
| U+02A34 | ⨴ | \otimeslhrim | Multiplication Sign In Left Half Circle |
| U+02A35 | ⨵ | \otimesrhrim | Multiplication Sign In Right Half Circle |
| U+02A36 | ⨶ | \otimeshat | Circled Multiplication Sign With Circumflex Accent |
| U+02A37 | ⨷ | \Otimes | Multiplication Sign In Double Circle |
| U+02A38 | ⨸ | \odiv | Circled Division Sign |
| U+02A39 | ⨹ | \triangleplus | Plus Sign In Triangle |
| U+02A3A | ⨺ | \triangleminus | Minus Sign In Triangle |
| U+02A3B | ⨻ | \triangletimes | Multiplication Sign In Triangle |
| U+02A3C | ⨼ | \intprod | Interior Product |
| U+02A3D | ⨽ | \intprodr | Righthand Interior Product |
| U+02A3F | ⨿ | \amalg | Amalgamation Or Coproduct |
| U+02A40 | ⩀ | \capdot | Intersection With Dot |
| U+02A41 | ⩁ | \uminus | Union With Minus Sign |
| U+02A42 | ⩂ | \barcup | Union With Overbar |
| U+02A43 | ⩃ | \barcap | Intersection With Overbar |
| U+02A44 | ⩄ | \capwedge | Intersection With Logical And |
| U+02A45 | ⩅ | \cupvee | Union With Logical Or |
| U+02A4A | ⩊ | \twocups | Union Beside And Joined With Union |
| U+02A4B | ⩋ | \twocaps | Intersection Beside And Joined With Intersection |
| U+02A4C | ⩌ | \closedvarcup | Closed Union With Serifs |
| U+02A4D | ⩍ | \closedvarcap | Closed Intersection With Serifs |
| U+02A4E | ⩎ | \Sqcap | Double Square Intersection |
| U+02A4F | ⩏ | \Sqcup | Double Square Union |
| U+02A50 | ⩐ | \closedvarcupsmashprod | Closed Union With Serifs And Smash Product |
| U+02A51 | ⩑ | \wedgeodot | Logical And With Dot Above |
| U+02A52 | ⩒ | \veeodot | Logical Or With Dot Above |
| U+02A53 | ⩓ | \And | Double Logical And |
| U+02A54 | ⩔ | \Or | Double Logical Or |
| U+02A55 | ⩕ | \wedgeonwedge | Two Intersecting Logical And |
| U+02A56 | ⩖ | \ElOr | Two Intersecting Logical Or |
| U+02A57 | ⩗ | \bigslopedvee | Sloping Large Or |
| U+02A58 | ⩘ | \bigslopedwedge | Sloping Large And |
| U+02A5A | ⩚ | \wedgemidvert | Logical And With Middle Stem |
| U+02A5B | ⩛ | \veemidvert | Logical Or With Middle Stem |
| U+02A5C | ⩜ | \midbarwedge | Logical And With Horizontal Dash |
| U+02A5D | ⩝ | \midbarvee | Logical Or With Horizontal Dash |
| U+02A5E | ⩞ | \perspcorrespond | Logical And With Double Overbar |
| U+02A5F | ⩟ | \minhat | Logical And With Underbar |
| U+02A60 | ⩠ | \wedgedoublebar | Logical And With Double Underbar |
| U+02A61 | ⩡ | \varveebar | Small Vee With Underbar |
| U+02A62 | ⩢ | \doublebarvee | Logical Or With Double Overbar |
| U+02A63 | ⩣ | \veedoublebar | Logical Or With Double Underbar |
| U+02A66 | ⩦ | \eqdot | Equals Sign With Dot Below |
| U+02A67 | ⩧ | \dotequiv | Identical With Dot Above |
| U+02A6A | ⩪ | \dotsim | Tilde Operator With Dot Above |
| U+02A6B | ⩫ | \simrdots | Tilde Operator With Rising Dots |
| U+02A6C | ⩬ | \simminussim | Similar Minus Similar |
| U+02A6D | ⩭ | \congdot | Congruent With Dot Above |
| U+02A6E | ⩮ | \asteq | Equals With Asterisk |
| U+02A6F | ⩯ | \hatapprox | Almost Equal To With Circumflex Accent |
| U+02A70 | ⩰ | \approxeqq | Approximately Equal Or Equal To |
| U+02A71 | ⩱ | \eqqplus | Equals Sign Above Plus Sign |
| U+02A72 | ⩲ | \pluseqq | Plus Sign Above Equals Sign |
| U+02A73 | ⩳ | \eqqsim | Equals Sign Above Tilde Operator |
| U+02A74 | ⩴ | \Coloneq | Double Colon Equal |
| U+02A75 | ⩵ | \Equal | Two Consecutive Equals Signs |
| U+02A76 | ⩶ | \eqeqeq | Three Consecutive Equals Signs |
| U+02A77 | ⩷ | \ddotseq | Equals Sign With Two Dots Above And Two Dots Below |
| U+02A78 | ⩸ | \equivDD | Equivalent With Four Dots Above |
| U+02A79 | ⩹ | \ltcir | Less-Than With Circle Inside |
| U+02A7A | ⩺ | \gtcir | Greater-Than With Circle Inside |
| U+02A7B | ⩻ | \ltquest | Less-Than With Question Mark Above |
| U+02A7C | ⩼ | \gtquest | Greater-Than With Question Mark Above |
| U+02A7D | ⩽ | \leqslant | Less-Than Or Slanted Equal To |
| U+02A7D + U+00338 | ⩽̸ | \nleqslant | Less-Than Or Slanted Equal To + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02A7E | ⩾ | \geqslant | Greater-Than Or Slanted Equal To |
| U+02A7E + U+00338 | ⩾̸ | \ngeqslant | Greater-Than Or Slanted Equal To + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02A7F | ⩿ | \lesdot | Less-Than Or Slanted Equal To With Dot Inside |
| U+02A80 | ⪀ | \gesdot | Greater-Than Or Slanted Equal To With Dot Inside |
| U+02A81 | ⪁ | \lesdoto | Less-Than Or Slanted Equal To With Dot Above |
| U+02A82 | ⪂ | \gesdoto | Greater-Than Or Slanted Equal To With Dot Above |
| U+02A83 | ⪃ | \lesdotor | Less-Than Or Slanted Equal To With Dot Above Right |
| U+02A84 | ⪄ | \gesdotol | Greater-Than Or Slanted Equal To With Dot Above Left |
| U+02A85 | ⪅ | \lessapprox | Less-Than Or Approximate |
| U+02A86 | ⪆ | \gtrapprox | Greater-Than Or Approximate |
| U+02A87 | ⪇ | \lneq | Less-Than And Single-Line Not Equal To |
| U+02A88 | ⪈ | \gneq | Greater-Than And Single-Line Not Equal To |
| U+02A89 | ⪉ | \lnapprox | Less-Than And Not Approximate |
| U+02A8A | ⪊ | \gnapprox | Greater-Than And Not Approximate |
| U+02A8B | ⪋ | \lesseqqgtr | Less-Than Above Double-Line Equal Above Greater-Than |
| U+02A8C | ⪌ | \gtreqqless | Greater-Than Above Double-Line Equal Above Less-Than |
| U+02A8D | ⪍ | \lsime | Less-Than Above Similar Or Equal |
| U+02A8E | ⪎ | \gsime | Greater-Than Above Similar Or Equal |
| U+02A8F | ⪏ | \lsimg | Less-Than Above Similar Above Greater-Than |
| U+02A90 | ⪐ | \gsiml | Greater-Than Above Similar Above Less-Than |
| U+02A91 | ⪑ | \lgE | Less-Than Above Greater-Than Above Double-Line Equal |
| U+02A92 | ⪒ | \glE | Greater-Than Above Less-Than Above Double-Line Equal |
| U+02A93 | ⪓ | \lesges | Less-Than Above Slanted Equal Above Greater-Than Above Slanted Equal |
| U+02A94 | ⪔ | \gesles | Greater-Than Above Slanted Equal Above Less-Than Above Slanted Equal |
| U+02A95 | ⪕ | \eqslantless | Slanted Equal To Or Less-Than |
| U+02A96 | ⪖ | \eqslantgtr | Slanted Equal To Or Greater-Than |
| U+02A97 | ⪗ | \elsdot | Slanted Equal To Or Less-Than With Dot Inside |
| U+02A98 | ⪘ | \egsdot | Slanted Equal To Or Greater-Than With Dot Inside |
| U+02A99 | ⪙ | \eqqless | Double-Line Equal To Or Less-Than |
| U+02A9A | ⪚ | \eqqgtr | Double-Line Equal To Or Greater-Than |
| U+02A9B | ⪛ | \eqqslantless | Double-Line Slanted Equal To Or Less-Than |
| U+02A9C | ⪜ | \eqqslantgtr | Double-Line Slanted Equal To Or Greater-Than |
| U+02A9D | ⪝ | \simless | Similar Or Less-Than |
| U+02A9E | ⪞ | \simgtr | Similar Or Greater-Than |
| U+02A9F | ⪟ | \simlE | Similar Above Less-Than Above Equals Sign |
| U+02AA0 | ⪠ | \simgE | Similar Above Greater-Than Above Equals Sign |
| U+02AA1 | ⪡ | \NestedLessLess | Double Nested Less-Than |
| U+02AA1 + U+00338 | ⪡̸ | \NotNestedLessLess | Double Nested Less-Than + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02AA2 | ⪢ | \NestedGreaterGreater | Double Nested Greater-Than |
| U+02AA2 + U+00338 | ⪢̸ | \NotNestedGreaterGreater | Double Nested Greater-Than + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02AA3 | ⪣ | \partialmeetcontraction | Double Nested Less-Than With Underbar |
| U+02AA4 | ⪤ | \glj | Greater-Than Overlapping Less-Than |
| U+02AA5 | ⪥ | \gla | Greater-Than Beside Less-Than |
| U+02AA6 | ⪦ | \ltcc | Less-Than Closed By Curve |
| U+02AA7 | ⪧ | \gtcc | Greater-Than Closed By Curve |
| U+02AA8 | ⪨ | \lescc | Less-Than Closed By Curve Above Slanted Equal |
| U+02AA9 | ⪩ | \gescc | Greater-Than Closed By Curve Above Slanted Equal |
| U+02AAA | ⪪ | \smt | Smaller Than |
| U+02AAB | ⪫ | \lat | Larger Than |
| U+02AAC | ⪬ | \smte | Smaller Than Or Equal To |
| U+02AAD | ⪭ | \late | Larger Than Or Equal To |
| U+02AAE | ⪮ | \bumpeqq | Equals Sign With Bumpy Above |
| U+02AAF | ⪯ | \preceq | Precedes Above Single-Line Equals Sign |
| U+02AAF + U+00338 | ⪯̸ | \npreceq | Precedes Above Single-Line Equals Sign + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02AB0 | ⪰ | \succeq | Succeeds Above Single-Line Equals Sign |
| U+02AB0 + U+00338 | ⪰̸ | \nsucceq | Succeeds Above Single-Line Equals Sign + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02AB1 | ⪱ | \precneq | Precedes Above Single-Line Not Equal To |
| U+02AB2 | ⪲ | \succneq | Succeeds Above Single-Line Not Equal To |
| U+02AB3 | ⪳ | \preceqq | Precedes Above Equals Sign |
| U+02AB4 | ⪴ | \succeqq | Succeeds Above Equals Sign |
| U+02AB5 | ⪵ | \precneqq | Precedes Above Not Equal To |
| U+02AB6 | ⪶ | \succneqq | Succeeds Above Not Equal To |
| U+02AB7 | ⪷ | \precapprox | Precedes Above Almost Equal To |
| U+02AB8 | ⪸ | \succapprox | Succeeds Above Almost Equal To |
| U+02AB9 | ⪹ | \precnapprox | Precedes Above Not Almost Equal To |
| U+02ABA | ⪺ | \succnapprox | Succeeds Above Not Almost Equal To |
| U+02ABB | ⪻ | \Prec | Double Precedes |
| U+02ABC | ⪼ | \Succ | Double Succeeds |
| U+02ABD | ⪽ | \subsetdot | Subset With Dot |
| U+02ABE | ⪾ | \supsetdot | Superset With Dot |
| U+02ABF | ⪿ | \subsetplus | Subset With Plus Sign Below |
| U+02AC0 | ⫀ | \supsetplus | Superset With Plus Sign Below |
| U+02AC1 | ⫁ | \submult | Subset With Multiplication Sign Below |
| U+02AC2 | ⫂ | \supmult | Superset With Multiplication Sign Below |
| U+02AC3 | ⫃ | \subedot | Subset Of Or Equal To With Dot Above |
| U+02AC4 | ⫄ | \supedot | Superset Of Or Equal To With Dot Above |
| U+02AC5 | ⫅ | \subseteqq | Subset Of Above Equals Sign |
| U+02AC5 + U+00338 | ⫅̸ | \nsubseteqq | Subset Of Above Equals Sign + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02AC6 | ⫆ | \supseteqq | Superset Of Above Equals Sign |
| U+02AC6 + U+00338 | ⫆̸ | \nsupseteqq | Superset Of Above Equals Sign + Combining Long Solidus Overlay / Non-Spacing Long Slash Overlay |
| U+02AC7 | ⫇ | \subsim | Subset Of Above Tilde Operator |
| U+02AC8 | ⫈ | \supsim | Superset Of Above Tilde Operator |
| U+02AC9 | ⫉ | \subsetapprox | Subset Of Above Almost Equal To |
| U+02ACA | ⫊ | \supsetapprox | Superset Of Above Almost Equal To |
| U+02ACB | ⫋ | \subsetneqq | Subset Of Above Not Equal To |
| U+02ACC | ⫌ | \supsetneqq | Superset Of Above Not Equal To |
| U+02ACD | ⫍ | \lsqhook | Square Left Open Box Operator |
| U+02ACE | ⫎ | \rsqhook | Square Right Open Box Operator |
| U+02ACF | ⫏ | \csub | Closed Subset |
| U+02AD0 | ⫐ | \csup | Closed Superset |
| U+02AD1 | ⫑ | \csube | Closed Subset Or Equal To |
| U+02AD2 | ⫒ | \csupe | Closed Superset Or Equal To |
| U+02AD3 | ⫓ | \subsup | Subset Above Superset |
| U+02AD4 | ⫔ | \supsub | Superset Above Subset |
| U+02AD5 | ⫕ | \subsub | Subset Above Subset |
| U+02AD6 | ⫖ | \supsup | Superset Above Superset |
| U+02AD7 | ⫗ | \suphsub | Superset Beside Subset |
| U+02AD8 | ⫘ | \supdsub | Superset Beside And Joined By Dash With Subset |
| U+02AD9 | ⫙ | \forkv | Element Of Opening Downwards |
| U+02ADB | ⫛ | \mlcp | Transversal Intersection |
| U+02ADC | ⫝̸ | \forks | Forking |
| U+02ADD | ⫝ | \forksnot | Nonforking |
| U+02AE3 | ⫣ | \dashV | Double Vertical Bar Left Turnstile |
| U+02AE4 | ⫤ | \Dashv | Vertical Bar Double Left Turnstile |
| U+02AEA | ⫪ | \Top, \downvDash | Double Down Tack |
| U+02AEB | ⫫ | \upvDash, \Bot, \indep | Double Up Tack |
| U+02AF4 | ⫴ | \interleave | Triple Vertical Bar Binary Relation |
| U+02AF6 | ⫶ | \tdcol | Triple Colon Operator |
| U+02AF7 | ⫷ | \lllnest | Triple Nested Less-Than |
| U+02AF8 | ⫸ | \gggnest | Triple Nested Greater-Than |
| U+02AF9 | ⫹ | \leqqslant | Double-Line Slanted Less-Than Or Equal To |
| U+02AFA | ⫺ | \geqqslant | Double-Line Slanted Greater-Than Or Equal To |
| U+02B05 | ⬅ | \:arrow\_left: | Leftwards Black Arrow |
| U+02B06 | ⬆ | \:arrow\_up: | Upwards Black Arrow |
| U+02B07 | ⬇ | \:arrow\_down: | Downwards Black Arrow |
| U+02B12 | ⬒ | \squaretopblack | Square With Top Half Black |
| U+02B13 | ⬓ | \squarebotblack | Square With Bottom Half Black |
| U+02B14 | ⬔ | \squareurblack | Square With Upper Right Diagonal Half Black |
| U+02B15 | ⬕ | \squarellblack | Square With Lower Left Diagonal Half Black |
| U+02B16 | ⬖ | \diamondleftblack | Diamond With Left Half Black |
| U+02B17 | ⬗ | \diamondrightblack | Diamond With Right Half Black |
| U+02B18 | ⬘ | \diamondtopblack | Diamond With Top Half Black |
| U+02B19 | ⬙ | \diamondbotblack | Diamond With Bottom Half Black |
| U+02B1A | ⬚ | \dottedsquare | Dotted Square |
| U+02B1B | ⬛ | \lgblksquare, \:black\_large\_square: | Black Large Square |
| U+02B1C | ⬜ | \lgwhtsquare, \:white\_large\_square: | White Large Square |
| U+02B1D | ⬝ | \vysmblksquare | Black Very Small Square |
| U+02B1E | ⬞ | \vysmwhtsquare | White Very Small Square |
| U+02B1F | ⬟ | \pentagonblack | Black Pentagon |
| U+02B20 | ⬠ | \pentagon | White Pentagon |
| U+02B21 | ⬡ | \varhexagon | White Hexagon |
| U+02B22 | ⬢ | \varhexagonblack | Black Hexagon |
| U+02B23 | ⬣ | \hexagonblack | Horizontal Black Hexagon |
| U+02B24 | ⬤ | \lgblkcircle | Black Large Circle |
| U+02B25 | ⬥ | \mdblkdiamond | Black Medium Diamond |
| U+02B26 | ⬦ | \mdwhtdiamond | White Medium Diamond |
| U+02B27 | ⬧ | \mdblklozenge | Black Medium Lozenge |
| U+02B28 | ⬨ | \mdwhtlozenge | White Medium Lozenge |
| U+02B29 | ⬩ | \smblkdiamond | Black Small Diamond |
| U+02B2A | ⬪ | \smblklozenge | Black Small Lozenge |
| U+02B2B | ⬫ | \smwhtlozenge | White Small Lozenge |
| U+02B2C | ⬬ | \blkhorzoval | Black Horizontal Ellipse |
| U+02B2D | ⬭ | \whthorzoval | White Horizontal Ellipse |
| U+02B2E | ⬮ | \blkvertoval | Black Vertical Ellipse |
| U+02B2F | ⬯ | \whtvertoval | White Vertical Ellipse |
| U+02B30 | ⬰ | \circleonleftarrow | Left Arrow With Small Circle |
| U+02B31 | ⬱ | \leftthreearrows | Three Leftwards Arrows |
| U+02B32 | ⬲ | \leftarrowonoplus | Left Arrow With Circled Plus |
| U+02B33 | ⬳ | \longleftsquigarrow | Long Leftwards Squiggle Arrow |
| U+02B34 | ⬴ | \nvtwoheadleftarrow | Leftwards Two-Headed Arrow With Vertical Stroke |
| U+02B35 | ⬵ | \nVtwoheadleftarrow | Leftwards Two-Headed Arrow With Double Vertical Stroke |
| U+02B36 | ⬶ | \twoheadmapsfrom | Leftwards Two-Headed Arrow From Bar |
| U+02B37 | ⬷ | \twoheadleftdbkarrow | Leftwards Two-Headed Triple Dash Arrow |
| U+02B38 | ⬸ | \leftdotarrow | Leftwards Arrow With Dotted Stem |
| U+02B39 | ⬹ | \nvleftarrowtail | Leftwards Arrow With Tail With Vertical Stroke |
| U+02B3A | ⬺ | \nVleftarrowtail | Leftwards Arrow With Tail With Double Vertical Stroke |
| U+02B3B | ⬻ | \twoheadleftarrowtail | Leftwards Two-Headed Arrow With Tail |
| U+02B3C | ⬼ | \nvtwoheadleftarrowtail | Leftwards Two-Headed Arrow With Tail With Vertical Stroke |
| U+02B3D | ⬽ | \nVtwoheadleftarrowtail | Leftwards Two-Headed Arrow With Tail With Double Vertical Stroke |
| U+02B3E | ⬾ | \leftarrowx | Leftwards Arrow Through X |
| U+02B3F | ⬿ | \leftcurvedarrow | Wave Arrow Pointing Directly Left |
| U+02B40 | ⭀ | \equalleftarrow | Equals Sign Above Leftwards Arrow |
| U+02B41 | ⭁ | \bsimilarleftarrow | Reverse Tilde Operator Above Leftwards Arrow |
| U+02B42 | ⭂ | \leftarrowbackapprox | Leftwards Arrow Above Reverse Almost Equal To |
| U+02B43 | ⭃ | \rightarrowgtr | Rightwards Arrow Through Greater-Than |
| U+02B44 | ⭄ | \rightarrowsupset | Rightwards Arrow Through Superset |
| U+02B45 | ⭅ | \LLeftarrow | Leftwards Quadruple Arrow |
| U+02B46 | ⭆ | \RRightarrow | Rightwards Quadruple Arrow |
| U+02B47 | ⭇ | \bsimilarrightarrow | Reverse Tilde Operator Above Rightwards Arrow |
| U+02B48 | ⭈ | \rightarrowbackapprox | Rightwards Arrow Above Reverse Almost Equal To |
| U+02B49 | ⭉ | \similarleftarrow | Tilde Operator Above Leftwards Arrow |
| U+02B4A | ⭊ | \leftarrowapprox | Leftwards Arrow Above Almost Equal To |
| U+02B4B | ⭋ | \leftarrowbsimilar | Leftwards Arrow Above Reverse Tilde Operator |
| U+02B4C | ⭌ | \rightarrowbsimilar | Rightwards Arrow Above Reverse Tilde Operator |
| U+02B50 | ⭐ | \medwhitestar, \:star: | White Medium Star |
| U+02B51 | ⭑ | \medblackstar | Black Small Star |
| U+02B52 | ⭒ | \smwhitestar | White Small Star |
| U+02B53 | ⭓ | \rightpentagonblack | Black Right-Pointing Pentagon |
| U+02B54 | ⭔ | \rightpentagon | White Right-Pointing Pentagon |
| U+02B55 | ⭕ | \:o: | Heavy Large Circle |
| U+02C7C | ⱼ | \\_j | Latin Subscript Small Letter J |
| U+02C7D | ⱽ | \^V | Modifier Letter Capital V |
| U+03012 | 〒 | \postalmark | Postal Mark |
| U+03030 | 〰 | \:wavy\_dash: | Wavy Dash |
| U+0303D | 〽 | \:part\_alternation\_mark: | Part Alternation Mark |
| U+03297 | ㊗ | \:congratulations: | Circled Ideograph Congratulation |
| U+03299 | ㊙ | \:secret: | Circled Ideograph Secret |
| U+0A71B | ꜛ | \^uparrow | Modifier Letter Raised Up Arrow |
| U+0A71C | ꜜ | \^downarrow | Modifier Letter Raised Down Arrow |
| U+0A71D | ꜝ | \^! | Modifier Letter Raised Exclamation Mark |
| U+1D400 | 𝐀 | \bfA | Mathematical Bold Capital A |
| U+1D401 | 𝐁 | \bfB | Mathematical Bold Capital B |
| U+1D402 | 𝐂 | \bfC | Mathematical Bold Capital C |
| U+1D403 | 𝐃 | \bfD | Mathematical Bold Capital D |
| U+1D404 | 𝐄 | \bfE | Mathematical Bold Capital E |
| U+1D405 | 𝐅 | \bfF | Mathematical Bold Capital F |
| U+1D406 | 𝐆 | \bfG | Mathematical Bold Capital G |
| U+1D407 | 𝐇 | \bfH | Mathematical Bold Capital H |
| U+1D408 | 𝐈 | \bfI | Mathematical Bold Capital I |
| U+1D409 | 𝐉 | \bfJ | Mathematical Bold Capital J |
| U+1D40A | 𝐊 | \bfK | Mathematical Bold Capital K |
| U+1D40B | 𝐋 | \bfL | Mathematical Bold Capital L |
| U+1D40C | 𝐌 | \bfM | Mathematical Bold Capital M |
| U+1D40D | 𝐍 | \bfN | Mathematical Bold Capital N |
| U+1D40E | 𝐎 | \bfO | Mathematical Bold Capital O |
| U+1D40F | 𝐏 | \bfP | Mathematical Bold Capital P |
| U+1D410 | 𝐐 | \bfQ | Mathematical Bold Capital Q |
| U+1D411 | 𝐑 | \bfR | Mathematical Bold Capital R |
| U+1D412 | 𝐒 | \bfS | Mathematical Bold Capital S |
| U+1D413 | 𝐓 | \bfT | Mathematical Bold Capital T |
| U+1D414 | 𝐔 | \bfU | Mathematical Bold Capital U |
| U+1D415 | 𝐕 | \bfV | Mathematical Bold Capital V |
| U+1D416 | 𝐖 | \bfW | Mathematical Bold Capital W |
| U+1D417 | 𝐗 | \bfX | Mathematical Bold Capital X |
| U+1D418 | 𝐘 | \bfY | Mathematical Bold Capital Y |
| U+1D419 | 𝐙 | \bfZ | Mathematical Bold Capital Z |
| U+1D41A | 𝐚 | \bfa | Mathematical Bold Small A |
| U+1D41B | 𝐛 | \bfb | Mathematical Bold Small B |
| U+1D41C | 𝐜 | \bfc | Mathematical Bold Small C |
| U+1D41D | 𝐝 | \bfd | Mathematical Bold Small D |
| U+1D41E | 𝐞 | \bfe | Mathematical Bold Small E |
| U+1D41F | 𝐟 | \bff | Mathematical Bold Small F |
| U+1D420 | 𝐠 | \bfg | Mathematical Bold Small G |
| U+1D421 | 𝐡 | \bfh | Mathematical Bold Small H |
| U+1D422 | 𝐢 | \bfi | Mathematical Bold Small I |
| U+1D423 | 𝐣 | \bfj | Mathematical Bold Small J |
| U+1D424 | 𝐤 | \bfk | Mathematical Bold Small K |
| U+1D425 | 𝐥 | \bfl | Mathematical Bold Small L |
| U+1D426 | 𝐦 | \bfm | Mathematical Bold Small M |
| U+1D427 | 𝐧 | \bfn | Mathematical Bold Small N |
| U+1D428 | 𝐨 | \bfo | Mathematical Bold Small O |
| U+1D429 | 𝐩 | \bfp | Mathematical Bold Small P |
| U+1D42A | 𝐪 | \bfq | Mathematical Bold Small Q |
| U+1D42B | 𝐫 | \bfr | Mathematical Bold Small R |
| U+1D42C | 𝐬 | \bfs | Mathematical Bold Small S |
| U+1D42D | 𝐭 | \bft | Mathematical Bold Small T |
| U+1D42E | 𝐮 | \bfu | Mathematical Bold Small U |
| U+1D42F | 𝐯 | \bfv | Mathematical Bold Small V |
| U+1D430 | 𝐰 | \bfw | Mathematical Bold Small W |
| U+1D431 | 𝐱 | \bfx | Mathematical Bold Small X |
| U+1D432 | 𝐲 | \bfy | Mathematical Bold Small Y |
| U+1D433 | 𝐳 | \bfz | Mathematical Bold Small Z |
| U+1D434 | 𝐴 | \itA | Mathematical Italic Capital A |
| U+1D435 | 𝐵 | \itB | Mathematical Italic Capital B |
| U+1D436 | 𝐶 | \itC | Mathematical Italic Capital C |
| U+1D437 | 𝐷 | \itD | Mathematical Italic Capital D |
| U+1D438 | 𝐸 | \itE | Mathematical Italic Capital E |
| U+1D439 | 𝐹 | \itF | Mathematical Italic Capital F |
| U+1D43A | 𝐺 | \itG | Mathematical Italic Capital G |
| U+1D43B | 𝐻 | \itH | Mathematical Italic Capital H |
| U+1D43C | 𝐼 | \itI | Mathematical Italic Capital I |
| U+1D43D | 𝐽 | \itJ | Mathematical Italic Capital J |
| U+1D43E | 𝐾 | \itK | Mathematical Italic Capital K |
| U+1D43F | 𝐿 | \itL | Mathematical Italic Capital L |
| U+1D440 | 𝑀 | \itM | Mathematical Italic Capital M |
| U+1D441 | 𝑁 | \itN | Mathematical Italic Capital N |
| U+1D442 | 𝑂 | \itO | Mathematical Italic Capital O |
| U+1D443 | 𝑃 | \itP | Mathematical Italic Capital P |
| U+1D444 | 𝑄 | \itQ | Mathematical Italic Capital Q |
| U+1D445 | 𝑅 | \itR | Mathematical Italic Capital R |
| U+1D446 | 𝑆 | \itS | Mathematical Italic Capital S |
| U+1D447 | 𝑇 | \itT | Mathematical Italic Capital T |
| U+1D448 | 𝑈 | \itU | Mathematical Italic Capital U |
| U+1D449 | 𝑉 | \itV | Mathematical Italic Capital V |
| U+1D44A | 𝑊 | \itW | Mathematical Italic Capital W |
| U+1D44B | 𝑋 | \itX | Mathematical Italic Capital X |
| U+1D44C | 𝑌 | \itY | Mathematical Italic Capital Y |
| U+1D44D | 𝑍 | \itZ | Mathematical Italic Capital Z |
| U+1D44E | 𝑎 | \ita | Mathematical Italic Small A |
| U+1D44F | 𝑏 | \itb | Mathematical Italic Small B |
| U+1D450 | 𝑐 | \itc | Mathematical Italic Small C |
| U+1D451 | 𝑑 | \itd | Mathematical Italic Small D |
| U+1D452 | 𝑒 | \ite | Mathematical Italic Small E |
| U+1D453 | 𝑓 | \itf | Mathematical Italic Small F |
| U+1D454 | 𝑔 | \itg | Mathematical Italic Small G |
| U+1D456 | 𝑖 | \iti | Mathematical Italic Small I |
| U+1D457 | 𝑗 | \itj | Mathematical Italic Small J |
| U+1D458 | 𝑘 | \itk | Mathematical Italic Small K |
| U+1D459 | 𝑙 | \itl | Mathematical Italic Small L |
| U+1D45A | 𝑚 | \itm | Mathematical Italic Small M |
| U+1D45B | 𝑛 | \itn | Mathematical Italic Small N |
| U+1D45C | 𝑜 | \ito | Mathematical Italic Small O |
| U+1D45D | 𝑝 | \itp | Mathematical Italic Small P |
| U+1D45E | 𝑞 | \itq | Mathematical Italic Small Q |
| U+1D45F | 𝑟 | \itr | Mathematical Italic Small R |
| U+1D460 | 𝑠 | \its | Mathematical Italic Small S |
| U+1D461 | 𝑡 | \itt | Mathematical Italic Small T |
| U+1D462 | 𝑢 | \itu | Mathematical Italic Small U |
| U+1D463 | 𝑣 | \itv | Mathematical Italic Small V |
| U+1D464 | 𝑤 | \itw | Mathematical Italic Small W |
| U+1D465 | 𝑥 | \itx | Mathematical Italic Small X |
| U+1D466 | 𝑦 | \ity | Mathematical Italic Small Y |
| U+1D467 | 𝑧 | \itz | Mathematical Italic Small Z |
| U+1D468 | 𝑨 | \biA | Mathematical Bold Italic Capital A |
| U+1D469 | 𝑩 | \biB | Mathematical Bold Italic Capital B |
| U+1D46A | 𝑪 | \biC | Mathematical Bold Italic Capital C |
| U+1D46B | 𝑫 | \biD | Mathematical Bold Italic Capital D |
| U+1D46C | 𝑬 | \biE | Mathematical Bold Italic Capital E |
| U+1D46D | 𝑭 | \biF | Mathematical Bold Italic Capital F |
| U+1D46E | 𝑮 | \biG | Mathematical Bold Italic Capital G |
| U+1D46F | 𝑯 | \biH | Mathematical Bold Italic Capital H |
| U+1D470 | 𝑰 | \biI | Mathematical Bold Italic Capital I |
| U+1D471 | 𝑱 | \biJ | Mathematical Bold Italic Capital J |
| U+1D472 | 𝑲 | \biK | Mathematical Bold Italic Capital K |
| U+1D473 | 𝑳 | \biL | Mathematical Bold Italic Capital L |
| U+1D474 | 𝑴 | \biM | Mathematical Bold Italic Capital M |
| U+1D475 | 𝑵 | \biN | Mathematical Bold Italic Capital N |
| U+1D476 | 𝑶 | \biO | Mathematical Bold Italic Capital O |
| U+1D477 | 𝑷 | \biP | Mathematical Bold Italic Capital P |
| U+1D478 | 𝑸 | \biQ | Mathematical Bold Italic Capital Q |
| U+1D479 | 𝑹 | \biR | Mathematical Bold Italic Capital R |
| U+1D47A | 𝑺 | \biS | Mathematical Bold Italic Capital S |
| U+1D47B | 𝑻 | \biT | Mathematical Bold Italic Capital T |
| U+1D47C | 𝑼 | \biU | Mathematical Bold Italic Capital U |
| U+1D47D | 𝑽 | \biV | Mathematical Bold Italic Capital V |
| U+1D47E | 𝑾 | \biW | Mathematical Bold Italic Capital W |
| U+1D47F | 𝑿 | \biX | Mathematical Bold Italic Capital X |
| U+1D480 | 𝒀 | \biY | Mathematical Bold Italic Capital Y |
| U+1D481 | 𝒁 | \biZ | Mathematical Bold Italic Capital Z |
| U+1D482 | 𝒂 | \bia | Mathematical Bold Italic Small A |
| U+1D483 | 𝒃 | \bib | Mathematical Bold Italic Small B |
| U+1D484 | 𝒄 | \bic | Mathematical Bold Italic Small C |
| U+1D485 | 𝒅 | \bid | Mathematical Bold Italic Small D |
| U+1D486 | 𝒆 | \bie | Mathematical Bold Italic Small E |
| U+1D487 | 𝒇 | \bif | Mathematical Bold Italic Small F |
| U+1D488 | 𝒈 | \big | Mathematical Bold Italic Small G |
| U+1D489 | 𝒉 | \bih | Mathematical Bold Italic Small H |
| U+1D48A | 𝒊 | \bii | Mathematical Bold Italic Small I |
| U+1D48B | 𝒋 | \bij | Mathematical Bold Italic Small J |
| U+1D48C | 𝒌 | \bik | Mathematical Bold Italic Small K |
| U+1D48D | 𝒍 | \bil | Mathematical Bold Italic Small L |
| U+1D48E | 𝒎 | \bim | Mathematical Bold Italic Small M |
| U+1D48F | 𝒏 | \bin | Mathematical Bold Italic Small N |
| U+1D490 | 𝒐 | \bio | Mathematical Bold Italic Small O |
| U+1D491 | 𝒑 | \bip | Mathematical Bold Italic Small P |
| U+1D492 | 𝒒 | \biq | Mathematical Bold Italic Small Q |
| U+1D493 | 𝒓 | \bir | Mathematical Bold Italic Small R |
| U+1D494 | 𝒔 | \bis | Mathematical Bold Italic Small S |
| U+1D495 | 𝒕 | \bit | Mathematical Bold Italic Small T |
| U+1D496 | 𝒖 | \biu | Mathematical Bold Italic Small U |
| U+1D497 | 𝒗 | \biv | Mathematical Bold Italic Small V |
| U+1D498 | 𝒘 | \biw | Mathematical Bold Italic Small W |
| U+1D499 | 𝒙 | \bix | Mathematical Bold Italic Small X |
| U+1D49A | 𝒚 | \biy | Mathematical Bold Italic Small Y |
| U+1D49B | 𝒛 | \biz | Mathematical Bold Italic Small Z |
| U+1D49C | 𝒜 | \scrA | Mathematical Script Capital A |
| U+1D49E | 𝒞 | \scrC | Mathematical Script Capital C |
| U+1D49F | 𝒟 | \scrD | Mathematical Script Capital D |
| U+1D4A2 | 𝒢 | \scrG | Mathematical Script Capital G |
| U+1D4A5 | 𝒥 | \scrJ | Mathematical Script Capital J |
| U+1D4A6 | 𝒦 | \scrK | Mathematical Script Capital K |
| U+1D4A9 | 𝒩 | \scrN | Mathematical Script Capital N |
| U+1D4AA | 𝒪 | \scrO | Mathematical Script Capital O |
| U+1D4AB | 𝒫 | \scrP | Mathematical Script Capital P |
| U+1D4AC | 𝒬 | \scrQ | Mathematical Script Capital Q |
| U+1D4AE | 𝒮 | \scrS | Mathematical Script Capital S |
| U+1D4AF | 𝒯 | \scrT | Mathematical Script Capital T |
| U+1D4B0 | 𝒰 | \scrU | Mathematical Script Capital U |
| U+1D4B1 | 𝒱 | \scrV | Mathematical Script Capital V |
| U+1D4B2 | 𝒲 | \scrW | Mathematical Script Capital W |
| U+1D4B3 | 𝒳 | \scrX | Mathematical Script Capital X |
| U+1D4B4 | 𝒴 | \scrY | Mathematical Script Capital Y |
| U+1D4B5 | 𝒵 | \scrZ | Mathematical Script Capital Z |
| U+1D4B6 | 𝒶 | \scra | Mathematical Script Small A |
| U+1D4B7 | 𝒷 | \scrb | Mathematical Script Small B |
| U+1D4B8 | 𝒸 | \scrc | Mathematical Script Small C |
| U+1D4B9 | 𝒹 | \scrd | Mathematical Script Small D |
| U+1D4BB | 𝒻 | \scrf | Mathematical Script Small F |
| U+1D4BD | 𝒽 | \scrh | Mathematical Script Small H |
| U+1D4BE | 𝒾 | \scri | Mathematical Script Small I |
| U+1D4BF | 𝒿 | \scrj | Mathematical Script Small J |
| U+1D4C0 | 𝓀 | \scrk | Mathematical Script Small K |
| U+1D4C1 | 𝓁 | \scrl | Mathematical Script Small L |
| U+1D4C2 | 𝓂 | \scrm | Mathematical Script Small M |
| U+1D4C3 | 𝓃 | \scrn | Mathematical Script Small N |
| U+1D4C5 | 𝓅 | \scrp | Mathematical Script Small P |
| U+1D4C6 | 𝓆 | \scrq | Mathematical Script Small Q |
| U+1D4C7 | 𝓇 | \scrr | Mathematical Script Small R |
| U+1D4C8 | 𝓈 | \scrs | Mathematical Script Small S |
| U+1D4C9 | 𝓉 | \scrt | Mathematical Script Small T |
| U+1D4CA | 𝓊 | \scru | Mathematical Script Small U |
| U+1D4CB | 𝓋 | \scrv | Mathematical Script Small V |
| U+1D4CC | 𝓌 | \scrw | Mathematical Script Small W |
| U+1D4CD | 𝓍 | \scrx | Mathematical Script Small X |
| U+1D4CE | 𝓎 | \scry | Mathematical Script Small Y |
| U+1D4CF | 𝓏 | \scrz | Mathematical Script Small Z |
| U+1D4D0 | 𝓐 | \bscrA | Mathematical Bold Script Capital A |
| U+1D4D1 | 𝓑 | \bscrB | Mathematical Bold Script Capital B |
| U+1D4D2 | 𝓒 | \bscrC | Mathematical Bold Script Capital C |
| U+1D4D3 | 𝓓 | \bscrD | Mathematical Bold Script Capital D |
| U+1D4D4 | 𝓔 | \bscrE | Mathematical Bold Script Capital E |
| U+1D4D5 | 𝓕 | \bscrF | Mathematical Bold Script Capital F |
| U+1D4D6 | 𝓖 | \bscrG | Mathematical Bold Script Capital G |
| U+1D4D7 | 𝓗 | \bscrH | Mathematical Bold Script Capital H |
| U+1D4D8 | 𝓘 | \bscrI | Mathematical Bold Script Capital I |
| U+1D4D9 | 𝓙 | \bscrJ | Mathematical Bold Script Capital J |
| U+1D4DA | 𝓚 | \bscrK | Mathematical Bold Script Capital K |
| U+1D4DB | 𝓛 | \bscrL | Mathematical Bold Script Capital L |
| U+1D4DC | 𝓜 | \bscrM | Mathematical Bold Script Capital M |
| U+1D4DD | 𝓝 | \bscrN | Mathematical Bold Script Capital N |
| U+1D4DE | 𝓞 | \bscrO | Mathematical Bold Script Capital O |
| U+1D4DF | 𝓟 | \bscrP | Mathematical Bold Script Capital P |
| U+1D4E0 | 𝓠 | \bscrQ | Mathematical Bold Script Capital Q |
| U+1D4E1 | 𝓡 | \bscrR | Mathematical Bold Script Capital R |
| U+1D4E2 | 𝓢 | \bscrS | Mathematical Bold Script Capital S |
| U+1D4E3 | 𝓣 | \bscrT | Mathematical Bold Script Capital T |
| U+1D4E4 | 𝓤 | \bscrU | Mathematical Bold Script Capital U |
| U+1D4E5 | 𝓥 | \bscrV | Mathematical Bold Script Capital V |
| U+1D4E6 | 𝓦 | \bscrW | Mathematical Bold Script Capital W |
| U+1D4E7 | 𝓧 | \bscrX | Mathematical Bold Script Capital X |
| U+1D4E8 | 𝓨 | \bscrY | Mathematical Bold Script Capital Y |
| U+1D4E9 | 𝓩 | \bscrZ | Mathematical Bold Script Capital Z |
| U+1D4EA | 𝓪 | \bscra | Mathematical Bold Script Small A |
| U+1D4EB | 𝓫 | \bscrb | Mathematical Bold Script Small B |
| U+1D4EC | 𝓬 | \bscrc | Mathematical Bold Script Small C |
| U+1D4ED | 𝓭 | \bscrd | Mathematical Bold Script Small D |
| U+1D4EE | 𝓮 | \bscre | Mathematical Bold Script Small E |
| U+1D4EF | 𝓯 | \bscrf | Mathematical Bold Script Small F |
| U+1D4F0 | 𝓰 | \bscrg | Mathematical Bold Script Small G |
| U+1D4F1 | 𝓱 | \bscrh | Mathematical Bold Script Small H |
| U+1D4F2 | 𝓲 | \bscri | Mathematical Bold Script Small I |
| U+1D4F3 | 𝓳 | \bscrj | Mathematical Bold Script Small J |
| U+1D4F4 | 𝓴 | \bscrk | Mathematical Bold Script Small K |
| U+1D4F5 | 𝓵 | \bscrl | Mathematical Bold Script Small L |
| U+1D4F6 | 𝓶 | \bscrm | Mathematical Bold Script Small M |
| U+1D4F7 | 𝓷 | \bscrn | Mathematical Bold Script Small N |
| U+1D4F8 | 𝓸 | \bscro | Mathematical Bold Script Small O |
| U+1D4F9 | 𝓹 | \bscrp | Mathematical Bold Script Small P |
| U+1D4FA | 𝓺 | \bscrq | Mathematical Bold Script Small Q |
| U+1D4FB | 𝓻 | \bscrr | Mathematical Bold Script Small R |
| U+1D4FC | 𝓼 | \bscrs | Mathematical Bold Script Small S |
| U+1D4FD | 𝓽 | \bscrt | Mathematical Bold Script Small T |
| U+1D4FE | 𝓾 | \bscru | Mathematical Bold Script Small U |
| U+1D4FF | 𝓿 | \bscrv | Mathematical Bold Script Small V |
| U+1D500 | 𝔀 | \bscrw | Mathematical Bold Script Small W |
| U+1D501 | 𝔁 | \bscrx | Mathematical Bold Script Small X |
| U+1D502 | 𝔂 | \bscry | Mathematical Bold Script Small Y |
| U+1D503 | 𝔃 | \bscrz | Mathematical Bold Script Small Z |
| U+1D504 | 𝔄 | \frakA | Mathematical Fraktur Capital A |
| U+1D505 | 𝔅 | \frakB | Mathematical Fraktur Capital B |
| U+1D507 | 𝔇 | \frakD | Mathematical Fraktur Capital D |
| U+1D508 | 𝔈 | \frakE | Mathematical Fraktur Capital E |
| U+1D509 | 𝔉 | \frakF | Mathematical Fraktur Capital F |
| U+1D50A | 𝔊 | \frakG | Mathematical Fraktur Capital G |
| U+1D50D | 𝔍 | \frakJ | Mathematical Fraktur Capital J |
| U+1D50E | 𝔎 | \frakK | Mathematical Fraktur Capital K |
| U+1D50F | 𝔏 | \frakL | Mathematical Fraktur Capital L |
| U+1D510 | 𝔐 | \frakM | Mathematical Fraktur Capital M |
| U+1D511 | 𝔑 | \frakN | Mathematical Fraktur Capital N |
| U+1D512 | 𝔒 | \frakO | Mathematical Fraktur Capital O |
| U+1D513 | 𝔓 | \frakP | Mathematical Fraktur Capital P |
| U+1D514 | 𝔔 | \frakQ | Mathematical Fraktur Capital Q |
| U+1D516 | 𝔖 | \frakS | Mathematical Fraktur Capital S |
| U+1D517 | 𝔗 | \frakT | Mathematical Fraktur Capital T |
| U+1D518 | 𝔘 | \frakU | Mathematical Fraktur Capital U |
| U+1D519 | 𝔙 | \frakV | Mathematical Fraktur Capital V |
| U+1D51A | 𝔚 | \frakW | Mathematical Fraktur Capital W |
| U+1D51B | 𝔛 | \frakX | Mathematical Fraktur Capital X |
| U+1D51C | 𝔜 | \frakY | Mathematical Fraktur Capital Y |
| U+1D51E | 𝔞 | \fraka | Mathematical Fraktur Small A |
| U+1D51F | 𝔟 | \frakb | Mathematical Fraktur Small B |
| U+1D520 | 𝔠 | \frakc | Mathematical Fraktur Small C |
| U+1D521 | 𝔡 | \frakd | Mathematical Fraktur Small D |
| U+1D522 | 𝔢 | \frake | Mathematical Fraktur Small E |
| U+1D523 | 𝔣 | \frakf | Mathematical Fraktur Small F |
| U+1D524 | 𝔤 | \frakg | Mathematical Fraktur Small G |
| U+1D525 | 𝔥 | \frakh | Mathematical Fraktur Small H |
| U+1D526 | 𝔦 | \fraki | Mathematical Fraktur Small I |
| U+1D527 | 𝔧 | \frakj | Mathematical Fraktur Small J |
| U+1D528 | 𝔨 | \frakk | Mathematical Fraktur Small K |
| U+1D529 | 𝔩 | \frakl | Mathematical Fraktur Small L |
| U+1D52A | 𝔪 | \frakm | Mathematical Fraktur Small M |
| U+1D52B | 𝔫 | \frakn | Mathematical Fraktur Small N |
| U+1D52C | 𝔬 | \frako | Mathematical Fraktur Small O |
| U+1D52D | 𝔭 | \frakp | Mathematical Fraktur Small P |
| U+1D52E | 𝔮 | \frakq | Mathematical Fraktur Small Q |
| U+1D52F | 𝔯 | \frakr | Mathematical Fraktur Small R |
| U+1D530 | 𝔰 | \fraks | Mathematical Fraktur Small S |
| U+1D531 | 𝔱 | \frakt | Mathematical Fraktur Small T |
| U+1D532 | 𝔲 | \fraku | Mathematical Fraktur Small U |
| U+1D533 | 𝔳 | \frakv | Mathematical Fraktur Small V |
| U+1D534 | 𝔴 | \frakw | Mathematical Fraktur Small W |
| U+1D535 | 𝔵 | \frakx | Mathematical Fraktur Small X |
| U+1D536 | 𝔶 | \fraky | Mathematical Fraktur Small Y |
| U+1D537 | 𝔷 | \frakz | Mathematical Fraktur Small Z |
| U+1D538 | 𝔸 | \bbA | Mathematical Double-Struck Capital A |
| U+1D539 | 𝔹 | \bbB | Mathematical Double-Struck Capital B |
| U+1D53B | 𝔻 | \bbD | Mathematical Double-Struck Capital D |
| U+1D53C | 𝔼 | \bbE | Mathematical Double-Struck Capital E |
| U+1D53D | 𝔽 | \bbF | Mathematical Double-Struck Capital F |
| U+1D53E | 𝔾 | \bbG | Mathematical Double-Struck Capital G |
| U+1D540 | 𝕀 | \bbI | Mathematical Double-Struck Capital I |
| U+1D541 | 𝕁 | \bbJ | Mathematical Double-Struck Capital J |
| U+1D542 | 𝕂 | \bbK | Mathematical Double-Struck Capital K |
| U+1D543 | 𝕃 | \bbL | Mathematical Double-Struck Capital L |
| U+1D544 | 𝕄 | \bbM | Mathematical Double-Struck Capital M |
| U+1D546 | 𝕆 | \bbO | Mathematical Double-Struck Capital O |
| U+1D54A | 𝕊 | \bbS | Mathematical Double-Struck Capital S |
| U+1D54B | 𝕋 | \bbT | Mathematical Double-Struck Capital T |
| U+1D54C | 𝕌 | \bbU | Mathematical Double-Struck Capital U |
| U+1D54D | 𝕍 | \bbV | Mathematical Double-Struck Capital V |
| U+1D54E | 𝕎 | \bbW | Mathematical Double-Struck Capital W |
| U+1D54F | 𝕏 | \bbX | Mathematical Double-Struck Capital X |
| U+1D550 | 𝕐 | \bbY | Mathematical Double-Struck Capital Y |
| U+1D552 | 𝕒 | \bba | Mathematical Double-Struck Small A |
| U+1D553 | 𝕓 | \bbb | Mathematical Double-Struck Small B |
| U+1D554 | 𝕔 | \bbc | Mathematical Double-Struck Small C |
| U+1D555 | 𝕕 | \bbd | Mathematical Double-Struck Small D |
| U+1D556 | 𝕖 | \bbe | Mathematical Double-Struck Small E |
| U+1D557 | 𝕗 | \bbf | Mathematical Double-Struck Small F |
| U+1D558 | 𝕘 | \bbg | Mathematical Double-Struck Small G |
| U+1D559 | 𝕙 | \bbh | Mathematical Double-Struck Small H |
| U+1D55A | 𝕚 | \bbi | Mathematical Double-Struck Small I |
| U+1D55B | 𝕛 | \bbj | Mathematical Double-Struck Small J |
| U+1D55C | 𝕜 | \bbk | Mathematical Double-Struck Small K |
| U+1D55D | 𝕝 | \bbl | Mathematical Double-Struck Small L |
| U+1D55E | 𝕞 | \bbm | Mathematical Double-Struck Small M |
| U+1D55F | 𝕟 | \bbn | Mathematical Double-Struck Small N |
| U+1D560 | 𝕠 | \bbo | Mathematical Double-Struck Small O |
| U+1D561 | 𝕡 | \bbp | Mathematical Double-Struck Small P |
| U+1D562 | 𝕢 | \bbq | Mathematical Double-Struck Small Q |
| U+1D563 | 𝕣 | \bbr | Mathematical Double-Struck Small R |
| U+1D564 | 𝕤 | \bbs | Mathematical Double-Struck Small S |
| U+1D565 | 𝕥 | \bbt | Mathematical Double-Struck Small T |
| U+1D566 | 𝕦 | \bbu | Mathematical Double-Struck Small U |
| U+1D567 | 𝕧 | \bbv | Mathematical Double-Struck Small V |
| U+1D568 | 𝕨 | \bbw | Mathematical Double-Struck Small W |
| U+1D569 | 𝕩 | \bbx | Mathematical Double-Struck Small X |
| U+1D56A | 𝕪 | \bby | Mathematical Double-Struck Small Y |
| U+1D56B | 𝕫 | \bbz | Mathematical Double-Struck Small Z |
| U+1D56C | 𝕬 | \bfrakA | Mathematical Bold Fraktur Capital A |
| U+1D56D | 𝕭 | \bfrakB | Mathematical Bold Fraktur Capital B |
| U+1D56E | 𝕮 | \bfrakC | Mathematical Bold Fraktur Capital C |
| U+1D56F | 𝕯 | \bfrakD | Mathematical Bold Fraktur Capital D |
| U+1D570 | 𝕰 | \bfrakE | Mathematical Bold Fraktur Capital E |
| U+1D571 | 𝕱 | \bfrakF | Mathematical Bold Fraktur Capital F |
| U+1D572 | 𝕲 | \bfrakG | Mathematical Bold Fraktur Capital G |
| U+1D573 | 𝕳 | \bfrakH | Mathematical Bold Fraktur Capital H |
| U+1D574 | 𝕴 | \bfrakI | Mathematical Bold Fraktur Capital I |
| U+1D575 | 𝕵 | \bfrakJ | Mathematical Bold Fraktur Capital J |
| U+1D576 | 𝕶 | \bfrakK | Mathematical Bold Fraktur Capital K |
| U+1D577 | 𝕷 | \bfrakL | Mathematical Bold Fraktur Capital L |
| U+1D578 | 𝕸 | \bfrakM | Mathematical Bold Fraktur Capital M |
| U+1D579 | 𝕹 | \bfrakN | Mathematical Bold Fraktur Capital N |
| U+1D57A | 𝕺 | \bfrakO | Mathematical Bold Fraktur Capital O |
| U+1D57B | 𝕻 | \bfrakP | Mathematical Bold Fraktur Capital P |
| U+1D57C | 𝕼 | \bfrakQ | Mathematical Bold Fraktur Capital Q |
| U+1D57D | 𝕽 | \bfrakR | Mathematical Bold Fraktur Capital R |
| U+1D57E | 𝕾 | \bfrakS | Mathematical Bold Fraktur Capital S |
| U+1D57F | 𝕿 | \bfrakT | Mathematical Bold Fraktur Capital T |
| U+1D580 | 𝖀 | \bfrakU | Mathematical Bold Fraktur Capital U |
| U+1D581 | 𝖁 | \bfrakV | Mathematical Bold Fraktur Capital V |
| U+1D582 | 𝖂 | \bfrakW | Mathematical Bold Fraktur Capital W |
| U+1D583 | 𝖃 | \bfrakX | Mathematical Bold Fraktur Capital X |
| U+1D584 | 𝖄 | \bfrakY | Mathematical Bold Fraktur Capital Y |
| U+1D585 | 𝖅 | \bfrakZ | Mathematical Bold Fraktur Capital Z |
| U+1D586 | 𝖆 | \bfraka | Mathematical Bold Fraktur Small A |
| U+1D587 | 𝖇 | \bfrakb | Mathematical Bold Fraktur Small B |
| U+1D588 | 𝖈 | \bfrakc | Mathematical Bold Fraktur Small C |
| U+1D589 | 𝖉 | \bfrakd | Mathematical Bold Fraktur Small D |
| U+1D58A | 𝖊 | \bfrake | Mathematical Bold Fraktur Small E |
| U+1D58B | 𝖋 | \bfrakf | Mathematical Bold Fraktur Small F |
| U+1D58C | 𝖌 | \bfrakg | Mathematical Bold Fraktur Small G |
| U+1D58D | 𝖍 | \bfrakh | Mathematical Bold Fraktur Small H |
| U+1D58E | 𝖎 | \bfraki | Mathematical Bold Fraktur Small I |
| U+1D58F | 𝖏 | \bfrakj | Mathematical Bold Fraktur Small J |
| U+1D590 | 𝖐 | \bfrakk | Mathematical Bold Fraktur Small K |
| U+1D591 | 𝖑 | \bfrakl | Mathematical Bold Fraktur Small L |
| U+1D592 | 𝖒 | \bfrakm | Mathematical Bold Fraktur Small M |
| U+1D593 | 𝖓 | \bfrakn | Mathematical Bold Fraktur Small N |
| U+1D594 | 𝖔 | \bfrako | Mathematical Bold Fraktur Small O |
| U+1D595 | 𝖕 | \bfrakp | Mathematical Bold Fraktur Small P |
| U+1D596 | 𝖖 | \bfrakq | Mathematical Bold Fraktur Small Q |
| U+1D597 | 𝖗 | \bfrakr | Mathematical Bold Fraktur Small R |
| U+1D598 | 𝖘 | \bfraks | Mathematical Bold Fraktur Small S |
| U+1D599 | 𝖙 | \bfrakt | Mathematical Bold Fraktur Small T |
| U+1D59A | 𝖚 | \bfraku | Mathematical Bold Fraktur Small U |
| U+1D59B | 𝖛 | \bfrakv | Mathematical Bold Fraktur Small V |
| U+1D59C | 𝖜 | \bfrakw | Mathematical Bold Fraktur Small W |
| U+1D59D | 𝖝 | \bfrakx | Mathematical Bold Fraktur Small X |
| U+1D59E | 𝖞 | \bfraky | Mathematical Bold Fraktur Small Y |
| U+1D59F | 𝖟 | \bfrakz | Mathematical Bold Fraktur Small Z |
| U+1D5A0 | 𝖠 | \sansA | Mathematical Sans-Serif Capital A |
| U+1D5A1 | 𝖡 | \sansB | Mathematical Sans-Serif Capital B |
| U+1D5A2 | 𝖢 | \sansC | Mathematical Sans-Serif Capital C |
| U+1D5A3 | 𝖣 | \sansD | Mathematical Sans-Serif Capital D |
| U+1D5A4 | 𝖤 | \sansE | Mathematical Sans-Serif Capital E |
| U+1D5A5 | 𝖥 | \sansF | Mathematical Sans-Serif Capital F |
| U+1D5A6 | 𝖦 | \sansG | Mathematical Sans-Serif Capital G |
| U+1D5A7 | 𝖧 | \sansH | Mathematical Sans-Serif Capital H |
| U+1D5A8 | 𝖨 | \sansI | Mathematical Sans-Serif Capital I |
| U+1D5A9 | 𝖩 | \sansJ | Mathematical Sans-Serif Capital J |
| U+1D5AA | 𝖪 | \sansK | Mathematical Sans-Serif Capital K |
| U+1D5AB | 𝖫 | \sansL | Mathematical Sans-Serif Capital L |
| U+1D5AC | 𝖬 | \sansM | Mathematical Sans-Serif Capital M |
| U+1D5AD | 𝖭 | \sansN | Mathematical Sans-Serif Capital N |
| U+1D5AE | 𝖮 | \sansO | Mathematical Sans-Serif Capital O |
| U+1D5AF | 𝖯 | \sansP | Mathematical Sans-Serif Capital P |
| U+1D5B0 | 𝖰 | \sansQ | Mathematical Sans-Serif Capital Q |
| U+1D5B1 | 𝖱 | \sansR | Mathematical Sans-Serif Capital R |
| U+1D5B2 | 𝖲 | \sansS | Mathematical Sans-Serif Capital S |
| U+1D5B3 | 𝖳 | \sansT | Mathematical Sans-Serif Capital T |
| U+1D5B4 | 𝖴 | \sansU | Mathematical Sans-Serif Capital U |
| U+1D5B5 | 𝖵 | \sansV | Mathematical Sans-Serif Capital V |
| U+1D5B6 | 𝖶 | \sansW | Mathematical Sans-Serif Capital W |
| U+1D5B7 | 𝖷 | \sansX | Mathematical Sans-Serif Capital X |
| U+1D5B8 | 𝖸 | \sansY | Mathematical Sans-Serif Capital Y |
| U+1D5B9 | 𝖹 | \sansZ | Mathematical Sans-Serif Capital Z |
| U+1D5BA | 𝖺 | \sansa | Mathematical Sans-Serif Small A |
| U+1D5BB | 𝖻 | \sansb | Mathematical Sans-Serif Small B |
| U+1D5BC | 𝖼 | \sansc | Mathematical Sans-Serif Small C |
| U+1D5BD | 𝖽 | \sansd | Mathematical Sans-Serif Small D |
| U+1D5BE | 𝖾 | \sanse | Mathematical Sans-Serif Small E |
| U+1D5BF | 𝖿 | \sansf | Mathematical Sans-Serif Small F |
| U+1D5C0 | 𝗀 | \sansg | Mathematical Sans-Serif Small G |
| U+1D5C1 | 𝗁 | \sansh | Mathematical Sans-Serif Small H |
| U+1D5C2 | 𝗂 | \sansi | Mathematical Sans-Serif Small I |
| U+1D5C3 | 𝗃 | \sansj | Mathematical Sans-Serif Small J |
| U+1D5C4 | 𝗄 | \sansk | Mathematical Sans-Serif Small K |
| U+1D5C5 | 𝗅 | \sansl | Mathematical Sans-Serif Small L |
| U+1D5C6 | 𝗆 | \sansm | Mathematical Sans-Serif Small M |
| U+1D5C7 | 𝗇 | \sansn | Mathematical Sans-Serif Small N |
| U+1D5C8 | 𝗈 | \sanso | Mathematical Sans-Serif Small O |
| U+1D5C9 | 𝗉 | \sansp | Mathematical Sans-Serif Small P |
| U+1D5CA | 𝗊 | \sansq | Mathematical Sans-Serif Small Q |
| U+1D5CB | 𝗋 | \sansr | Mathematical Sans-Serif Small R |
| U+1D5CC | 𝗌 | \sanss | Mathematical Sans-Serif Small S |
| U+1D5CD | 𝗍 | \sanst | Mathematical Sans-Serif Small T |
| U+1D5CE | 𝗎 | \sansu | Mathematical Sans-Serif Small U |
| U+1D5CF | 𝗏 | \sansv | Mathematical Sans-Serif Small V |
| U+1D5D0 | 𝗐 | \sansw | Mathematical Sans-Serif Small W |
| U+1D5D1 | 𝗑 | \sansx | Mathematical Sans-Serif Small X |
| U+1D5D2 | 𝗒 | \sansy | Mathematical Sans-Serif Small Y |
| U+1D5D3 | 𝗓 | \sansz | Mathematical Sans-Serif Small Z |
| U+1D5D4 | 𝗔 | \bsansA | Mathematical Sans-Serif Bold Capital A |
| U+1D5D5 | 𝗕 | \bsansB | Mathematical Sans-Serif Bold Capital B |
| U+1D5D6 | 𝗖 | \bsansC | Mathematical Sans-Serif Bold Capital C |
| U+1D5D7 | 𝗗 | \bsansD | Mathematical Sans-Serif Bold Capital D |
| U+1D5D8 | 𝗘 | \bsansE | Mathematical Sans-Serif Bold Capital E |
| U+1D5D9 | 𝗙 | \bsansF | Mathematical Sans-Serif Bold Capital F |
| U+1D5DA | 𝗚 | \bsansG | Mathematical Sans-Serif Bold Capital G |
| U+1D5DB | 𝗛 | \bsansH | Mathematical Sans-Serif Bold Capital H |
| U+1D5DC | 𝗜 | \bsansI | Mathematical Sans-Serif Bold Capital I |
| U+1D5DD | 𝗝 | \bsansJ | Mathematical Sans-Serif Bold Capital J |
| U+1D5DE | 𝗞 | \bsansK | Mathematical Sans-Serif Bold Capital K |
| U+1D5DF | 𝗟 | \bsansL | Mathematical Sans-Serif Bold Capital L |
| U+1D5E0 | 𝗠 | \bsansM | Mathematical Sans-Serif Bold Capital M |
| U+1D5E1 | 𝗡 | \bsansN | Mathematical Sans-Serif Bold Capital N |
| U+1D5E2 | 𝗢 | \bsansO | Mathematical Sans-Serif Bold Capital O |
| U+1D5E3 | 𝗣 | \bsansP | Mathematical Sans-Serif Bold Capital P |
| U+1D5E4 | 𝗤 | \bsansQ | Mathematical Sans-Serif Bold Capital Q |
| U+1D5E5 | 𝗥 | \bsansR | Mathematical Sans-Serif Bold Capital R |
| U+1D5E6 | 𝗦 | \bsansS | Mathematical Sans-Serif Bold Capital S |
| U+1D5E7 | 𝗧 | \bsansT | Mathematical Sans-Serif Bold Capital T |
| U+1D5E8 | 𝗨 | \bsansU | Mathematical Sans-Serif Bold Capital U |
| U+1D5E9 | 𝗩 | \bsansV | Mathematical Sans-Serif Bold Capital V |
| U+1D5EA | 𝗪 | \bsansW | Mathematical Sans-Serif Bold Capital W |
| U+1D5EB | 𝗫 | \bsansX | Mathematical Sans-Serif Bold Capital X |
| U+1D5EC | 𝗬 | \bsansY | Mathematical Sans-Serif Bold Capital Y |
| U+1D5ED | 𝗭 | \bsansZ | Mathematical Sans-Serif Bold Capital Z |
| U+1D5EE | 𝗮 | \bsansa | Mathematical Sans-Serif Bold Small A |
| U+1D5EF | 𝗯 | \bsansb | Mathematical Sans-Serif Bold Small B |
| U+1D5F0 | 𝗰 | \bsansc | Mathematical Sans-Serif Bold Small C |
| U+1D5F1 | 𝗱 | \bsansd | Mathematical Sans-Serif Bold Small D |
| U+1D5F2 | 𝗲 | \bsanse | Mathematical Sans-Serif Bold Small E |
| U+1D5F3 | 𝗳 | \bsansf | Mathematical Sans-Serif Bold Small F |
| U+1D5F4 | 𝗴 | \bsansg | Mathematical Sans-Serif Bold Small G |
| U+1D5F5 | 𝗵 | \bsansh | Mathematical Sans-Serif Bold Small H |
| U+1D5F6 | 𝗶 | \bsansi | Mathematical Sans-Serif Bold Small I |
| U+1D5F7 | 𝗷 | \bsansj | Mathematical Sans-Serif Bold Small J |
| U+1D5F8 | 𝗸 | \bsansk | Mathematical Sans-Serif Bold Small K |
| U+1D5F9 | 𝗹 | \bsansl | Mathematical Sans-Serif Bold Small L |
| U+1D5FA | 𝗺 | \bsansm | Mathematical Sans-Serif Bold Small M |
| U+1D5FB | 𝗻 | \bsansn | Mathematical Sans-Serif Bold Small N |
| U+1D5FC | 𝗼 | \bsanso | Mathematical Sans-Serif Bold Small O |
| U+1D5FD | 𝗽 | \bsansp | Mathematical Sans-Serif Bold Small P |
| U+1D5FE | 𝗾 | \bsansq | Mathematical Sans-Serif Bold Small Q |
| U+1D5FF | 𝗿 | \bsansr | Mathematical Sans-Serif Bold Small R |
| U+1D600 | 𝘀 | \bsanss | Mathematical Sans-Serif Bold Small S |
| U+1D601 | 𝘁 | \bsanst | Mathematical Sans-Serif Bold Small T |
| U+1D602 | 𝘂 | \bsansu | Mathematical Sans-Serif Bold Small U |
| U+1D603 | 𝘃 | \bsansv | Mathematical Sans-Serif Bold Small V |
| U+1D604 | 𝘄 | \bsansw | Mathematical Sans-Serif Bold Small W |
| U+1D605 | 𝘅 | \bsansx | Mathematical Sans-Serif Bold Small X |
| U+1D606 | 𝘆 | \bsansy | Mathematical Sans-Serif Bold Small Y |
| U+1D607 | 𝘇 | \bsansz | Mathematical Sans-Serif Bold Small Z |
| U+1D608 | 𝘈 | \isansA | Mathematical Sans-Serif Italic Capital A |
| U+1D609 | 𝘉 | \isansB | Mathematical Sans-Serif Italic Capital B |
| U+1D60A | 𝘊 | \isansC | Mathematical Sans-Serif Italic Capital C |
| U+1D60B | 𝘋 | \isansD | Mathematical Sans-Serif Italic Capital D |
| U+1D60C | 𝘌 | \isansE | Mathematical Sans-Serif Italic Capital E |
| U+1D60D | 𝘍 | \isansF | Mathematical Sans-Serif Italic Capital F |
| U+1D60E | 𝘎 | \isansG | Mathematical Sans-Serif Italic Capital G |
| U+1D60F | 𝘏 | \isansH | Mathematical Sans-Serif Italic Capital H |
| U+1D610 | 𝘐 | \isansI | Mathematical Sans-Serif Italic Capital I |
| U+1D611 | 𝘑 | \isansJ | Mathematical Sans-Serif Italic Capital J |
| U+1D612 | 𝘒 | \isansK | Mathematical Sans-Serif Italic Capital K |
| U+1D613 | 𝘓 | \isansL | Mathematical Sans-Serif Italic Capital L |
| U+1D614 | 𝘔 | \isansM | Mathematical Sans-Serif Italic Capital M |
| U+1D615 | 𝘕 | \isansN | Mathematical Sans-Serif Italic Capital N |
| U+1D616 | 𝘖 | \isansO | Mathematical Sans-Serif Italic Capital O |
| U+1D617 | 𝘗 | \isansP | Mathematical Sans-Serif Italic Capital P |
| U+1D618 | 𝘘 | \isansQ | Mathematical Sans-Serif Italic Capital Q |
| U+1D619 | 𝘙 | \isansR | Mathematical Sans-Serif Italic Capital R |
| U+1D61A | 𝘚 | \isansS | Mathematical Sans-Serif Italic Capital S |
| U+1D61B | 𝘛 | \isansT | Mathematical Sans-Serif Italic Capital T |
| U+1D61C | 𝘜 | \isansU | Mathematical Sans-Serif Italic Capital U |
| U+1D61D | 𝘝 | \isansV | Mathematical Sans-Serif Italic Capital V |
| U+1D61E | 𝘞 | \isansW | Mathematical Sans-Serif Italic Capital W |
| U+1D61F | 𝘟 | \isansX | Mathematical Sans-Serif Italic Capital X |
| U+1D620 | 𝘠 | \isansY | Mathematical Sans-Serif Italic Capital Y |
| U+1D621 | 𝘡 | \isansZ | Mathematical Sans-Serif Italic Capital Z |
| U+1D622 | 𝘢 | \isansa | Mathematical Sans-Serif Italic Small A |
| U+1D623 | 𝘣 | \isansb | Mathematical Sans-Serif Italic Small B |
| U+1D624 | 𝘤 | \isansc | Mathematical Sans-Serif Italic Small C |
| U+1D625 | 𝘥 | \isansd | Mathematical Sans-Serif Italic Small D |
| U+1D626 | 𝘦 | \isanse | Mathematical Sans-Serif Italic Small E |
| U+1D627 | 𝘧 | \isansf | Mathematical Sans-Serif Italic Small F |
| U+1D628 | 𝘨 | \isansg | Mathematical Sans-Serif Italic Small G |
| U+1D629 | 𝘩 | \isansh | Mathematical Sans-Serif Italic Small H |
| U+1D62A | 𝘪 | \isansi | Mathematical Sans-Serif Italic Small I |
| U+1D62B | 𝘫 | \isansj | Mathematical Sans-Serif Italic Small J |
| U+1D62C | 𝘬 | \isansk | Mathematical Sans-Serif Italic Small K |
| U+1D62D | 𝘭 | \isansl | Mathematical Sans-Serif Italic Small L |
| U+1D62E | 𝘮 | \isansm | Mathematical Sans-Serif Italic Small M |
| U+1D62F | 𝘯 | \isansn | Mathematical Sans-Serif Italic Small N |
| U+1D630 | 𝘰 | \isanso | Mathematical Sans-Serif Italic Small O |
| U+1D631 | 𝘱 | \isansp | Mathematical Sans-Serif Italic Small P |
| U+1D632 | 𝘲 | \isansq | Mathematical Sans-Serif Italic Small Q |
| U+1D633 | 𝘳 | \isansr | Mathematical Sans-Serif Italic Small R |
| U+1D634 | 𝘴 | \isanss | Mathematical Sans-Serif Italic Small S |
| U+1D635 | 𝘵 | \isanst | Mathematical Sans-Serif Italic Small T |
| U+1D636 | 𝘶 | \isansu | Mathematical Sans-Serif Italic Small U |
| U+1D637 | 𝘷 | \isansv | Mathematical Sans-Serif Italic Small V |
| U+1D638 | 𝘸 | \isansw | Mathematical Sans-Serif Italic Small W |
| U+1D639 | 𝘹 | \isansx | Mathematical Sans-Serif Italic Small X |
| U+1D63A | 𝘺 | \isansy | Mathematical Sans-Serif Italic Small Y |
| U+1D63B | 𝘻 | \isansz | Mathematical Sans-Serif Italic Small Z |
| U+1D63C | 𝘼 | \bisansA | Mathematical Sans-Serif Bold Italic Capital A |
| U+1D63D | 𝘽 | \bisansB | Mathematical Sans-Serif Bold Italic Capital B |
| U+1D63E | 𝘾 | \bisansC | Mathematical Sans-Serif Bold Italic Capital C |
| U+1D63F | 𝘿 | \bisansD | Mathematical Sans-Serif Bold Italic Capital D |
| U+1D640 | 𝙀 | \bisansE | Mathematical Sans-Serif Bold Italic Capital E |
| U+1D641 | 𝙁 | \bisansF | Mathematical Sans-Serif Bold Italic Capital F |
| U+1D642 | 𝙂 | \bisansG | Mathematical Sans-Serif Bold Italic Capital G |
| U+1D643 | 𝙃 | \bisansH | Mathematical Sans-Serif Bold Italic Capital H |
| U+1D644 | 𝙄 | \bisansI | Mathematical Sans-Serif Bold Italic Capital I |
| U+1D645 | 𝙅 | \bisansJ | Mathematical Sans-Serif Bold Italic Capital J |
| U+1D646 | 𝙆 | \bisansK | Mathematical Sans-Serif Bold Italic Capital K |
| U+1D647 | 𝙇 | \bisansL | Mathematical Sans-Serif Bold Italic Capital L |
| U+1D648 | 𝙈 | \bisansM | Mathematical Sans-Serif Bold Italic Capital M |
| U+1D649 | 𝙉 | \bisansN | Mathematical Sans-Serif Bold Italic Capital N |
| U+1D64A | 𝙊 | \bisansO | Mathematical Sans-Serif Bold Italic Capital O |
| U+1D64B | 𝙋 | \bisansP | Mathematical Sans-Serif Bold Italic Capital P |
| U+1D64C | 𝙌 | \bisansQ | Mathematical Sans-Serif Bold Italic Capital Q |
| U+1D64D | 𝙍 | \bisansR | Mathematical Sans-Serif Bold Italic Capital R |
| U+1D64E | 𝙎 | \bisansS | Mathematical Sans-Serif Bold Italic Capital S |
| U+1D64F | 𝙏 | \bisansT | Mathematical Sans-Serif Bold Italic Capital T |
| U+1D650 | 𝙐 | \bisansU | Mathematical Sans-Serif Bold Italic Capital U |
| U+1D651 | 𝙑 | \bisansV | Mathematical Sans-Serif Bold Italic Capital V |
| U+1D652 | 𝙒 | \bisansW | Mathematical Sans-Serif Bold Italic Capital W |
| U+1D653 | 𝙓 | \bisansX | Mathematical Sans-Serif Bold Italic Capital X |
| U+1D654 | 𝙔 | \bisansY | Mathematical Sans-Serif Bold Italic Capital Y |
| U+1D655 | 𝙕 | \bisansZ | Mathematical Sans-Serif Bold Italic Capital Z |
| U+1D656 | 𝙖 | \bisansa | Mathematical Sans-Serif Bold Italic Small A |
| U+1D657 | 𝙗 | \bisansb | Mathematical Sans-Serif Bold Italic Small B |
| U+1D658 | 𝙘 | \bisansc | Mathematical Sans-Serif Bold Italic Small C |
| U+1D659 | 𝙙 | \bisansd | Mathematical Sans-Serif Bold Italic Small D |
| U+1D65A | 𝙚 | \bisanse | Mathematical Sans-Serif Bold Italic Small E |
| U+1D65B | 𝙛 | \bisansf | Mathematical Sans-Serif Bold Italic Small F |
| U+1D65C | 𝙜 | \bisansg | Mathematical Sans-Serif Bold Italic Small G |
| U+1D65D | 𝙝 | \bisansh | Mathematical Sans-Serif Bold Italic Small H |
| U+1D65E | 𝙞 | \bisansi | Mathematical Sans-Serif Bold Italic Small I |
| U+1D65F | 𝙟 | \bisansj | Mathematical Sans-Serif Bold Italic Small J |
| U+1D660 | 𝙠 | \bisansk | Mathematical Sans-Serif Bold Italic Small K |
| U+1D661 | 𝙡 | \bisansl | Mathematical Sans-Serif Bold Italic Small L |
| U+1D662 | 𝙢 | \bisansm | Mathematical Sans-Serif Bold Italic Small M |
| U+1D663 | 𝙣 | \bisansn | Mathematical Sans-Serif Bold Italic Small N |
| U+1D664 | 𝙤 | \bisanso | Mathematical Sans-Serif Bold Italic Small O |
| U+1D665 | 𝙥 | \bisansp | Mathematical Sans-Serif Bold Italic Small P |
| U+1D666 | 𝙦 | \bisansq | Mathematical Sans-Serif Bold Italic Small Q |
| U+1D667 | 𝙧 | \bisansr | Mathematical Sans-Serif Bold Italic Small R |
| U+1D668 | 𝙨 | \bisanss | Mathematical Sans-Serif Bold Italic Small S |
| U+1D669 | 𝙩 | \bisanst | Mathematical Sans-Serif Bold Italic Small T |
| U+1D66A | 𝙪 | \bisansu | Mathematical Sans-Serif Bold Italic Small U |
| U+1D66B | 𝙫 | \bisansv | Mathematical Sans-Serif Bold Italic Small V |
| U+1D66C | 𝙬 | \bisansw | Mathematical Sans-Serif Bold Italic Small W |
| U+1D66D | 𝙭 | \bisansx | Mathematical Sans-Serif Bold Italic Small X |
| U+1D66E | 𝙮 | \bisansy | Mathematical Sans-Serif Bold Italic Small Y |
| U+1D66F | 𝙯 | \bisansz | Mathematical Sans-Serif Bold Italic Small Z |
| U+1D670 | 𝙰 | \ttA | Mathematical Monospace Capital A |
| U+1D671 | 𝙱 | \ttB | Mathematical Monospace Capital B |
| U+1D672 | 𝙲 | \ttC | Mathematical Monospace Capital C |
| U+1D673 | 𝙳 | \ttD | Mathematical Monospace Capital D |
| U+1D674 | 𝙴 | \ttE | Mathematical Monospace Capital E |
| U+1D675 | 𝙵 | \ttF | Mathematical Monospace Capital F |
| U+1D676 | 𝙶 | \ttG | Mathematical Monospace Capital G |
| U+1D677 | 𝙷 | \ttH | Mathematical Monospace Capital H |
| U+1D678 | 𝙸 | \ttI | Mathematical Monospace Capital I |
| U+1D679 | 𝙹 | \ttJ | Mathematical Monospace Capital J |
| U+1D67A | 𝙺 | \ttK | Mathematical Monospace Capital K |
| U+1D67B | 𝙻 | \ttL | Mathematical Monospace Capital L |
| U+1D67C | 𝙼 | \ttM | Mathematical Monospace Capital M |
| U+1D67D | 𝙽 | \ttN | Mathematical Monospace Capital N |
| U+1D67E | 𝙾 | \ttO | Mathematical Monospace Capital O |
| U+1D67F | 𝙿 | \ttP | Mathematical Monospace Capital P |
| U+1D680 | 𝚀 | \ttQ | Mathematical Monospace Capital Q |
| U+1D681 | 𝚁 | \ttR | Mathematical Monospace Capital R |
| U+1D682 | 𝚂 | \ttS | Mathematical Monospace Capital S |
| U+1D683 | 𝚃 | \ttT | Mathematical Monospace Capital T |
| U+1D684 | 𝚄 | \ttU | Mathematical Monospace Capital U |
| U+1D685 | 𝚅 | \ttV | Mathematical Monospace Capital V |
| U+1D686 | 𝚆 | \ttW | Mathematical Monospace Capital W |
| U+1D687 | 𝚇 | \ttX | Mathematical Monospace Capital X |
| U+1D688 | 𝚈 | \ttY | Mathematical Monospace Capital Y |
| U+1D689 | 𝚉 | \ttZ | Mathematical Monospace Capital Z |
| U+1D68A | 𝚊 | \tta | Mathematical Monospace Small A |
| U+1D68B | 𝚋 | \ttb | Mathematical Monospace Small B |
| U+1D68C | 𝚌 | \ttc | Mathematical Monospace Small C |
| U+1D68D | 𝚍 | \ttd | Mathematical Monospace Small D |
| U+1D68E | 𝚎 | \tte | Mathematical Monospace Small E |
| U+1D68F | 𝚏 | \ttf | Mathematical Monospace Small F |
| U+1D690 | 𝚐 | \ttg | Mathematical Monospace Small G |
| U+1D691 | 𝚑 | \tth | Mathematical Monospace Small H |
| U+1D692 | 𝚒 | \tti | Mathematical Monospace Small I |
| U+1D693 | 𝚓 | \ttj | Mathematical Monospace Small J |
| U+1D694 | 𝚔 | \ttk | Mathematical Monospace Small K |
| U+1D695 | 𝚕 | \ttl | Mathematical Monospace Small L |
| U+1D696 | 𝚖 | \ttm | Mathematical Monospace Small M |
| U+1D697 | 𝚗 | \ttn | Mathematical Monospace Small N |
| U+1D698 | 𝚘 | \tto | Mathematical Monospace Small O |
| U+1D699 | 𝚙 | \ttp | Mathematical Monospace Small P |
| U+1D69A | 𝚚 | \ttq | Mathematical Monospace Small Q |
| U+1D69B | 𝚛 | \ttr | Mathematical Monospace Small R |
| U+1D69C | 𝚜 | \tts | Mathematical Monospace Small S |
| U+1D69D | 𝚝 | \ttt | Mathematical Monospace Small T |
| U+1D69E | 𝚞 | \ttu | Mathematical Monospace Small U |
| U+1D69F | 𝚟 | \ttv | Mathematical Monospace Small V |
| U+1D6A0 | 𝚠 | \ttw | Mathematical Monospace Small W |
| U+1D6A1 | 𝚡 | \ttx | Mathematical Monospace Small X |
| U+1D6A2 | 𝚢 | \tty | Mathematical Monospace Small Y |
| U+1D6A3 | 𝚣 | \ttz | Mathematical Monospace Small Z |
| U+1D6A4 | 𝚤 | \itimath | Mathematical Italic Small Dotless I |
| U+1D6A5 | 𝚥 | \itjmath | Mathematical Italic Small Dotless J |
| U+1D6A8 | 𝚨 | \bfAlpha | Mathematical Bold Capital Alpha |
| U+1D6A9 | 𝚩 | \bfBeta | Mathematical Bold Capital Beta |
| U+1D6AA | 𝚪 | \bfGamma | Mathematical Bold Capital Gamma |
| U+1D6AB | 𝚫 | \bfDelta | Mathematical Bold Capital Delta |
| U+1D6AC | 𝚬 | \bfEpsilon | Mathematical Bold Capital Epsilon |
| U+1D6AD | 𝚭 | \bfZeta | Mathematical Bold Capital Zeta |
| U+1D6AE | 𝚮 | \bfEta | Mathematical Bold Capital Eta |
| U+1D6AF | 𝚯 | \bfTheta | Mathematical Bold Capital Theta |
| U+1D6B0 | 𝚰 | \bfIota | Mathematical Bold Capital Iota |
| U+1D6B1 | 𝚱 | \bfKappa | Mathematical Bold Capital Kappa |
| U+1D6B2 | 𝚲 | \bfLambda | Mathematical Bold Capital Lamda |
| U+1D6B3 | 𝚳 | \bfMu | Mathematical Bold Capital Mu |
| U+1D6B4 | 𝚴 | \bfNu | Mathematical Bold Capital Nu |
| U+1D6B5 | 𝚵 | \bfXi | Mathematical Bold Capital Xi |
| U+1D6B6 | 𝚶 | \bfOmicron | Mathematical Bold Capital Omicron |
| U+1D6B7 | 𝚷 | \bfPi | Mathematical Bold Capital Pi |
| U+1D6B8 | 𝚸 | \bfRho | Mathematical Bold Capital Rho |
| U+1D6B9 | 𝚹 | \bfvarTheta | Mathematical Bold Capital Theta Symbol |
| U+1D6BA | 𝚺 | \bfSigma | Mathematical Bold Capital Sigma |
| U+1D6BB | 𝚻 | \bfTau | Mathematical Bold Capital Tau |
| U+1D6BC | 𝚼 | \bfUpsilon | Mathematical Bold Capital Upsilon |
| U+1D6BD | 𝚽 | \bfPhi | Mathematical Bold Capital Phi |
| U+1D6BE | 𝚾 | \bfChi | Mathematical Bold Capital Chi |
| U+1D6BF | 𝚿 | \bfPsi | Mathematical Bold Capital Psi |
| U+1D6C0 | 𝛀 | \bfOmega | Mathematical Bold Capital Omega |
| U+1D6C1 | 𝛁 | \bfnabla | Mathematical Bold Nabla |
| U+1D6C2 | 𝛂 | \bfalpha | Mathematical Bold Small Alpha |
| U+1D6C3 | 𝛃 | \bfbeta | Mathematical Bold Small Beta |
| U+1D6C4 | 𝛄 | \bfgamma | Mathematical Bold Small Gamma |
| U+1D6C5 | 𝛅 | \bfdelta | Mathematical Bold Small Delta |
| U+1D6C6 | 𝛆 | \bfvarepsilon | Mathematical Bold Small Epsilon |
| U+1D6C7 | 𝛇 | \bfzeta | Mathematical Bold Small Zeta |
| U+1D6C8 | 𝛈 | \bfeta | Mathematical Bold Small Eta |
| U+1D6C9 | 𝛉 | \bftheta | Mathematical Bold Small Theta |
| U+1D6CA | 𝛊 | \bfiota | Mathematical Bold Small Iota |
| U+1D6CB | 𝛋 | \bfkappa | Mathematical Bold Small Kappa |
| U+1D6CC | 𝛌 | \bflambda | Mathematical Bold Small Lamda |
| U+1D6CD | 𝛍 | \bfmu | Mathematical Bold Small Mu |
| U+1D6CE | 𝛎 | \bfnu | Mathematical Bold Small Nu |
| U+1D6CF | 𝛏 | \bfxi | Mathematical Bold Small Xi |
| U+1D6D0 | 𝛐 | \bfomicron | Mathematical Bold Small Omicron |
| U+1D6D1 | 𝛑 | \bfpi | Mathematical Bold Small Pi |
| U+1D6D2 | 𝛒 | \bfrho | Mathematical Bold Small Rho |
| U+1D6D3 | 𝛓 | \bfvarsigma | Mathematical Bold Small Final Sigma |
| U+1D6D4 | 𝛔 | \bfsigma | Mathematical Bold Small Sigma |
| U+1D6D5 | 𝛕 | \bftau | Mathematical Bold Small Tau |
| U+1D6D6 | 𝛖 | \bfupsilon | Mathematical Bold Small Upsilon |
| U+1D6D7 | 𝛗 | \bfvarphi | Mathematical Bold Small Phi |
| U+1D6D8 | 𝛘 | \bfchi | Mathematical Bold Small Chi |
| U+1D6D9 | 𝛙 | \bfpsi | Mathematical Bold Small Psi |
| U+1D6DA | 𝛚 | \bfomega | Mathematical Bold Small Omega |
| U+1D6DB | 𝛛 | \bfpartial | Mathematical Bold Partial Differential |
| U+1D6DC | 𝛜 | \bfepsilon | Mathematical Bold Epsilon Symbol |
| U+1D6DD | 𝛝 | \bfvartheta | Mathematical Bold Theta Symbol |
| U+1D6DE | 𝛞 | \bfvarkappa | Mathematical Bold Kappa Symbol |
| U+1D6DF | 𝛟 | \bfphi | Mathematical Bold Phi Symbol |
| U+1D6E0 | 𝛠 | \bfvarrho | Mathematical Bold Rho Symbol |
| U+1D6E1 | 𝛡 | \bfvarpi | Mathematical Bold Pi Symbol |
| U+1D6E2 | 𝛢 | \itAlpha | Mathematical Italic Capital Alpha |
| U+1D6E3 | 𝛣 | \itBeta | Mathematical Italic Capital Beta |
| U+1D6E4 | 𝛤 | \itGamma | Mathematical Italic Capital Gamma |
| U+1D6E5 | 𝛥 | \itDelta | Mathematical Italic Capital Delta |
| U+1D6E6 | 𝛦 | \itEpsilon | Mathematical Italic Capital Epsilon |
| U+1D6E7 | 𝛧 | \itZeta | Mathematical Italic Capital Zeta |
| U+1D6E8 | 𝛨 | \itEta | Mathematical Italic Capital Eta |
| U+1D6E9 | 𝛩 | \itTheta | Mathematical Italic Capital Theta |
| U+1D6EA | 𝛪 | \itIota | Mathematical Italic Capital Iota |
| U+1D6EB | 𝛫 | \itKappa | Mathematical Italic Capital Kappa |
| U+1D6EC | 𝛬 | \itLambda | Mathematical Italic Capital Lamda |
| U+1D6ED | 𝛭 | \itMu | Mathematical Italic Capital Mu |
| U+1D6EE | 𝛮 | \itNu | Mathematical Italic Capital Nu |
| U+1D6EF | 𝛯 | \itXi | Mathematical Italic Capital Xi |
| U+1D6F0 | 𝛰 | \itOmicron | Mathematical Italic Capital Omicron |
| U+1D6F1 | 𝛱 | \itPi | Mathematical Italic Capital Pi |
| U+1D6F2 | 𝛲 | \itRho | Mathematical Italic Capital Rho |
| U+1D6F3 | 𝛳 | \itvarTheta | Mathematical Italic Capital Theta Symbol |
| U+1D6F4 | 𝛴 | \itSigma | Mathematical Italic Capital Sigma |
| U+1D6F5 | 𝛵 | \itTau | Mathematical Italic Capital Tau |
| U+1D6F6 | 𝛶 | \itUpsilon | Mathematical Italic Capital Upsilon |
| U+1D6F7 | 𝛷 | \itPhi | Mathematical Italic Capital Phi |
| U+1D6F8 | 𝛸 | \itChi | Mathematical Italic Capital Chi |
| U+1D6F9 | 𝛹 | \itPsi | Mathematical Italic Capital Psi |
| U+1D6FA | 𝛺 | \itOmega | Mathematical Italic Capital Omega |
| U+1D6FB | 𝛻 | \itnabla | Mathematical Italic Nabla |
| U+1D6FC | 𝛼 | \italpha | Mathematical Italic Small Alpha |
| U+1D6FD | 𝛽 | \itbeta | Mathematical Italic Small Beta |
| U+1D6FE | 𝛾 | \itgamma | Mathematical Italic Small Gamma |
| U+1D6FF | 𝛿 | \itdelta | Mathematical Italic Small Delta |
| U+1D700 | 𝜀 | \itvarepsilon | Mathematical Italic Small Epsilon |
| U+1D701 | 𝜁 | \itzeta | Mathematical Italic Small Zeta |
| U+1D702 | 𝜂 | \iteta | Mathematical Italic Small Eta |
| U+1D703 | 𝜃 | \ittheta | Mathematical Italic Small Theta |
| U+1D704 | 𝜄 | \itiota | Mathematical Italic Small Iota |
| U+1D705 | 𝜅 | \itkappa | Mathematical Italic Small Kappa |
| U+1D706 | 𝜆 | \itlambda | Mathematical Italic Small Lamda |
| U+1D707 | 𝜇 | \itmu | Mathematical Italic Small Mu |
| U+1D708 | 𝜈 | \itnu | Mathematical Italic Small Nu |
| U+1D709 | 𝜉 | \itxi | Mathematical Italic Small Xi |
| U+1D70A | 𝜊 | \itomicron | Mathematical Italic Small Omicron |
| U+1D70B | 𝜋 | \itpi | Mathematical Italic Small Pi |
| U+1D70C | 𝜌 | \itrho | Mathematical Italic Small Rho |
| U+1D70D | 𝜍 | \itvarsigma | Mathematical Italic Small Final Sigma |
| U+1D70E | 𝜎 | \itsigma | Mathematical Italic Small Sigma |
| U+1D70F | 𝜏 | \ittau | Mathematical Italic Small Tau |
| U+1D710 | 𝜐 | \itupsilon | Mathematical Italic Small Upsilon |
| U+1D711 | 𝜑 | \itvarphi | Mathematical Italic Small Phi |
| U+1D712 | 𝜒 | \itchi | Mathematical Italic Small Chi |
| U+1D713 | 𝜓 | \itpsi | Mathematical Italic Small Psi |
| U+1D714 | 𝜔 | \itomega | Mathematical Italic Small Omega |
| U+1D715 | 𝜕 | \itpartial | Mathematical Italic Partial Differential |
| U+1D716 | 𝜖 | \itepsilon | Mathematical Italic Epsilon Symbol |
| U+1D717 | 𝜗 | \itvartheta | Mathematical Italic Theta Symbol |
| U+1D718 | 𝜘 | \itvarkappa | Mathematical Italic Kappa Symbol |
| U+1D719 | 𝜙 | \itphi | Mathematical Italic Phi Symbol |
| U+1D71A | 𝜚 | \itvarrho | Mathematical Italic Rho Symbol |
| U+1D71B | 𝜛 | \itvarpi | Mathematical Italic Pi Symbol |
| U+1D71C | 𝜜 | \biAlpha | Mathematical Bold Italic Capital Alpha |
| U+1D71D | 𝜝 | \biBeta | Mathematical Bold Italic Capital Beta |
| U+1D71E | 𝜞 | \biGamma | Mathematical Bold Italic Capital Gamma |
| U+1D71F | 𝜟 | \biDelta | Mathematical Bold Italic Capital Delta |
| U+1D720 | 𝜠 | \biEpsilon | Mathematical Bold Italic Capital Epsilon |
| U+1D721 | 𝜡 | \biZeta | Mathematical Bold Italic Capital Zeta |
| U+1D722 | 𝜢 | \biEta | Mathematical Bold Italic Capital Eta |
| U+1D723 | 𝜣 | \biTheta | Mathematical Bold Italic Capital Theta |
| U+1D724 | 𝜤 | \biIota | Mathematical Bold Italic Capital Iota |
| U+1D725 | 𝜥 | \biKappa | Mathematical Bold Italic Capital Kappa |
| U+1D726 | 𝜦 | \biLambda | Mathematical Bold Italic Capital Lamda |
| U+1D727 | 𝜧 | \biMu | Mathematical Bold Italic Capital Mu |
| U+1D728 | 𝜨 | \biNu | Mathematical Bold Italic Capital Nu |
| U+1D729 | 𝜩 | \biXi | Mathematical Bold Italic Capital Xi |
| U+1D72A | 𝜪 | \biOmicron | Mathematical Bold Italic Capital Omicron |
| U+1D72B | 𝜫 | \biPi | Mathematical Bold Italic Capital Pi |
| U+1D72C | 𝜬 | \biRho | Mathematical Bold Italic Capital Rho |
| U+1D72D | 𝜭 | \bivarTheta | Mathematical Bold Italic Capital Theta Symbol |
| U+1D72E | 𝜮 | \biSigma | Mathematical Bold Italic Capital Sigma |
| U+1D72F | 𝜯 | \biTau | Mathematical Bold Italic Capital Tau |
| U+1D730 | 𝜰 | \biUpsilon | Mathematical Bold Italic Capital Upsilon |
| U+1D731 | 𝜱 | \biPhi | Mathematical Bold Italic Capital Phi |
| U+1D732 | 𝜲 | \biChi | Mathematical Bold Italic Capital Chi |
| U+1D733 | 𝜳 | \biPsi | Mathematical Bold Italic Capital Psi |
| U+1D734 | 𝜴 | \biOmega | Mathematical Bold Italic Capital Omega |
| U+1D735 | 𝜵 | \binabla | Mathematical Bold Italic Nabla |
| U+1D736 | 𝜶 | \bialpha | Mathematical Bold Italic Small Alpha |
| U+1D737 | 𝜷 | \bibeta | Mathematical Bold Italic Small Beta |
| U+1D738 | 𝜸 | \bigamma | Mathematical Bold Italic Small Gamma |
| U+1D739 | 𝜹 | \bidelta | Mathematical Bold Italic Small Delta |
| U+1D73A | 𝜺 | \bivarepsilon | Mathematical Bold Italic Small Epsilon |
| U+1D73B | 𝜻 | \bizeta | Mathematical Bold Italic Small Zeta |
| U+1D73C | 𝜼 | \bieta | Mathematical Bold Italic Small Eta |
| U+1D73D | 𝜽 | \bitheta | Mathematical Bold Italic Small Theta |
| U+1D73E | 𝜾 | \biiota | Mathematical Bold Italic Small Iota |
| U+1D73F | 𝜿 | \bikappa | Mathematical Bold Italic Small Kappa |
| U+1D740 | 𝝀 | \bilambda | Mathematical Bold Italic Small Lamda |
| U+1D741 | 𝝁 | \bimu | Mathematical Bold Italic Small Mu |
| U+1D742 | 𝝂 | \binu | Mathematical Bold Italic Small Nu |
| U+1D743 | 𝝃 | \bixi | Mathematical Bold Italic Small Xi |
| U+1D744 | 𝝄 | \biomicron | Mathematical Bold Italic Small Omicron |
| U+1D745 | 𝝅 | \bipi | Mathematical Bold Italic Small Pi |
| U+1D746 | 𝝆 | \birho | Mathematical Bold Italic Small Rho |
| U+1D747 | 𝝇 | \bivarsigma | Mathematical Bold Italic Small Final Sigma |
| U+1D748 | 𝝈 | \bisigma | Mathematical Bold Italic Small Sigma |
| U+1D749 | 𝝉 | \bitau | Mathematical Bold Italic Small Tau |
| U+1D74A | 𝝊 | \biupsilon | Mathematical Bold Italic Small Upsilon |
| U+1D74B | 𝝋 | \bivarphi | Mathematical Bold Italic Small Phi |
| U+1D74C | 𝝌 | \bichi | Mathematical Bold Italic Small Chi |
| U+1D74D | 𝝍 | \bipsi | Mathematical Bold Italic Small Psi |
| U+1D74E | 𝝎 | \biomega | Mathematical Bold Italic Small Omega |
| U+1D74F | 𝝏 | \bipartial | Mathematical Bold Italic Partial Differential |
| U+1D750 | 𝝐 | \biepsilon | Mathematical Bold Italic Epsilon Symbol |
| U+1D751 | 𝝑 | \bivartheta | Mathematical Bold Italic Theta Symbol |
| U+1D752 | 𝝒 | \bivarkappa | Mathematical Bold Italic Kappa Symbol |
| U+1D753 | 𝝓 | \biphi | Mathematical Bold Italic Phi Symbol |
| U+1D754 | 𝝔 | \bivarrho | Mathematical Bold Italic Rho Symbol |
| U+1D755 | 𝝕 | \bivarpi | Mathematical Bold Italic Pi Symbol |
| U+1D756 | 𝝖 | \bsansAlpha | Mathematical Sans-Serif Bold Capital Alpha |
| U+1D757 | 𝝗 | \bsansBeta | Mathematical Sans-Serif Bold Capital Beta |
| U+1D758 | 𝝘 | \bsansGamma | Mathematical Sans-Serif Bold Capital Gamma |
| U+1D759 | 𝝙 | \bsansDelta | Mathematical Sans-Serif Bold Capital Delta |
| U+1D75A | 𝝚 | \bsansEpsilon | Mathematical Sans-Serif Bold Capital Epsilon |
| U+1D75B | 𝝛 | \bsansZeta | Mathematical Sans-Serif Bold Capital Zeta |
| U+1D75C | 𝝜 | \bsansEta | Mathematical Sans-Serif Bold Capital Eta |
| U+1D75D | 𝝝 | \bsansTheta | Mathematical Sans-Serif Bold Capital Theta |
| U+1D75E | 𝝞 | \bsansIota | Mathematical Sans-Serif Bold Capital Iota |
| U+1D75F | 𝝟 | \bsansKappa | Mathematical Sans-Serif Bold Capital Kappa |
| U+1D760 | 𝝠 | \bsansLambda | Mathematical Sans-Serif Bold Capital Lamda |
| U+1D761 | 𝝡 | \bsansMu | Mathematical Sans-Serif Bold Capital Mu |
| U+1D762 | 𝝢 | \bsansNu | Mathematical Sans-Serif Bold Capital Nu |
| U+1D763 | 𝝣 | \bsansXi | Mathematical Sans-Serif Bold Capital Xi |
| U+1D764 | 𝝤 | \bsansOmicron | Mathematical Sans-Serif Bold Capital Omicron |
| U+1D765 | 𝝥 | \bsansPi | Mathematical Sans-Serif Bold Capital Pi |
| U+1D766 | 𝝦 | \bsansRho | Mathematical Sans-Serif Bold Capital Rho |
| U+1D767 | 𝝧 | \bsansvarTheta | Mathematical Sans-Serif Bold Capital Theta Symbol |
| U+1D768 | 𝝨 | \bsansSigma | Mathematical Sans-Serif Bold Capital Sigma |
| U+1D769 | 𝝩 | \bsansTau | Mathematical Sans-Serif Bold Capital Tau |
| U+1D76A | 𝝪 | \bsansUpsilon | Mathematical Sans-Serif Bold Capital Upsilon |
| U+1D76B | 𝝫 | \bsansPhi | Mathematical Sans-Serif Bold Capital Phi |
| U+1D76C | 𝝬 | \bsansChi | Mathematical Sans-Serif Bold Capital Chi |
| U+1D76D | 𝝭 | \bsansPsi | Mathematical Sans-Serif Bold Capital Psi |
| U+1D76E | 𝝮 | \bsansOmega | Mathematical Sans-Serif Bold Capital Omega |
| U+1D76F | 𝝯 | \bsansnabla | Mathematical Sans-Serif Bold Nabla |
| U+1D770 | 𝝰 | \bsansalpha | Mathematical Sans-Serif Bold Small Alpha |
| U+1D771 | 𝝱 | \bsansbeta | Mathematical Sans-Serif Bold Small Beta |
| U+1D772 | 𝝲 | \bsansgamma | Mathematical Sans-Serif Bold Small Gamma |
| U+1D773 | 𝝳 | \bsansdelta | Mathematical Sans-Serif Bold Small Delta |
| U+1D774 | 𝝴 | \bsansvarepsilon | Mathematical Sans-Serif Bold Small Epsilon |
| U+1D775 | 𝝵 | \bsanszeta | Mathematical Sans-Serif Bold Small Zeta |
| U+1D776 | 𝝶 | \bsanseta | Mathematical Sans-Serif Bold Small Eta |
| U+1D777 | 𝝷 | \bsanstheta | Mathematical Sans-Serif Bold Small Theta |
| U+1D778 | 𝝸 | \bsansiota | Mathematical Sans-Serif Bold Small Iota |
| U+1D779 | 𝝹 | \bsanskappa | Mathematical Sans-Serif Bold Small Kappa |
| U+1D77A | 𝝺 | \bsanslambda | Mathematical Sans-Serif Bold Small Lamda |
| U+1D77B | 𝝻 | \bsansmu | Mathematical Sans-Serif Bold Small Mu |
| U+1D77C | 𝝼 | \bsansnu | Mathematical Sans-Serif Bold Small Nu |
| U+1D77D | 𝝽 | \bsansxi | Mathematical Sans-Serif Bold Small Xi |
| U+1D77E | 𝝾 | \bsansomicron | Mathematical Sans-Serif Bold Small Omicron |
| U+1D77F | 𝝿 | \bsanspi | Mathematical Sans-Serif Bold Small Pi |
| U+1D780 | 𝞀 | \bsansrho | Mathematical Sans-Serif Bold Small Rho |
| U+1D781 | 𝞁 | \bsansvarsigma | Mathematical Sans-Serif Bold Small Final Sigma |
| U+1D782 | 𝞂 | \bsanssigma | Mathematical Sans-Serif Bold Small Sigma |
| U+1D783 | 𝞃 | \bsanstau | Mathematical Sans-Serif Bold Small Tau |
| U+1D784 | 𝞄 | \bsansupsilon | Mathematical Sans-Serif Bold Small Upsilon |
| U+1D785 | 𝞅 | \bsansvarphi | Mathematical Sans-Serif Bold Small Phi |
| U+1D786 | 𝞆 | \bsanschi | Mathematical Sans-Serif Bold Small Chi |
| U+1D787 | 𝞇 | \bsanspsi | Mathematical Sans-Serif Bold Small Psi |
| U+1D788 | 𝞈 | \bsansomega | Mathematical Sans-Serif Bold Small Omega |
| U+1D789 | 𝞉 | \bsanspartial | Mathematical Sans-Serif Bold Partial Differential |
| U+1D78A | 𝞊 | \bsansepsilon | Mathematical Sans-Serif Bold Epsilon Symbol |
| U+1D78B | 𝞋 | \bsansvartheta | Mathematical Sans-Serif Bold Theta Symbol |
| U+1D78C | 𝞌 | \bsansvarkappa | Mathematical Sans-Serif Bold Kappa Symbol |
| U+1D78D | 𝞍 | \bsansphi | Mathematical Sans-Serif Bold Phi Symbol |
| U+1D78E | 𝞎 | \bsansvarrho | Mathematical Sans-Serif Bold Rho Symbol |
| U+1D78F | 𝞏 | \bsansvarpi | Mathematical Sans-Serif Bold Pi Symbol |
| U+1D790 | 𝞐 | \bisansAlpha | Mathematical Sans-Serif Bold Italic Capital Alpha |
| U+1D791 | 𝞑 | \bisansBeta | Mathematical Sans-Serif Bold Italic Capital Beta |
| U+1D792 | 𝞒 | \bisansGamma | Mathematical Sans-Serif Bold Italic Capital Gamma |
| U+1D793 | 𝞓 | \bisansDelta | Mathematical Sans-Serif Bold Italic Capital Delta |
| U+1D794 | 𝞔 | \bisansEpsilon | Mathematical Sans-Serif Bold Italic Capital Epsilon |
| U+1D795 | 𝞕 | \bisansZeta | Mathematical Sans-Serif Bold Italic Capital Zeta |
| U+1D796 | 𝞖 | \bisansEta | Mathematical Sans-Serif Bold Italic Capital Eta |
| U+1D797 | 𝞗 | \bisansTheta | Mathematical Sans-Serif Bold Italic Capital Theta |
| U+1D798 | 𝞘 | \bisansIota | Mathematical Sans-Serif Bold Italic Capital Iota |
| U+1D799 | 𝞙 | \bisansKappa | Mathematical Sans-Serif Bold Italic Capital Kappa |
| U+1D79A | 𝞚 | \bisansLambda | Mathematical Sans-Serif Bold Italic Capital Lamda |
| U+1D79B | 𝞛 | \bisansMu | Mathematical Sans-Serif Bold Italic Capital Mu |
| U+1D79C | 𝞜 | \bisansNu | Mathematical Sans-Serif Bold Italic Capital Nu |
| U+1D79D | 𝞝 | \bisansXi | Mathematical Sans-Serif Bold Italic Capital Xi |
| U+1D79E | 𝞞 | \bisansOmicron | Mathematical Sans-Serif Bold Italic Capital Omicron |
| U+1D79F | 𝞟 | \bisansPi | Mathematical Sans-Serif Bold Italic Capital Pi |
| U+1D7A0 | 𝞠 | \bisansRho | Mathematical Sans-Serif Bold Italic Capital Rho |
| U+1D7A1 | 𝞡 | \bisansvarTheta | Mathematical Sans-Serif Bold Italic Capital Theta Symbol |
| U+1D7A2 | 𝞢 | \bisansSigma | Mathematical Sans-Serif Bold Italic Capital Sigma |
| U+1D7A3 | 𝞣 | \bisansTau | Mathematical Sans-Serif Bold Italic Capital Tau |
| U+1D7A4 | 𝞤 | \bisansUpsilon | Mathematical Sans-Serif Bold Italic Capital Upsilon |
| U+1D7A5 | 𝞥 | \bisansPhi | Mathematical Sans-Serif Bold Italic Capital Phi |
| U+1D7A6 | 𝞦 | \bisansChi | Mathematical Sans-Serif Bold Italic Capital Chi |
| U+1D7A7 | 𝞧 | \bisansPsi | Mathematical Sans-Serif Bold Italic Capital Psi |
| U+1D7A8 | 𝞨 | \bisansOmega | Mathematical Sans-Serif Bold Italic Capital Omega |
| U+1D7A9 | 𝞩 | \bisansnabla | Mathematical Sans-Serif Bold Italic Nabla |
| U+1D7AA | 𝞪 | \bisansalpha | Mathematical Sans-Serif Bold Italic Small Alpha |
| U+1D7AB | 𝞫 | \bisansbeta | Mathematical Sans-Serif Bold Italic Small Beta |
| U+1D7AC | 𝞬 | \bisansgamma | Mathematical Sans-Serif Bold Italic Small Gamma |
| U+1D7AD | 𝞭 | \bisansdelta | Mathematical Sans-Serif Bold Italic Small Delta |
| U+1D7AE | 𝞮 | \bisansvarepsilon | Mathematical Sans-Serif Bold Italic Small Epsilon |
| U+1D7AF | 𝞯 | \bisanszeta | Mathematical Sans-Serif Bold Italic Small Zeta |
| U+1D7B0 | 𝞰 | \bisanseta | Mathematical Sans-Serif Bold Italic Small Eta |
| U+1D7B1 | 𝞱 | \bisanstheta | Mathematical Sans-Serif Bold Italic Small Theta |
| U+1D7B2 | 𝞲 | \bisansiota | Mathematical Sans-Serif Bold Italic Small Iota |
| U+1D7B3 | 𝞳 | \bisanskappa | Mathematical Sans-Serif Bold Italic Small Kappa |
| U+1D7B4 | 𝞴 | \bisanslambda | Mathematical Sans-Serif Bold Italic Small Lamda |
| U+1D7B5 | 𝞵 | \bisansmu | Mathematical Sans-Serif Bold Italic Small Mu |
| U+1D7B6 | 𝞶 | \bisansnu | Mathematical Sans-Serif Bold Italic Small Nu |
| U+1D7B7 | 𝞷 | \bisansxi | Mathematical Sans-Serif Bold Italic Small Xi |
| U+1D7B8 | 𝞸 | \bisansomicron | Mathematical Sans-Serif Bold Italic Small Omicron |
| U+1D7B9 | 𝞹 | \bisanspi | Mathematical Sans-Serif Bold Italic Small Pi |
| U+1D7BA | 𝞺 | \bisansrho | Mathematical Sans-Serif Bold Italic Small Rho |
| U+1D7BB | 𝞻 | \bisansvarsigma | Mathematical Sans-Serif Bold Italic Small Final Sigma |
| U+1D7BC | 𝞼 | \bisanssigma | Mathematical Sans-Serif Bold Italic Small Sigma |
| U+1D7BD | 𝞽 | \bisanstau | Mathematical Sans-Serif Bold Italic Small Tau |
| U+1D7BE | 𝞾 | \bisansupsilon | Mathematical Sans-Serif Bold Italic Small Upsilon |
| U+1D7BF | 𝞿 | \bisansvarphi | Mathematical Sans-Serif Bold Italic Small Phi |
| U+1D7C0 | 𝟀 | \bisanschi | Mathematical Sans-Serif Bold Italic Small Chi |
| U+1D7C1 | 𝟁 | \bisanspsi | Mathematical Sans-Serif Bold Italic Small Psi |
| U+1D7C2 | 𝟂 | \bisansomega | Mathematical Sans-Serif Bold Italic Small Omega |
| U+1D7C3 | 𝟃 | \bisanspartial | Mathematical Sans-Serif Bold Italic Partial Differential |
| U+1D7C4 | 𝟄 | \bisansepsilon | Mathematical Sans-Serif Bold Italic Epsilon Symbol |
| U+1D7C5 | 𝟅 | \bisansvartheta | Mathematical Sans-Serif Bold Italic Theta Symbol |
| U+1D7C6 | 𝟆 | \bisansvarkappa | Mathematical Sans-Serif Bold Italic Kappa Symbol |
| U+1D7C7 | 𝟇 | \bisansphi | Mathematical Sans-Serif Bold Italic Phi Symbol |
| U+1D7C8 | 𝟈 | \bisansvarrho | Mathematical Sans-Serif Bold Italic Rho Symbol |
| U+1D7C9 | 𝟉 | \bisansvarpi | Mathematical Sans-Serif Bold Italic Pi Symbol |
| U+1D7CA | 𝟊 | \bfDigamma | Mathematical Bold Capital Digamma |
| U+1D7CB | 𝟋 | \bfdigamma | Mathematical Bold Small Digamma |
| U+1D7CE | 𝟎 | \bfzero | Mathematical Bold Digit Zero |
| U+1D7CF | 𝟏 | \bfone | Mathematical Bold Digit One |
| U+1D7D0 | 𝟐 | \bftwo | Mathematical Bold Digit Two |
| U+1D7D1 | 𝟑 | \bfthree | Mathematical Bold Digit Three |
| U+1D7D2 | 𝟒 | \bffour | Mathematical Bold Digit Four |
| U+1D7D3 | 𝟓 | \bffive | Mathematical Bold Digit Five |
| U+1D7D4 | 𝟔 | \bfsix | Mathematical Bold Digit Six |
| U+1D7D5 | 𝟕 | \bfseven | Mathematical Bold Digit Seven |
| U+1D7D6 | 𝟖 | \bfeight | Mathematical Bold Digit Eight |
| U+1D7D7 | 𝟗 | \bfnine | Mathematical Bold Digit Nine |
| U+1D7D8 | 𝟘 | \bbzero | Mathematical Double-Struck Digit Zero |
| U+1D7D9 | 𝟙 | \bbone | Mathematical Double-Struck Digit One |
| U+1D7DA | 𝟚 | \bbtwo | Mathematical Double-Struck Digit Two |
| U+1D7DB | 𝟛 | \bbthree | Mathematical Double-Struck Digit Three |
| U+1D7DC | 𝟜 | \bbfour | Mathematical Double-Struck Digit Four |
| U+1D7DD | 𝟝 | \bbfive | Mathematical Double-Struck Digit Five |
| U+1D7DE | 𝟞 | \bbsix | Mathematical Double-Struck Digit Six |
| U+1D7DF | 𝟟 | \bbseven | Mathematical Double-Struck Digit Seven |
| U+1D7E0 | 𝟠 | \bbeight | Mathematical Double-Struck Digit Eight |
| U+1D7E1 | 𝟡 | \bbnine | Mathematical Double-Struck Digit Nine |
| U+1D7E2 | 𝟢 | \sanszero | Mathematical Sans-Serif Digit Zero |
| U+1D7E3 | 𝟣 | \sansone | Mathematical Sans-Serif Digit One |
| U+1D7E4 | 𝟤 | \sanstwo | Mathematical Sans-Serif Digit Two |
| U+1D7E5 | 𝟥 | \sansthree | Mathematical Sans-Serif Digit Three |
| U+1D7E6 | 𝟦 | \sansfour | Mathematical Sans-Serif Digit Four |
| U+1D7E7 | 𝟧 | \sansfive | Mathematical Sans-Serif Digit Five |
| U+1D7E8 | 𝟨 | \sanssix | Mathematical Sans-Serif Digit Six |
| U+1D7E9 | 𝟩 | \sansseven | Mathematical Sans-Serif Digit Seven |
| U+1D7EA | 𝟪 | \sanseight | Mathematical Sans-Serif Digit Eight |
| U+1D7EB | 𝟫 | \sansnine | Mathematical Sans-Serif Digit Nine |
| U+1D7EC | 𝟬 | \bsanszero | Mathematical Sans-Serif Bold Digit Zero |
| U+1D7ED | 𝟭 | \bsansone | Mathematical Sans-Serif Bold Digit One |
| U+1D7EE | 𝟮 | \bsanstwo | Mathematical Sans-Serif Bold Digit Two |
| U+1D7EF | 𝟯 | \bsansthree | Mathematical Sans-Serif Bold Digit Three |
| U+1D7F0 | 𝟰 | \bsansfour | Mathematical Sans-Serif Bold Digit Four |
| U+1D7F1 | 𝟱 | \bsansfive | Mathematical Sans-Serif Bold Digit Five |
| U+1D7F2 | 𝟲 | \bsanssix | Mathematical Sans-Serif Bold Digit Six |
| U+1D7F3 | 𝟳 | \bsansseven | Mathematical Sans-Serif Bold Digit Seven |
| U+1D7F4 | 𝟴 | \bsanseight | Mathematical Sans-Serif Bold Digit Eight |
| U+1D7F5 | 𝟵 | \bsansnine | Mathematical Sans-Serif Bold Digit Nine |
| U+1D7F6 | 𝟶 | \ttzero | Mathematical Monospace Digit Zero |
| U+1D7F7 | 𝟷 | \ttone | Mathematical Monospace Digit One |
| U+1D7F8 | 𝟸 | \tttwo | Mathematical Monospace Digit Two |
| U+1D7F9 | 𝟹 | \ttthree | Mathematical Monospace Digit Three |
| U+1D7FA | 𝟺 | \ttfour | Mathematical Monospace Digit Four |
| U+1D7FB | 𝟻 | \ttfive | Mathematical Monospace Digit Five |
| U+1D7FC | 𝟼 | \ttsix | Mathematical Monospace Digit Six |
| U+1D7FD | 𝟽 | \ttseven | Mathematical Monospace Digit Seven |
| U+1D7FE | 𝟾 | \tteight | Mathematical Monospace Digit Eight |
| U+1D7FF | 𝟿 | \ttnine | Mathematical Monospace Digit Nine |
| U+1F004 | 🀄 | \:mahjong: | Mahjong Tile Red Dragon |
| U+1F0CF | 🃏 | \:black\_joker: | Playing Card Black Joker |
| U+1F170 | 🅰 | \:a: | Negative Squared Latin Capital Letter A |
| U+1F171 | 🅱 | \:b: | Negative Squared Latin Capital Letter B |
| U+1F17E | 🅾 | \:o2: | Negative Squared Latin Capital Letter O |
| U+1F17F | 🅿 | \:parking: | Negative Squared Latin Capital Letter P |
| U+1F18E | 🆎 | \:ab: | Negative Squared Ab |
| U+1F191 | 🆑 | \:cl: | Squared Cl |
| U+1F192 | 🆒 | \:cool: | Squared Cool |
| U+1F193 | 🆓 | \:free: | Squared Free |
| U+1F194 | 🆔 | \:id: | Squared Id |
| U+1F195 | 🆕 | \:new: | Squared New |
| U+1F196 | 🆖 | \:ng: | Squared Ng |
| U+1F197 | 🆗 | \:ok: | Squared Ok |
| U+1F198 | 🆘 | \:sos: | Squared Sos |
| U+1F199 | 🆙 | \:up: | Squared Up With Exclamation Mark |
| U+1F19A | 🆚 | \:vs: | Squared Vs |
| U+1F201 | 🈁 | \:koko: | Squared Katakana Koko |
| U+1F202 | 🈂 | \:sa: | Squared Katakana Sa |
| U+1F21A | 🈚 | \:u7121: | Squared Cjk Unified Ideograph-7121 |
| U+1F22F | 🈯 | \:u6307: | Squared Cjk Unified Ideograph-6307 |
| U+1F232 | 🈲 | \:u7981: | Squared Cjk Unified Ideograph-7981 |
| U+1F233 | 🈳 | \:u7a7a: | Squared Cjk Unified Ideograph-7A7A |
| U+1F234 | 🈴 | \:u5408: | Squared Cjk Unified Ideograph-5408 |
| U+1F235 | 🈵 | \:u6e80: | Squared Cjk Unified Ideograph-6E80 |
| U+1F236 | 🈶 | \:u6709: | Squared Cjk Unified Ideograph-6709 |
| U+1F237 | 🈷 | \:u6708: | Squared Cjk Unified Ideograph-6708 |
| U+1F238 | 🈸 | \:u7533: | Squared Cjk Unified Ideograph-7533 |
| U+1F239 | 🈹 | \:u5272: | Squared Cjk Unified Ideograph-5272 |
| U+1F23A | 🈺 | \:u55b6: | Squared Cjk Unified Ideograph-55B6 |
| U+1F250 | 🉐 | \:ideograph\_advantage: | Circled Ideograph Advantage |
| U+1F251 | 🉑 | \:accept: | Circled Ideograph Accept |
| U+1F300 | 🌀 | \:cyclone: | Cyclone |
| U+1F301 | 🌁 | \:foggy: | Foggy |
| U+1F302 | 🌂 | \:closed\_umbrella: | Closed Umbrella |
| U+1F303 | 🌃 | \:night\_with\_stars: | Night With Stars |
| U+1F304 | 🌄 | \:sunrise\_over\_mountains: | Sunrise Over Mountains |
| U+1F305 | 🌅 | \:sunrise: | Sunrise |
| U+1F306 | 🌆 | \:city\_sunset: | Cityscape At Dusk |
| U+1F307 | 🌇 | \:city\_sunrise: | Sunset Over Buildings |
| U+1F308 | 🌈 | \:rainbow: | Rainbow |
| U+1F309 | 🌉 | \:bridge\_at\_night: | Bridge At Night |
| U+1F30A | 🌊 | \:ocean: | Water Wave |
| U+1F30B | 🌋 | \:volcano: | Volcano |
| U+1F30C | 🌌 | \:milky\_way: | Milky Way |
| U+1F30D | 🌍 | \:earth\_africa: | Earth Globe Europe-Africa |
| U+1F30E | 🌎 | \:earth\_americas: | Earth Globe Americas |
| U+1F30F | 🌏 | \:earth\_asia: | Earth Globe Asia-Australia |
| U+1F310 | 🌐 | \:globe\_with\_meridians: | Globe With Meridians |
| U+1F311 | 🌑 | \:new\_moon: | New Moon Symbol |
| U+1F312 | 🌒 | \:waxing\_crescent\_moon: | Waxing Crescent Moon Symbol |
| U+1F313 | 🌓 | \:first\_quarter\_moon: | First Quarter Moon Symbol |
| U+1F314 | 🌔 | \:moon: | Waxing Gibbous Moon Symbol |
| U+1F315 | 🌕 | \:full\_moon: | Full Moon Symbol |
| U+1F316 | 🌖 | \:waning\_gibbous\_moon: | Waning Gibbous Moon Symbol |
| U+1F317 | 🌗 | \:last\_quarter\_moon: | Last Quarter Moon Symbol |
| U+1F318 | 🌘 | \:waning\_crescent\_moon: | Waning Crescent Moon Symbol |
| U+1F319 | 🌙 | \:crescent\_moon: | Crescent Moon |
| U+1F31A | 🌚 | \:new\_moon\_with\_face: | New Moon With Face |
| U+1F31B | 🌛 | \:first\_quarter\_moon\_with\_face: | First Quarter Moon With Face |
| U+1F31C | 🌜 | \:last\_quarter\_moon\_with\_face: | Last Quarter Moon With Face |
| U+1F31D | 🌝 | \:full\_moon\_with\_face: | Full Moon With Face |
| U+1F31E | 🌞 | \:sun\_with\_face: | Sun With Face |
| U+1F31F | 🌟 | \:star2: | Glowing Star |
| U+1F320 | 🌠 | \:stars: | Shooting Star |
| U+1F32D | 🌭 | \:hotdog: | Hot Dog |
| U+1F32E | 🌮 | \:taco: | Taco |
| U+1F32F | 🌯 | \:burrito: | Burrito |
| U+1F330 | 🌰 | \:chestnut: | Chestnut |
| U+1F331 | 🌱 | \:seedling: | Seedling |
| U+1F332 | 🌲 | \:evergreen\_tree: | Evergreen Tree |
| U+1F333 | 🌳 | \:deciduous\_tree: | Deciduous Tree |
| U+1F334 | 🌴 | \:palm\_tree: | Palm Tree |
| U+1F335 | 🌵 | \:cactus: | Cactus |
| U+1F337 | 🌷 | \:tulip: | Tulip |
| U+1F338 | 🌸 | \:cherry\_blossom: | Cherry Blossom |
| U+1F339 | 🌹 | \:rose: | Rose |
| U+1F33A | 🌺 | \:hibiscus: | Hibiscus |
| U+1F33B | 🌻 | \:sunflower: | Sunflower |
| U+1F33C | 🌼 | \:blossom: | Blossom |
| U+1F33D | 🌽 | \:corn: | Ear Of Maize |
| U+1F33E | 🌾 | \:ear\_of\_rice: | Ear Of Rice |
| U+1F33F | 🌿 | \:herb: | Herb |
| U+1F340 | 🍀 | \:four\_leaf\_clover: | Four Leaf Clover |
| U+1F341 | 🍁 | \:maple\_leaf: | Maple Leaf |
| U+1F342 | 🍂 | \:fallen\_leaf: | Fallen Leaf |
| U+1F343 | 🍃 | \:leaves: | Leaf Fluttering In Wind |
| U+1F344 | 🍄 | \:mushroom: | Mushroom |
| U+1F345 | 🍅 | \:tomato: | Tomato |
| U+1F346 | 🍆 | \:eggplant: | Aubergine |
| U+1F347 | 🍇 | \:grapes: | Grapes |
| U+1F348 | 🍈 | \:melon: | Melon |
| U+1F349 | 🍉 | \:watermelon: | Watermelon |
| U+1F34A | 🍊 | \:tangerine: | Tangerine |
| U+1F34B | 🍋 | \:lemon: | Lemon |
| U+1F34C | 🍌 | \:banana: | Banana |
| U+1F34D | 🍍 | \:pineapple: | Pineapple |
| U+1F34E | 🍎 | \:apple: | Red Apple |
| U+1F34F | 🍏 | \:green\_apple: | Green Apple |
| U+1F350 | 🍐 | \:pear: | Pear |
| U+1F351 | 🍑 | \:peach: | Peach |
| U+1F352 | 🍒 | \:cherries: | Cherries |
| U+1F353 | 🍓 | \:strawberry: | Strawberry |
| U+1F354 | 🍔 | \:hamburger: | Hamburger |
| U+1F355 | 🍕 | \:pizza: | Slice Of Pizza |
| U+1F356 | 🍖 | \:meat\_on\_bone: | Meat On Bone |
| U+1F357 | 🍗 | \:poultry\_leg: | Poultry Leg |
| U+1F358 | 🍘 | \:rice\_cracker: | Rice Cracker |
| U+1F359 | 🍙 | \:rice\_ball: | Rice Ball |
| U+1F35A | 🍚 | \:rice: | Cooked Rice |
| U+1F35B | 🍛 | \:curry: | Curry And Rice |
| U+1F35C | 🍜 | \:ramen: | Steaming Bowl |
| U+1F35D | 🍝 | \:spaghetti: | Spaghetti |
| U+1F35E | 🍞 | \:bread: | Bread |
| U+1F35F | 🍟 | \:fries: | French Fries |
| U+1F360 | 🍠 | \:sweet\_potato: | Roasted Sweet Potato |
| U+1F361 | 🍡 | \:dango: | Dango |
| U+1F362 | 🍢 | \:oden: | Oden |
| U+1F363 | 🍣 | \:sushi: | Sushi |
| U+1F364 | 🍤 | \:fried\_shrimp: | Fried Shrimp |
| U+1F365 | 🍥 | \:fish\_cake: | Fish Cake With Swirl Design |
| U+1F366 | 🍦 | \:icecream: | Soft Ice Cream |
| U+1F367 | 🍧 | \:shaved\_ice: | Shaved Ice |
| U+1F368 | 🍨 | \:ice\_cream: | Ice Cream |
| U+1F369 | 🍩 | \:doughnut: | Doughnut |
| U+1F36A | 🍪 | \:cookie: | Cookie |
| U+1F36B | 🍫 | \:chocolate\_bar: | Chocolate Bar |
| U+1F36C | 🍬 | \:candy: | Candy |
| U+1F36D | 🍭 | \:lollipop: | Lollipop |
| U+1F36E | 🍮 | \:custard: | Custard |
| U+1F36F | 🍯 | \:honey\_pot: | Honey Pot |
| U+1F370 | 🍰 | \:cake: | Shortcake |
| U+1F371 | 🍱 | \:bento: | Bento Box |
| U+1F372 | 🍲 | \:stew: | Pot Of Food |
| U+1F373 | 🍳 | \:fried\_egg: | Cooking |
| U+1F374 | 🍴 | \:fork\_and\_knife: | Fork And Knife |
| U+1F375 | 🍵 | \:tea: | Teacup Without Handle |
| U+1F376 | 🍶 | \:sake: | Sake Bottle And Cup |
| U+1F377 | 🍷 | \:wine\_glass: | Wine Glass |
| U+1F378 | 🍸 | \:cocktail: | Cocktail Glass |
| U+1F379 | 🍹 | \:tropical\_drink: | Tropical Drink |
| U+1F37A | 🍺 | \:beer: | Beer Mug |
| U+1F37B | 🍻 | \:beers: | Clinking Beer Mugs |
| U+1F37C | 🍼 | \:baby\_bottle: | Baby Bottle |
| U+1F37E | 🍾 | \:champagne: | Bottle With Popping Cork |
| U+1F37F | 🍿 | \:popcorn: | Popcorn |
| U+1F380 | 🎀 | \:ribbon: | Ribbon |
| U+1F381 | 🎁 | \:gift: | Wrapped Present |
| U+1F382 | 🎂 | \:birthday: | Birthday Cake |
| U+1F383 | 🎃 | \:jack\_o\_lantern: | Jack-O-Lantern |
| U+1F384 | 🎄 | \:christmas\_tree: | Christmas Tree |
| U+1F385 | 🎅 | \:santa: | Father Christmas |
| U+1F386 | 🎆 | \:fireworks: | Fireworks |
| U+1F387 | 🎇 | \:sparkler: | Firework Sparkler |
| U+1F388 | 🎈 | \:balloon: | Balloon |
| U+1F389 | 🎉 | \:tada: | Party Popper |
| U+1F38A | 🎊 | \:confetti\_ball: | Confetti Ball |
| U+1F38B | 🎋 | \:tanabata\_tree: | Tanabata Tree |
| U+1F38C | 🎌 | \:crossed\_flags: | Crossed Flags |
| U+1F38D | 🎍 | \:bamboo: | Pine Decoration |
| U+1F38E | 🎎 | \:dolls: | Japanese Dolls |
| U+1F38F | 🎏 | \:flags: | Carp Streamer |
| U+1F390 | 🎐 | \:wind\_chime: | Wind Chime |
| U+1F391 | 🎑 | \:rice\_scene: | Moon Viewing Ceremony |
| U+1F392 | 🎒 | \:school\_satchel: | School Satchel |
| U+1F393 | 🎓 | \:mortar\_board: | Graduation Cap |
| U+1F3A0 | 🎠 | \:carousel\_horse: | Carousel Horse |
| U+1F3A1 | 🎡 | \:ferris\_wheel: | Ferris Wheel |
| U+1F3A2 | 🎢 | \:roller\_coaster: | Roller Coaster |
| U+1F3A3 | 🎣 | \:fishing\_pole\_and\_fish: | Fishing Pole And Fish |
| U+1F3A4 | 🎤 | \:microphone: | Microphone |
| U+1F3A5 | 🎥 | \:movie\_camera: | Movie Camera |
| U+1F3A6 | 🎦 | \:cinema: | Cinema |
| U+1F3A7 | 🎧 | \:headphones: | Headphone |
| U+1F3A8 | 🎨 | \:art: | Artist Palette |
| U+1F3A9 | 🎩 | \:tophat: | Top Hat |
| U+1F3AA | 🎪 | \:circus\_tent: | Circus Tent |
| U+1F3AB | 🎫 | \:ticket: | Ticket |
| U+1F3AC | 🎬 | \:clapper: | Clapper Board |
| U+1F3AD | 🎭 | \:performing\_arts: | Performing Arts |
| U+1F3AE | 🎮 | \:video\_game: | Video Game |
| U+1F3AF | 🎯 | \:dart: | Direct Hit |
| U+1F3B0 | 🎰 | \:slot\_machine: | Slot Machine |
| U+1F3B1 | 🎱 | \:8ball: | Billiards |
| U+1F3B2 | 🎲 | \:game\_die: | Game Die |
| U+1F3B3 | 🎳 | \:bowling: | Bowling |
| U+1F3B4 | 🎴 | \:flower\_playing\_cards: | Flower Playing Cards |
| U+1F3B5 | 🎵 | \:musical\_note: | Musical Note |
| U+1F3B6 | 🎶 | \:notes: | Multiple Musical Notes |
| U+1F3B7 | 🎷 | \:saxophone: | Saxophone |
| U+1F3B8 | 🎸 | \:guitar: | Guitar |
| U+1F3B9 | 🎹 | \:musical\_keyboard: | Musical Keyboard |
| U+1F3BA | 🎺 | \:trumpet: | Trumpet |
| U+1F3BB | 🎻 | \:violin: | Violin |
| U+1F3BC | 🎼 | \:musical\_score: | Musical Score |
| U+1F3BD | 🎽 | \:running\_shirt\_with\_sash: | Running Shirt With Sash |
| U+1F3BE | 🎾 | \:tennis: | Tennis Racquet And Ball |
| U+1F3BF | 🎿 | \:ski: | Ski And Ski Boot |
| U+1F3C0 | 🏀 | \:basketball: | Basketball And Hoop |
| U+1F3C1 | 🏁 | \:checkered\_flag: | Chequered Flag |
| U+1F3C2 | 🏂 | \:snowboarder: | Snowboarder |
| U+1F3C3 | 🏃 | \:runner: | Runner |
| U+1F3C4 | 🏄 | \:surfer: | Surfer |
| U+1F3C5 | 🏅 | \:sports\_medal: | Sports Medal |
| U+1F3C6 | 🏆 | \:trophy: | Trophy |
| U+1F3C7 | 🏇 | \:horse\_racing: | Horse Racing |
| U+1F3C8 | 🏈 | \:football: | American Football |
| U+1F3C9 | 🏉 | \:rugby\_football: | Rugby Football |
| U+1F3CA | 🏊 | \:swimmer: | Swimmer |
| U+1F3CF | 🏏 | \:cricket\_bat\_and\_ball: | Cricket Bat And Ball |
| U+1F3D0 | 🏐 | \:volleyball: | Volleyball |
| U+1F3D1 | 🏑 | \:field\_hockey\_stick\_and\_ball: | Field Hockey Stick And Ball |
| U+1F3D2 | 🏒 | \:ice\_hockey\_stick\_and\_puck: | Ice Hockey Stick And Puck |
| U+1F3D3 | 🏓 | \:table\_tennis\_paddle\_and\_ball: | Table Tennis Paddle And Ball |
| U+1F3E0 | 🏠 | \:house: | House Building |
| U+1F3E1 | 🏡 | \:house\_with\_garden: | House With Garden |
| U+1F3E2 | 🏢 | \:office: | Office Building |
| U+1F3E3 | 🏣 | \:post\_office: | Japanese Post Office |
| U+1F3E4 | 🏤 | \:european\_post\_office: | European Post Office |
| U+1F3E5 | 🏥 | \:hospital: | Hospital |
| U+1F3E6 | 🏦 | \:bank: | Bank |
| U+1F3E7 | 🏧 | \:atm: | Automated Teller Machine |
| U+1F3E8 | 🏨 | \:hotel: | Hotel |
| U+1F3E9 | 🏩 | \:love\_hotel: | Love Hotel |
| U+1F3EA | 🏪 | \:convenience\_store: | Convenience Store |
| U+1F3EB | 🏫 | \:school: | School |
| U+1F3EC | 🏬 | \:department\_store: | Department Store |
| U+1F3ED | 🏭 | \:factory: | Factory |
| U+1F3EE | 🏮 | \:izakaya\_lantern: | Izakaya Lantern |
| U+1F3EF | 🏯 | \:japanese\_castle: | Japanese Castle |
| U+1F3F0 | 🏰 | \:european\_castle: | European Castle |
| U+1F3F4 | 🏴 | \:waving\_black\_flag: | Waving Black Flag |
| U+1F3F8 | 🏸 | \:badminton\_racquet\_and\_shuttlecock: | Badminton Racquet And Shuttlecock |
| U+1F3F9 | 🏹 | \:bow\_and\_arrow: | Bow And Arrow |
| U+1F3FA | 🏺 | \:amphora: | Amphora |
| U+1F3FB | 🏻 | \:skin-tone-2: | Emoji Modifier Fitzpatrick Type-1-2 |
| U+1F3FC | 🏼 | \:skin-tone-3: | Emoji Modifier Fitzpatrick Type-3 |
| U+1F3FD | 🏽 | \:skin-tone-4: | Emoji Modifier Fitzpatrick Type-4 |
| U+1F3FE | 🏾 | \:skin-tone-5: | Emoji Modifier Fitzpatrick Type-5 |
| U+1F3FF | 🏿 | \:skin-tone-6: | Emoji Modifier Fitzpatrick Type-6 |
| U+1F400 | 🐀 | \:rat: | Rat |
| U+1F401 | 🐁 | \:mouse2: | Mouse |
| U+1F402 | 🐂 | \:ox: | Ox |
| U+1F403 | 🐃 | \:water\_buffalo: | Water Buffalo |
| U+1F404 | 🐄 | \:cow2: | Cow |
| U+1F405 | 🐅 | \:tiger2: | Tiger |
| U+1F406 | 🐆 | \:leopard: | Leopard |
| U+1F407 | 🐇 | \:rabbit2: | Rabbit |
| U+1F408 | 🐈 | \:cat2: | Cat |
| U+1F409 | 🐉 | \:dragon: | Dragon |
| U+1F40A | 🐊 | \:crocodile: | Crocodile |
| U+1F40B | 🐋 | \:whale2: | Whale |
| U+1F40C | 🐌 | \:snail: | Snail |
| U+1F40D | 🐍 | \:snake: | Snake |
| U+1F40E | 🐎 | \:racehorse: | Horse |
| U+1F40F | 🐏 | \:ram: | Ram |
| U+1F410 | 🐐 | \:goat: | Goat |
| U+1F411 | 🐑 | \:sheep: | Sheep |
| U+1F412 | 🐒 | \:monkey: | Monkey |
| U+1F413 | 🐓 | \:rooster: | Rooster |
| U+1F414 | 🐔 | \:chicken: | Chicken |
| U+1F415 | 🐕 | \:dog2: | Dog |
| U+1F416 | 🐖 | \:pig2: | Pig |
| U+1F417 | 🐗 | \:boar: | Boar |
| U+1F418 | 🐘 | \:elephant: | Elephant |
| U+1F419 | 🐙 | \:octopus: | Octopus |
| U+1F41A | 🐚 | \:shell: | Spiral Shell |
| U+1F41B | 🐛 | \:bug: | Bug |
| U+1F41C | 🐜 | \:ant: | Ant |
| U+1F41D | 🐝 | \:bee: | Honeybee |
| U+1F41E | 🐞 | \:ladybug: | Lady Beetle |
| U+1F41F | 🐟 | \:fish: | Fish |
| U+1F420 | 🐠 | \:tropical\_fish: | Tropical Fish |
| U+1F421 | 🐡 | \:blowfish: | Blowfish |
| U+1F422 | 🐢 | \:turtle: | Turtle |
| U+1F423 | 🐣 | \:hatching\_chick: | Hatching Chick |
| U+1F424 | 🐤 | \:baby\_chick: | Baby Chick |
| U+1F425 | 🐥 | \:hatched\_chick: | Front-Facing Baby Chick |
| U+1F426 | 🐦 | \:bird: | Bird |
| U+1F427 | 🐧 | \:penguin: | Penguin |
| U+1F428 | 🐨 | \:koala: | Koala |
| U+1F429 | 🐩 | \:poodle: | Poodle |
| U+1F42A | 🐪 | \:dromedary\_camel: | Dromedary Camel |
| U+1F42B | 🐫 | \:camel: | Bactrian Camel |
| U+1F42C | 🐬 | \:dolphin: | Dolphin |
| U+1F42D | 🐭 | \:mouse: | Mouse Face |
| U+1F42E | 🐮 | \:cow: | Cow Face |
| U+1F42F | 🐯 | \:tiger: | Tiger Face |
| U+1F430 | 🐰 | \:rabbit: | Rabbit Face |
| U+1F431 | 🐱 | \:cat: | Cat Face |
| U+1F432 | 🐲 | \:dragon\_face: | Dragon Face |
| U+1F433 | 🐳 | \:whale: | Spouting Whale |
| U+1F434 | 🐴 | \:horse: | Horse Face |
| U+1F435 | 🐵 | \:monkey\_face: | Monkey Face |
| U+1F436 | 🐶 | \:dog: | Dog Face |
| U+1F437 | 🐷 | \:pig: | Pig Face |
| U+1F438 | 🐸 | \:frog: | Frog Face |
| U+1F439 | 🐹 | \:hamster: | Hamster Face |
| U+1F43A | 🐺 | \:wolf: | Wolf Face |
| U+1F43B | 🐻 | \:bear: | Bear Face |
| U+1F43C | 🐼 | \:panda\_face: | Panda Face |
| U+1F43D | 🐽 | \:pig\_nose: | Pig Nose |
| U+1F43E | 🐾 | \:feet: | Paw Prints |
| U+1F440 | 👀 | \:eyes: | Eyes |
| U+1F442 | 👂 | \:ear: | Ear |
| U+1F443 | 👃 | \:nose: | Nose |
| U+1F444 | 👄 | \:lips: | Mouth |
| U+1F445 | 👅 | \:tongue: | Tongue |
| U+1F446 | 👆 | \:point\_up\_2: | White Up Pointing Backhand Index |
| U+1F447 | 👇 | \:point\_down: | White Down Pointing Backhand Index |
| U+1F448 | 👈 | \:point\_left: | White Left Pointing Backhand Index |
| U+1F449 | 👉 | \:point\_right: | White Right Pointing Backhand Index |
| U+1F44A | 👊 | \:facepunch: | Fisted Hand Sign |
| U+1F44B | 👋 | \:wave: | Waving Hand Sign |
| U+1F44C | 👌 | \:ok\_hand: | Ok Hand Sign |
| U+1F44D | 👍 | \:+1: | Thumbs Up Sign |
| U+1F44E | 👎 | \:-1: | Thumbs Down Sign |
| U+1F44F | 👏 | \:clap: | Clapping Hands Sign |
| U+1F450 | 👐 | \:open\_hands: | Open Hands Sign |
| U+1F451 | 👑 | \:crown: | Crown |
| U+1F452 | 👒 | \:womans\_hat: | Womans Hat |
| U+1F453 | 👓 | \:eyeglasses: | Eyeglasses |
| U+1F454 | 👔 | \:necktie: | Necktie |
| U+1F455 | 👕 | \:shirt: | T-Shirt |
| U+1F456 | 👖 | \:jeans: | Jeans |
| U+1F457 | 👗 | \:dress: | Dress |
| U+1F458 | 👘 | \:kimono: | Kimono |
| U+1F459 | 👙 | \:bikini: | Bikini |
| U+1F45A | 👚 | \:womans\_clothes: | Womans Clothes |
| U+1F45B | 👛 | \:purse: | Purse |
| U+1F45C | 👜 | \:handbag: | Handbag |
| U+1F45D | 👝 | \:pouch: | Pouch |
| U+1F45E | 👞 | \:mans\_shoe: | Mans Shoe |
| U+1F45F | 👟 | \:athletic\_shoe: | Athletic Shoe |
| U+1F460 | 👠 | \:high\_heel: | High-Heeled Shoe |
| U+1F461 | 👡 | \:sandal: | Womans Sandal |
| U+1F462 | 👢 | \:boot: | Womans Boots |
| U+1F463 | 👣 | \:footprints: | Footprints |
| U+1F464 | 👤 | \:bust\_in\_silhouette: | Bust In Silhouette |
| U+1F465 | 👥 | \:busts\_in\_silhouette: | Busts In Silhouette |
| U+1F466 | 👦 | \:boy: | Boy |
| U+1F467 | 👧 | \:girl: | Girl |
| U+1F468 | 👨 | \:man: | Man |
| U+1F469 | 👩 | \:woman: | Woman |
| U+1F46A | 👪 | \:family: | Family |
| U+1F46B | 👫 | \:couple:, \:man\_and\_woman\_holding\_hands: | Man And Woman Holding Hands |
| U+1F46C | 👬 | \:two\_men\_holding\_hands: | Two Men Holding Hands |
| U+1F46D | 👭 | \:two\_women\_holding\_hands: | Two Women Holding Hands |
| U+1F46E | 👮 | \:cop: | Police Officer |
| U+1F46F | 👯 | \:dancers: | Woman With Bunny Ears |
| U+1F470 | 👰 | \:bride\_with\_veil: | Bride With Veil |
| U+1F471 | 👱 | \:person\_with\_blond\_hair: | Person With Blond Hair |
| U+1F472 | 👲 | \:man\_with\_gua\_pi\_mao: | Man With Gua Pi Mao |
| U+1F473 | 👳 | \:man\_with\_turban: | Man With Turban |
| U+1F474 | 👴 | \:older\_man: | Older Man |
| U+1F475 | 👵 | \:older\_woman: | Older Woman |
| U+1F476 | 👶 | \:baby: | Baby |
| U+1F477 | 👷 | \:construction\_worker: | Construction Worker |
| U+1F478 | 👸 | \:princess: | Princess |
| U+1F479 | 👹 | \:japanese\_ogre: | Japanese Ogre |
| U+1F47A | 👺 | \:japanese\_goblin: | Japanese Goblin |
| U+1F47B | 👻 | \:ghost: | Ghost |
| U+1F47C | 👼 | \:angel: | Baby Angel |
| U+1F47D | 👽 | \:alien: | Extraterrestrial Alien |
| U+1F47E | 👾 | \:space\_invader: | Alien Monster |
| U+1F47F | 👿 | \:imp: | Imp |
| U+1F480 | 💀 | \:skull: | Skull |
| U+1F481 | 💁 | \:information\_desk\_person: | Information Desk Person |
| U+1F482 | 💂 | \:guardsman: | Guardsman |
| U+1F483 | 💃 | \:dancer: | Dancer |
| U+1F484 | 💄 | \:lipstick: | Lipstick |
| U+1F485 | 💅 | \:nail\_care: | Nail Polish |
| U+1F486 | 💆 | \:massage: | Face Massage |
| U+1F487 | 💇 | \:haircut: | Haircut |
| U+1F488 | 💈 | \:barber: | Barber Pole |
| U+1F489 | 💉 | \:syringe: | Syringe |
| U+1F48A | 💊 | \:pill: | Pill |
| U+1F48B | 💋 | \:kiss: | Kiss Mark |
| U+1F48C | 💌 | \:love\_letter: | Love Letter |
| U+1F48D | 💍 | \:ring: | Ring |
| U+1F48E | 💎 | \:gem: | Gem Stone |
| U+1F48F | 💏 | \:couplekiss: | Kiss |
| U+1F490 | 💐 | \:bouquet: | Bouquet |
| U+1F491 | 💑 | \:couple\_with\_heart: | Couple With Heart |
| U+1F492 | 💒 | \:wedding: | Wedding |
| U+1F493 | 💓 | \:heartbeat: | Beating Heart |
| U+1F494 | 💔 | \:broken\_heart: | Broken Heart |
| U+1F495 | 💕 | \:two\_hearts: | Two Hearts |
| U+1F496 | 💖 | \:sparkling\_heart: | Sparkling Heart |
| U+1F497 | 💗 | \:heartpulse: | Growing Heart |
| U+1F498 | 💘 | \:cupid: | Heart With Arrow |
| U+1F499 | 💙 | \:blue\_heart: | Blue Heart |
| U+1F49A | 💚 | \:green\_heart: | Green Heart |
| U+1F49B | 💛 | \:yellow\_heart: | Yellow Heart |
| U+1F49C | 💜 | \:purple\_heart: | Purple Heart |
| U+1F49D | 💝 | \:gift\_heart: | Heart With Ribbon |
| U+1F49E | 💞 | \:revolving\_hearts: | Revolving Hearts |
| U+1F49F | 💟 | \:heart\_decoration: | Heart Decoration |
| U+1F4A0 | 💠 | \:diamond\_shape\_with\_a\_dot\_inside: | Diamond Shape With A Dot Inside |
| U+1F4A1 | 💡 | \:bulb: | Electric Light Bulb |
| U+1F4A2 | 💢 | \:anger: | Anger Symbol |
| U+1F4A3 | 💣 | \:bomb: | Bomb |
| U+1F4A4 | 💤 | \:zzz: | Sleeping Symbol |
| U+1F4A5 | 💥 | \:boom: | Collision Symbol |
| U+1F4A6 | 💦 | \:sweat\_drops: | Splashing Sweat Symbol |
| U+1F4A7 | 💧 | \:droplet: | Droplet |
| U+1F4A8 | 💨 | \:dash: | Dash Symbol |
| U+1F4A9 | 💩 | \:hankey: | Pile Of Poo |
| U+1F4AA | 💪 | \:muscle: | Flexed Biceps |
| U+1F4AB | 💫 | \:dizzy: | Dizzy Symbol |
| U+1F4AC | 💬 | \:speech\_balloon: | Speech Balloon |
| U+1F4AD | 💭 | \:thought\_balloon: | Thought Balloon |
| U+1F4AE | 💮 | \:white\_flower: | White Flower |
| U+1F4AF | 💯 | \:100: | Hundred Points Symbol |
| U+1F4B0 | 💰 | \:moneybag: | Money Bag |
| U+1F4B1 | 💱 | \:currency\_exchange: | Currency Exchange |
| U+1F4B2 | 💲 | \:heavy\_dollar\_sign: | Heavy Dollar Sign |
| U+1F4B3 | 💳 | \:credit\_card: | Credit Card |
| U+1F4B4 | 💴 | \:yen: | Banknote With Yen Sign |
| U+1F4B5 | 💵 | \:dollar: | Banknote With Dollar Sign |
| U+1F4B6 | 💶 | \:euro: | Banknote With Euro Sign |
| U+1F4B7 | 💷 | \:pound: | Banknote With Pound Sign |
| U+1F4B8 | 💸 | \:money\_with\_wings: | Money With Wings |
| U+1F4B9 | 💹 | \:chart: | Chart With Upwards Trend And Yen Sign |
| U+1F4BA | 💺 | \:seat: | Seat |
| U+1F4BB | 💻 | \:computer: | Personal Computer |
| U+1F4BC | 💼 | \:briefcase: | Briefcase |
| U+1F4BD | 💽 | \:minidisc: | Minidisc |
| U+1F4BE | 💾 | \:floppy\_disk: | Floppy Disk |
| U+1F4BF | 💿 | \:cd: | Optical Disc |
| U+1F4C0 | 📀 | \:dvd: | Dvd |
| U+1F4C1 | 📁 | \:file\_folder: | File Folder |
| U+1F4C2 | 📂 | \:open\_file\_folder: | Open File Folder |
| U+1F4C3 | 📃 | \:page\_with\_curl: | Page With Curl |
| U+1F4C4 | 📄 | \:page\_facing\_up: | Page Facing Up |
| U+1F4C5 | 📅 | \:date: | Calendar |
| U+1F4C6 | 📆 | \:calendar: | Tear-Off Calendar |
| U+1F4C7 | 📇 | \:card\_index: | Card Index |
| U+1F4C8 | 📈 | \:chart\_with\_upwards\_trend: | Chart With Upwards Trend |
| U+1F4C9 | 📉 | \:chart\_with\_downwards\_trend: | Chart With Downwards Trend |
| U+1F4CA | 📊 | \:bar\_chart: | Bar Chart |
| U+1F4CB | 📋 | \:clipboard: | Clipboard |
| U+1F4CC | 📌 | \:pushpin: | Pushpin |
| U+1F4CD | 📍 | \:round\_pushpin: | Round Pushpin |
| U+1F4CE | 📎 | \:paperclip: | Paperclip |
| U+1F4CF | 📏 | \:straight\_ruler: | Straight Ruler |
| U+1F4D0 | 📐 | \:triangular\_ruler: | Triangular Ruler |
| U+1F4D1 | 📑 | \:bookmark\_tabs: | Bookmark Tabs |
| U+1F4D2 | 📒 | \:ledger: | Ledger |
| U+1F4D3 | 📓 | \:notebook: | Notebook |
| U+1F4D4 | 📔 | \:notebook\_with\_decorative\_cover: | Notebook With Decorative Cover |
| U+1F4D5 | 📕 | \:closed\_book: | Closed Book |
| U+1F4D6 | 📖 | \:book: | Open Book |
| U+1F4D7 | 📗 | \:green\_book: | Green Book |
| U+1F4D8 | 📘 | \:blue\_book: | Blue Book |
| U+1F4D9 | 📙 | \:orange\_book: | Orange Book |
| U+1F4DA | 📚 | \:books: | Books |
| U+1F4DB | 📛 | \:name\_badge: | Name Badge |
| U+1F4DC | 📜 | \:scroll: | Scroll |
| U+1F4DD | 📝 | \:memo: | Memo |
| U+1F4DE | 📞 | \:telephone\_receiver: | Telephone Receiver |
| U+1F4DF | 📟 | \:pager: | Pager |
| U+1F4E0 | 📠 | \:fax: | Fax Machine |
| U+1F4E1 | 📡 | \:satellite:, \:satellite\_antenna: | Satellite Antenna |
| U+1F4E2 | 📢 | \:loudspeaker: | Public Address Loudspeaker |
| U+1F4E3 | 📣 | \:mega: | Cheering Megaphone |
| U+1F4E4 | 📤 | \:outbox\_tray: | Outbox Tray |
| U+1F4E5 | 📥 | \:inbox\_tray: | Inbox Tray |
| U+1F4E6 | 📦 | \:package: | Package |
| U+1F4E7 | 📧 | \:e-mail: | E-Mail Symbol |
| U+1F4E8 | 📨 | \:incoming\_envelope: | Incoming Envelope |
| U+1F4E9 | 📩 | \:envelope\_with\_arrow: | Envelope With Downwards Arrow Above |
| U+1F4EA | 📪 | \:mailbox\_closed: | Closed Mailbox With Lowered Flag |
| U+1F4EB | 📫 | \:mailbox: | Closed Mailbox With Raised Flag |
| U+1F4EC | 📬 | \:mailbox\_with\_mail: | Open Mailbox With Raised Flag |
| U+1F4ED | 📭 | \:mailbox\_with\_no\_mail: | Open Mailbox With Lowered Flag |
| U+1F4EE | 📮 | \:postbox: | Postbox |
| U+1F4EF | 📯 | \:postal\_horn: | Postal Horn |
| U+1F4F0 | 📰 | \:newspaper: | Newspaper |
| U+1F4F1 | 📱 | \:iphone: | Mobile Phone |
| U+1F4F2 | 📲 | \:calling: | Mobile Phone With Rightwards Arrow At Left |
| U+1F4F3 | 📳 | \:vibration\_mode: | Vibration Mode |
| U+1F4F4 | 📴 | \:mobile\_phone\_off: | Mobile Phone Off |
| U+1F4F5 | 📵 | \:no\_mobile\_phones: | No Mobile Phones |
| U+1F4F6 | 📶 | \:signal\_strength: | Antenna With Bars |
| U+1F4F7 | 📷 | \:camera: | Camera |
| U+1F4F8 | 📸 | \:camera\_with\_flash: | Camera With Flash |
| U+1F4F9 | 📹 | \:video\_camera: | Video Camera |
| U+1F4FA | 📺 | \:tv: | Television |
| U+1F4FB | 📻 | \:radio: | Radio |
| U+1F4FC | 📼 | \:vhs: | Videocassette |
| U+1F4FF | 📿 | \:prayer\_beads: | Prayer Beads |
| U+1F500 | 🔀 | \:twisted\_rightwards\_arrows: | Twisted Rightwards Arrows |
| U+1F501 | 🔁 | \:repeat: | Clockwise Rightwards And Leftwards Open Circle Arrows |
| U+1F502 | 🔂 | \:repeat\_one: | Clockwise Rightwards And Leftwards Open Circle Arrows With Circled One Overlay |
| U+1F503 | 🔃 | \:arrows\_clockwise: | Clockwise Downwards And Upwards Open Circle Arrows |
| U+1F504 | 🔄 | \:arrows\_counterclockwise: | Anticlockwise Downwards And Upwards Open Circle Arrows |
| U+1F505 | 🔅 | \:low\_brightness: | Low Brightness Symbol |
| U+1F506 | 🔆 | \:high\_brightness: | High Brightness Symbol |
| U+1F507 | 🔇 | \:mute: | Speaker With Cancellation Stroke |
| U+1F508 | 🔈 | \:speaker: | Speaker |
| U+1F509 | 🔉 | \:sound: | Speaker With One Sound Wave |
| U+1F50A | 🔊 | \:loud\_sound: | Speaker With Three Sound Waves |
| U+1F50B | 🔋 | \:battery: | Battery |
| U+1F50C | 🔌 | \:electric\_plug: | Electric Plug |
| U+1F50D | 🔍 | \:mag: | Left-Pointing Magnifying Glass |
| U+1F50E | 🔎 | \:mag\_right: | Right-Pointing Magnifying Glass |
| U+1F50F | 🔏 | \:lock\_with\_ink\_pen: | Lock With Ink Pen |
| U+1F510 | 🔐 | \:closed\_lock\_with\_key: | Closed Lock With Key |
| U+1F511 | 🔑 | \:key: | Key |
| U+1F512 | 🔒 | \:lock: | Lock |
| U+1F513 | 🔓 | \:unlock: | Open Lock |
| U+1F514 | 🔔 | \:bell: | Bell |
| U+1F515 | 🔕 | \:no\_bell: | Bell With Cancellation Stroke |
| U+1F516 | 🔖 | \:bookmark: | Bookmark |
| U+1F517 | 🔗 | \:link: | Link Symbol |
| U+1F518 | 🔘 | \:radio\_button: | Radio Button |
| U+1F519 | 🔙 | \:back: | Back With Leftwards Arrow Above |
| U+1F51A | 🔚 | \:end: | End With Leftwards Arrow Above |
| U+1F51B | 🔛 | \:on: | On With Exclamation Mark With Left Right Arrow Above |
| U+1F51C | 🔜 | \:soon: | Soon With Rightwards Arrow Above |
| U+1F51D | 🔝 | \:top: | Top With Upwards Arrow Above |
| U+1F51E | 🔞 | \:underage: | No One Under Eighteen Symbol |
| U+1F51F | 🔟 | \:keycap\_ten: | Keycap Ten |
| U+1F520 | 🔠 | \:capital\_abcd: | Input Symbol For Latin Capital Letters |
| U+1F521 | 🔡 | \:abcd: | Input Symbol For Latin Small Letters |
| U+1F522 | 🔢 | \:1234: | Input Symbol For Numbers |
| U+1F523 | 🔣 | \:symbols: | Input Symbol For Symbols |
| U+1F524 | 🔤 | \:abc: | Input Symbol For Latin Letters |
| U+1F525 | 🔥 | \:fire: | Fire |
| U+1F526 | 🔦 | \:flashlight: | Electric Torch |
| U+1F527 | 🔧 | \:wrench: | Wrench |
| U+1F528 | 🔨 | \:hammer: | Hammer |
| U+1F529 | 🔩 | \:nut\_and\_bolt: | Nut And Bolt |
| U+1F52A | 🔪 | \:hocho: | Hocho |
| U+1F52B | 🔫 | \:gun: | Pistol |
| U+1F52C | 🔬 | \:microscope: | Microscope |
| U+1F52D | 🔭 | \:telescope: | Telescope |
| U+1F52E | 🔮 | \:crystal\_ball: | Crystal Ball |
| U+1F52F | 🔯 | \:six\_pointed\_star: | Six Pointed Star With Middle Dot |
| U+1F530 | 🔰 | \:beginner: | Japanese Symbol For Beginner |
| U+1F531 | 🔱 | \:trident: | Trident Emblem |
| U+1F532 | 🔲 | \:black\_square\_button: | Black Square Button |
| U+1F533 | 🔳 | \:white\_square\_button: | White Square Button |
| U+1F534 | 🔴 | \:red\_circle: | Large Red Circle |
| U+1F535 | 🔵 | \:large\_blue\_circle: | Large Blue Circle |
| U+1F536 | 🔶 | \:large\_orange\_diamond: | Large Orange Diamond |
| U+1F537 | 🔷 | \:large\_blue\_diamond: | Large Blue Diamond |
| U+1F538 | 🔸 | \:small\_orange\_diamond: | Small Orange Diamond |
| U+1F539 | 🔹 | \:small\_blue\_diamond: | Small Blue Diamond |
| U+1F53A | 🔺 | \:small\_red\_triangle: | Up-Pointing Red Triangle |
| U+1F53B | 🔻 | \:small\_red\_triangle\_down: | Down-Pointing Red Triangle |
| U+1F53C | 🔼 | \:arrow\_up\_small: | Up-Pointing Small Red Triangle |
| U+1F53D | 🔽 | \:arrow\_down\_small: | Down-Pointing Small Red Triangle |
| U+1F54B | 🕋 | \:kaaba: | Kaaba |
| U+1F54C | 🕌 | \:mosque: | Mosque |
| U+1F54D | 🕍 | \:synagogue: | Synagogue |
| U+1F54E | 🕎 | \:menorah\_with\_nine\_branches: | Menorah With Nine Branches |
| U+1F550 | 🕐 | \:clock1: | Clock Face One Oclock |
| U+1F551 | 🕑 | \:clock2: | Clock Face Two Oclock |
| U+1F552 | 🕒 | \:clock3: | Clock Face Three Oclock |
| U+1F553 | 🕓 | \:clock4: | Clock Face Four Oclock |
| U+1F554 | 🕔 | \:clock5: | Clock Face Five Oclock |
| U+1F555 | 🕕 | \:clock6: | Clock Face Six Oclock |
| U+1F556 | 🕖 | \:clock7: | Clock Face Seven Oclock |
| U+1F557 | 🕗 | \:clock8: | Clock Face Eight Oclock |
| U+1F558 | 🕘 | \:clock9: | Clock Face Nine Oclock |
| U+1F559 | 🕙 | \:clock10: | Clock Face Ten Oclock |
| U+1F55A | 🕚 | \:clock11: | Clock Face Eleven Oclock |
| U+1F55B | 🕛 | \:clock12: | Clock Face Twelve Oclock |
| U+1F55C | 🕜 | \:clock130: | Clock Face One-Thirty |
| U+1F55D | 🕝 | \:clock230: | Clock Face Two-Thirty |
| U+1F55E | 🕞 | \:clock330: | Clock Face Three-Thirty |
| U+1F55F | 🕟 | \:clock430: | Clock Face Four-Thirty |
| U+1F560 | 🕠 | \:clock530: | Clock Face Five-Thirty |
| U+1F561 | 🕡 | \:clock630: | Clock Face Six-Thirty |
| U+1F562 | 🕢 | \:clock730: | Clock Face Seven-Thirty |
| U+1F563 | 🕣 | \:clock830: | Clock Face Eight-Thirty |
| U+1F564 | 🕤 | \:clock930: | Clock Face Nine-Thirty |
| U+1F565 | 🕥 | \:clock1030: | Clock Face Ten-Thirty |
| U+1F566 | 🕦 | \:clock1130: | Clock Face Eleven-Thirty |
| U+1F567 | 🕧 | \:clock1230: | Clock Face Twelve-Thirty |
| U+1F57A | 🕺 | \:man\_dancing: | Man Dancing |
| U+1F595 | 🖕 | \:middle\_finger: | Reversed Hand With Middle Finger Extended |
| U+1F596 | 🖖 | \:spock-hand: | Raised Hand With Part Between Middle And Ring Fingers |
| U+1F5A4 | 🖤 | \:black\_heart: | Black Heart |
| U+1F5FB | 🗻 | \:mount\_fuji: | Mount Fuji |
| U+1F5FC | 🗼 | \:tokyo\_tower: | Tokyo Tower |
| U+1F5FD | 🗽 | \:statue\_of\_liberty: | Statue Of Liberty |
| U+1F5FE | 🗾 | \:japan: | Silhouette Of Japan |
| U+1F5FF | 🗿 | \:moyai: | Moyai |
| U+1F600 | 😀 | \:grinning: | Grinning Face |
| U+1F601 | 😁 | \:grin: | Grinning Face With Smiling Eyes |
| U+1F602 | 😂 | \:joy: | Face With Tears Of Joy |
| U+1F603 | 😃 | \:smiley: | Smiling Face With Open Mouth |
| U+1F604 | 😄 | \:smile: | Smiling Face With Open Mouth And Smiling Eyes |
| U+1F605 | 😅 | \:sweat\_smile: | Smiling Face With Open Mouth And Cold Sweat |
| U+1F606 | 😆 | \:laughing: | Smiling Face With Open Mouth And Tightly-Closed Eyes |
| U+1F607 | 😇 | \:innocent: | Smiling Face With Halo |
| U+1F608 | 😈 | \:smiling\_imp: | Smiling Face With Horns |
| U+1F609 | 😉 | \:wink: | Winking Face |
| U+1F60A | 😊 | \:blush: | Smiling Face With Smiling Eyes |
| U+1F60B | 😋 | \:yum: | Face Savouring Delicious Food |
| U+1F60C | 😌 | \:relieved: | Relieved Face |
| U+1F60D | 😍 | \:heart\_eyes: | Smiling Face With Heart-Shaped Eyes |
| U+1F60E | 😎 | \:sunglasses: | Smiling Face With Sunglasses |
| U+1F60F | 😏 | \:smirk: | Smirking Face |
| U+1F610 | 😐 | \:neutral\_face: | Neutral Face |
| U+1F611 | 😑 | \:expressionless: | Expressionless Face |
| U+1F612 | 😒 | \:unamused: | Unamused Face |
| U+1F613 | 😓 | \:sweat: | Face With Cold Sweat |
| U+1F614 | 😔 | \:pensive: | Pensive Face |
| U+1F615 | 😕 | \:confused: | Confused Face |
| U+1F616 | 😖 | \:confounded: | Confounded Face |
| U+1F617 | 😗 | \:kissing: | Kissing Face |
| U+1F618 | 😘 | \:kissing\_heart: | Face Throwing A Kiss |
| U+1F619 | 😙 | \:kissing\_smiling\_eyes: | Kissing Face With Smiling Eyes |
| U+1F61A | 😚 | \:kissing\_closed\_eyes: | Kissing Face With Closed Eyes |
| U+1F61B | 😛 | \:stuck\_out\_tongue: | Face With Stuck-Out Tongue |
| U+1F61C | 😜 | \:stuck\_out\_tongue\_winking\_eye: | Face With Stuck-Out Tongue And Winking Eye |
| U+1F61D | 😝 | \:stuck\_out\_tongue\_closed\_eyes: | Face With Stuck-Out Tongue And Tightly-Closed Eyes |
| U+1F61E | 😞 | \:disappointed: | Disappointed Face |
| U+1F61F | 😟 | \:worried: | Worried Face |
| U+1F620 | 😠 | \:angry: | Angry Face |
| U+1F621 | 😡 | \:rage: | Pouting Face |
| U+1F622 | 😢 | \:cry: | Crying Face |
| U+1F623 | 😣 | \:persevere: | Persevering Face |
| U+1F624 | 😤 | \:triumph: | Face With Look Of Triumph |
| U+1F625 | 😥 | \:disappointed\_relieved: | Disappointed But Relieved Face |
| U+1F626 | 😦 | \:frowning: | Frowning Face With Open Mouth |
| U+1F627 | 😧 | \:anguished: | Anguished Face |
| U+1F628 | 😨 | \:fearful: | Fearful Face |
| U+1F629 | 😩 | \:weary: | Weary Face |
| U+1F62A | 😪 | \:sleepy: | Sleepy Face |
| U+1F62B | 😫 | \:tired\_face: | Tired Face |
| U+1F62C | 😬 | \:grimacing: | Grimacing Face |
| U+1F62D | 😭 | \:sob: | Loudly Crying Face |
| U+1F62E | 😮 | \:open\_mouth: | Face With Open Mouth |
| U+1F62F | 😯 | \:hushed: | Hushed Face |
| U+1F630 | 😰 | \:cold\_sweat: | Face With Open Mouth And Cold Sweat |
| U+1F631 | 😱 | \:scream: | Face Screaming In Fear |
| U+1F632 | 😲 | \:astonished: | Astonished Face |
| U+1F633 | 😳 | \:flushed: | Flushed Face |
| U+1F634 | 😴 | \:sleeping: | Sleeping Face |
| U+1F635 | 😵 | \:dizzy\_face: | Dizzy Face |
| U+1F636 | 😶 | \:no\_mouth: | Face Without Mouth |
| U+1F637 | 😷 | \:mask: | Face With Medical Mask |
| U+1F638 | 😸 | \:smile\_cat: | Grinning Cat Face With Smiling Eyes |
| U+1F639 | 😹 | \:joy\_cat: | Cat Face With Tears Of Joy |
| U+1F63A | 😺 | \:smiley\_cat: | Smiling Cat Face With Open Mouth |
| U+1F63B | 😻 | \:heart\_eyes\_cat: | Smiling Cat Face With Heart-Shaped Eyes |
| U+1F63C | 😼 | \:smirk\_cat: | Cat Face With Wry Smile |
| U+1F63D | 😽 | \:kissing\_cat: | Kissing Cat Face With Closed Eyes |
| U+1F63E | 😾 | \:pouting\_cat: | Pouting Cat Face |
| U+1F63F | 😿 | \:crying\_cat\_face: | Crying Cat Face |
| U+1F640 | 🙀 | \:scream\_cat: | Weary Cat Face |
| U+1F641 | 🙁 | \:slightly\_frowning\_face: | Slightly Frowning Face |
| U+1F642 | 🙂 | \:slightly\_smiling\_face: | Slightly Smiling Face |
| U+1F643 | 🙃 | \:upside\_down\_face: | Upside-Down Face |
| U+1F644 | 🙄 | \:face\_with\_rolling\_eyes: | Face With Rolling Eyes |
| U+1F645 | 🙅 | \:no\_good: | Face With No Good Gesture |
| U+1F646 | 🙆 | \:ok\_woman: | Face With Ok Gesture |
| U+1F647 | 🙇 | \:bow: | Person Bowing Deeply |
| U+1F648 | 🙈 | \:see\_no\_evil: | See-No-Evil Monkey |
| U+1F649 | 🙉 | \:hear\_no\_evil: | Hear-No-Evil Monkey |
| U+1F64A | 🙊 | \:speak\_no\_evil: | Speak-No-Evil Monkey |
| U+1F64B | 🙋 | \:raising\_hand: | Happy Person Raising One Hand |
| U+1F64C | 🙌 | \:raised\_hands: | Person Raising Both Hands In Celebration |
| U+1F64D | 🙍 | \:person\_frowning: | Person Frowning |
| U+1F64E | 🙎 | \:person\_with\_pouting\_face: | Person With Pouting Face |
| U+1F64F | 🙏 | \:pray: | Person With Folded Hands |
| U+1F680 | 🚀 | \:rocket: | Rocket |
| U+1F681 | 🚁 | \:helicopter: | Helicopter |
| U+1F682 | 🚂 | \:steam\_locomotive: | Steam Locomotive |
| U+1F683 | 🚃 | \:railway\_car: | Railway Car |
| U+1F684 | 🚄 | \:bullettrain\_side: | High-Speed Train |
| U+1F685 | 🚅 | \:bullettrain\_front: | High-Speed Train With Bullet Nose |
| U+1F686 | 🚆 | \:train2: | Train |
| U+1F687 | 🚇 | \:metro: | Metro |
| U+1F688 | 🚈 | \:light\_rail: | Light Rail |
| U+1F689 | 🚉 | \:station: | Station |
| U+1F68A | 🚊 | \:tram: | Tram |
| U+1F68B | 🚋 | \:train: | Tram Car |
| U+1F68C | 🚌 | \:bus: | Bus |
| U+1F68D | 🚍 | \:oncoming\_bus: | Oncoming Bus |
| U+1F68E | 🚎 | \:trolleybus: | Trolleybus |
| U+1F68F | 🚏 | \:busstop: | Bus Stop |
| U+1F690 | 🚐 | \:minibus: | Minibus |
| U+1F691 | 🚑 | \:ambulance: | Ambulance |
| U+1F692 | 🚒 | \:fire\_engine: | Fire Engine |
| U+1F693 | 🚓 | \:police\_car: | Police Car |
| U+1F694 | 🚔 | \:oncoming\_police\_car: | Oncoming Police Car |
| U+1F695 | 🚕 | \:taxi: | Taxi |
| U+1F696 | 🚖 | \:oncoming\_taxi: | Oncoming Taxi |
| U+1F697 | 🚗 | \:car: | Automobile |
| U+1F698 | 🚘 | \:oncoming\_automobile: | Oncoming Automobile |
| U+1F699 | 🚙 | \:blue\_car: | Recreational Vehicle |
| U+1F69A | 🚚 | \:truck: | Delivery Truck |
| U+1F69B | 🚛 | \:articulated\_lorry: | Articulated Lorry |
| U+1F69C | 🚜 | \:tractor: | Tractor |
| U+1F69D | 🚝 | \:monorail: | Monorail |
| U+1F69E | 🚞 | \:mountain\_railway: | Mountain Railway |
| U+1F69F | 🚟 | \:suspension\_railway: | Suspension Railway |
| U+1F6A0 | 🚠 | \:mountain\_cableway: | Mountain Cableway |
| U+1F6A1 | 🚡 | \:aerial\_tramway: | Aerial Tramway |
| U+1F6A2 | 🚢 | \:ship: | Ship |
| U+1F6A3 | 🚣 | \:rowboat: | Rowboat |
| U+1F6A4 | 🚤 | \:speedboat: | Speedboat |
| U+1F6A5 | 🚥 | \:traffic\_light: | Horizontal Traffic Light |
| U+1F6A6 | 🚦 | \:vertical\_traffic\_light: | Vertical Traffic Light |
| U+1F6A7 | 🚧 | \:construction: | Construction Sign |
| U+1F6A8 | 🚨 | \:rotating\_light: | Police Cars Revolving Light |
| U+1F6A9 | 🚩 | \:triangular\_flag\_on\_post: | Triangular Flag On Post |
| U+1F6AA | 🚪 | \:door: | Door |
| U+1F6AB | 🚫 | \:no\_entry\_sign: | No Entry Sign |
| U+1F6AC | 🚬 | \:smoking: | Smoking Symbol |
| U+1F6AD | 🚭 | \:no\_smoking: | No Smoking Symbol |
| U+1F6AE | 🚮 | \:put\_litter\_in\_its\_place: | Put Litter In Its Place Symbol |
| U+1F6AF | 🚯 | \:do\_not\_litter: | Do Not Litter Symbol |
| U+1F6B0 | 🚰 | \:potable\_water: | Potable Water Symbol |
| U+1F6B1 | 🚱 | \:non-potable\_water: | Non-Potable Water Symbol |
| U+1F6B2 | 🚲 | \:bike: | Bicycle |
| U+1F6B3 | 🚳 | \:no\_bicycles: | No Bicycles |
| U+1F6B4 | 🚴 | \:bicyclist: | Bicyclist |
| U+1F6B5 | 🚵 | \:mountain\_bicyclist: | Mountain Bicyclist |
| U+1F6B6 | 🚶 | \:walking: | Pedestrian |
| U+1F6B7 | 🚷 | \:no\_pedestrians: | No Pedestrians |
| U+1F6B8 | 🚸 | \:children\_crossing: | Children Crossing |
| U+1F6B9 | 🚹 | \:mens: | Mens Symbol |
| U+1F6BA | 🚺 | \:womens: | Womens Symbol |
| U+1F6BB | 🚻 | \:restroom: | Restroom |
| U+1F6BC | 🚼 | \:baby\_symbol: | Baby Symbol |
| U+1F6BD | 🚽 | \:toilet: | Toilet |
| U+1F6BE | 🚾 | \:wc: | Water Closet |
| U+1F6BF | 🚿 | \:shower: | Shower |
| U+1F6C0 | 🛀 | \:bath: | Bath |
| U+1F6C1 | 🛁 | \:bathtub: | Bathtub |
| U+1F6C2 | 🛂 | \:passport\_control: | Passport Control |
| U+1F6C3 | 🛃 | \:customs: | Customs |
| U+1F6C4 | 🛄 | \:baggage\_claim: | Baggage Claim |
| U+1F6C5 | 🛅 | \:left\_luggage: | Left Luggage |
| U+1F6CC | 🛌 | \:sleeping\_accommodation: | Sleeping Accommodation |
| U+1F6D0 | 🛐 | \:place\_of\_worship: | Place Of Worship |
| U+1F6D1 | 🛑 | \:octagonal\_sign: | Octagonal Sign |
| U+1F6D2 | 🛒 | \:shopping\_trolley: | Shopping Trolley |
| U+1F6D5 | 🛕 | \:hindu\_temple: | Hindu Temple |
| U+1F6D6 | 🛖 | \:hut: | Hut |
| U+1F6D7 | 🛗 | \:elevator: | Elevator |
| U+1F6EB | 🛫 | \:airplane\_departure: | Airplane Departure |
| U+1F6EC | 🛬 | \:airplane\_arriving: | Airplane Arriving |
| U+1F6F4 | 🛴 | \:scooter: | Scooter |
| U+1F6F5 | 🛵 | \:motor\_scooter: | Motor Scooter |
| U+1F6F6 | 🛶 | \:canoe: | Canoe |
| U+1F6F7 | 🛷 | \:sled: | Sled |
| U+1F6F8 | 🛸 | \:flying\_saucer: | Flying Saucer |
| U+1F6F9 | 🛹 | \:skateboard: | Skateboard |
| U+1F6FA | 🛺 | \:auto\_rickshaw: | Auto Rickshaw |
| U+1F6FB | 🛻 | \:pickup\_truck: | Pickup Truck |
| U+1F6FC | 🛼 | \:roller\_skate: | Roller Skate |
| U+1F7E0 | 🟠 | \:large\_orange\_circle: | Large Orange Circle |
| U+1F7E1 | 🟡 | \:large\_yellow\_circle: | Large Yellow Circle |
| U+1F7E2 | 🟢 | \:large\_green\_circle: | Large Green Circle |
| U+1F7E3 | 🟣 | \:large\_purple\_circle: | Large Purple Circle |
| U+1F7E4 | 🟤 | \:large\_brown\_circle: | Large Brown Circle |
| U+1F7E5 | 🟥 | \:large\_red\_square: | Large Red Square |
| U+1F7E6 | 🟦 | \:large\_blue\_square: | Large Blue Square |
| U+1F7E7 | 🟧 | \:large\_orange\_square: | Large Orange Square |
| U+1F7E8 | 🟨 | \:large\_yellow\_square: | Large Yellow Square |
| U+1F7E9 | 🟩 | \:large\_green\_square: | Large Green Square |
| U+1F7EA | 🟪 | \:large\_purple\_square: | Large Purple Square |
| U+1F7EB | 🟫 | \:large\_brown\_square: | Large Brown Square |
| U+1F90C | 🤌 | \:pinched\_fingers: | Pinched Fingers |
| U+1F90D | 🤍 | \:white\_heart: | White Heart |
| U+1F90E | 🤎 | \:brown\_heart: | Brown Heart |
| U+1F90F | 🤏 | \:pinching\_hand: | Pinching Hand |
| U+1F910 | 🤐 | \:zipper\_mouth\_face: | Zipper-Mouth Face |
| U+1F911 | 🤑 | \:money\_mouth\_face: | Money-Mouth Face |
| U+1F912 | 🤒 | \:face\_with\_thermometer: | Face With Thermometer |
| U+1F913 | 🤓 | \:nerd\_face: | Nerd Face |
| U+1F914 | 🤔 | \:thinking\_face: | Thinking Face |
| U+1F915 | 🤕 | \:face\_with\_head\_bandage: | Face With Head-Bandage |
| U+1F916 | 🤖 | \:robot\_face: | Robot Face |
| U+1F917 | 🤗 | \:hugging\_face: | Hugging Face |
| U+1F918 | 🤘 | \:the\_horns: | Sign Of The Horns |
| U+1F919 | 🤙 | \:call\_me\_hand: | Call Me Hand |
| U+1F91A | 🤚 | \:raised\_back\_of\_hand: | Raised Back Of Hand |
| U+1F91B | 🤛 | \:left-facing\_fist: | Left-Facing Fist |
| U+1F91C | 🤜 | \:right-facing\_fist: | Right-Facing Fist |
| U+1F91D | 🤝 | \:handshake: | Handshake |
| U+1F91E | 🤞 | \:crossed\_fingers: | Hand With Index And Middle Fingers Crossed |
| U+1F91F | 🤟 | \:i\_love\_you\_hand\_sign: | I Love You Hand Sign |
| U+1F920 | 🤠 | \:face\_with\_cowboy\_hat: | Face With Cowboy Hat |
| U+1F921 | 🤡 | \:clown\_face: | Clown Face |
| U+1F922 | 🤢 | \:nauseated\_face: | Nauseated Face |
| U+1F923 | 🤣 | \:rolling\_on\_the\_floor\_laughing: | Rolling On The Floor Laughing |
| U+1F924 | 🤤 | \:drooling\_face: | Drooling Face |
| U+1F925 | 🤥 | \:lying\_face: | Lying Face |
| U+1F926 | 🤦 | \:face\_palm: | Face Palm |
| U+1F927 | 🤧 | \:sneezing\_face: | Sneezing Face |
| U+1F928 | 🤨 | \:face\_with\_raised\_eyebrow: | Face With One Eyebrow Raised |
| U+1F929 | 🤩 | \:star-struck: | Grinning Face With Star Eyes |
| U+1F92A | 🤪 | \:zany\_face: | Grinning Face With One Large And One Small Eye |
| U+1F92B | 🤫 | \:shushing\_face: | Face With Finger Covering Closed Lips |
| U+1F92C | 🤬 | \:face\_with\_symbols\_on\_mouth: | Serious Face With Symbols Covering Mouth |
| U+1F92D | 🤭 | \:face\_with\_hand\_over\_mouth: | Smiling Face With Smiling Eyes And Hand Covering Mouth |
| U+1F92E | 🤮 | \:face\_vomiting: | Face With Open Mouth Vomiting |
| U+1F92F | 🤯 | \:exploding\_head: | Shocked Face With Exploding Head |
| U+1F930 | 🤰 | \:pregnant\_woman: | Pregnant Woman |
| U+1F931 | 🤱 | \:breast-feeding: | Breast-Feeding |
| U+1F932 | 🤲 | \:palms\_up\_together: | Palms Up Together |
| U+1F933 | 🤳 | \:selfie: | Selfie |
| U+1F934 | 🤴 | \:prince: | Prince |
| U+1F935 | 🤵 | \:person\_in\_tuxedo: | Man In Tuxedo |
| U+1F936 | 🤶 | \:mrs\_claus: | Mother Christmas |
| U+1F937 | 🤷 | \:shrug: | Shrug |
| U+1F938 | 🤸 | \:person\_doing\_cartwheel: | Person Doing Cartwheel |
| U+1F939 | 🤹 | \:juggling: | Juggling |
| U+1F93A | 🤺 | \:fencer: | Fencer |
| U+1F93C | 🤼 | \:wrestlers: | Wrestlers |
| U+1F93D | 🤽 | \:water\_polo: | Water Polo |
| U+1F93E | 🤾 | \:handball: | Handball |
| U+1F93F | 🤿 | \:diving\_mask: | Diving Mask |
| U+1F940 | 🥀 | \:wilted\_flower: | Wilted Flower |
| U+1F941 | 🥁 | \:drum\_with\_drumsticks: | Drum With Drumsticks |
| U+1F942 | 🥂 | \:clinking\_glasses: | Clinking Glasses |
| U+1F943 | 🥃 | \:tumbler\_glass: | Tumbler Glass |
| U+1F944 | 🥄 | \:spoon: | Spoon |
| U+1F945 | 🥅 | \:goal\_net: | Goal Net |
| U+1F947 | 🥇 | \:first\_place\_medal: | First Place Medal |
| U+1F948 | 🥈 | \:second\_place\_medal: | Second Place Medal |
| U+1F949 | 🥉 | \:third\_place\_medal: | Third Place Medal |
| U+1F94A | 🥊 | \:boxing\_glove: | Boxing Glove |
| U+1F94B | 🥋 | \:martial\_arts\_uniform: | Martial Arts Uniform |
| U+1F94C | 🥌 | \:curling\_stone: | Curling Stone |
| U+1F94D | 🥍 | \:lacrosse: | Lacrosse Stick And Ball |
| U+1F94E | 🥎 | \:softball: | Softball |
| U+1F94F | 🥏 | \:flying\_disc: | Flying Disc |
| U+1F950 | 🥐 | \:croissant: | Croissant |
| U+1F951 | 🥑 | \:avocado: | Avocado |
| U+1F952 | 🥒 | \:cucumber: | Cucumber |
| U+1F953 | 🥓 | \:bacon: | Bacon |
| U+1F954 | 🥔 | \:potato: | Potato |
| U+1F955 | 🥕 | \:carrot: | Carrot |
| U+1F956 | 🥖 | \:baguette\_bread: | Baguette Bread |
| U+1F957 | 🥗 | \:green\_salad: | Green Salad |
| U+1F958 | 🥘 | \:shallow\_pan\_of\_food: | Shallow Pan Of Food |
| U+1F959 | 🥙 | \:stuffed\_flatbread: | Stuffed Flatbread |
| U+1F95A | 🥚 | \:egg: | Egg |
| U+1F95B | 🥛 | \:glass\_of\_milk: | Glass Of Milk |
| U+1F95C | 🥜 | \:peanuts: | Peanuts |
| U+1F95D | 🥝 | \:kiwifruit: | Kiwifruit |
| U+1F95E | 🥞 | \:pancakes: | Pancakes |
| U+1F95F | 🥟 | \:dumpling: | Dumpling |
| U+1F960 | 🥠 | \:fortune\_cookie: | Fortune Cookie |
| U+1F961 | 🥡 | \:takeout\_box: | Takeout Box |
| U+1F962 | 🥢 | \:chopsticks: | Chopsticks |
| U+1F963 | 🥣 | \:bowl\_with\_spoon: | Bowl With Spoon |
| U+1F964 | 🥤 | \:cup\_with\_straw: | Cup With Straw |
| U+1F965 | 🥥 | \:coconut: | Coconut |
| U+1F966 | 🥦 | \:broccoli: | Broccoli |
| U+1F967 | 🥧 | \:pie: | Pie |
| U+1F968 | 🥨 | \:pretzel: | Pretzel |
| U+1F969 | 🥩 | \:cut\_of\_meat: | Cut Of Meat |
| U+1F96A | 🥪 | \:sandwich: | Sandwich |
| U+1F96B | 🥫 | \:canned\_food: | Canned Food |
| U+1F96C | 🥬 | \:leafy\_green: | Leafy Green |
| U+1F96D | 🥭 | \:mango: | Mango |
| U+1F96E | 🥮 | \:moon\_cake: | Moon Cake |
| U+1F96F | 🥯 | \:bagel: | Bagel |
| U+1F970 | 🥰 | \:smiling\_face\_with\_3\_hearts: | Smiling Face With Smiling Eyes And Three Hearts |
| U+1F971 | 🥱 | \:yawning\_face: | Yawning Face |
| U+1F972 | 🥲 | \:smiling\_face\_with\_tear: | Smiling Face With Tear |
| U+1F973 | 🥳 | \:partying\_face: | Face With Party Horn And Party Hat |
| U+1F974 | 🥴 | \:woozy\_face: | Face With Uneven Eyes And Wavy Mouth |
| U+1F975 | 🥵 | \:hot\_face: | Overheated Face |
| U+1F976 | 🥶 | \:cold\_face: | Freezing Face |
| U+1F977 | 🥷 | \:ninja: | Ninja |
| U+1F978 | 🥸 | \:disguised\_face: | Disguised Face |
| U+1F97A | 🥺 | \:pleading\_face: | Face With Pleading Eyes |
| U+1F97B | 🥻 | \:sari: | Sari |
| U+1F97C | 🥼 | \:lab\_coat: | Lab Coat |
| U+1F97D | 🥽 | \:goggles: | Goggles |
| U+1F97E | 🥾 | \:hiking\_boot: | Hiking Boot |
| U+1F97F | 🥿 | \:womans\_flat\_shoe: | Flat Shoe |
| U+1F980 | 🦀 | \:crab: | Crab |
| U+1F981 | 🦁 | \:lion\_face: | Lion Face |
| U+1F982 | 🦂 | \:scorpion: | Scorpion |
| U+1F983 | 🦃 | \:turkey: | Turkey |
| U+1F984 | 🦄 | \:unicorn\_face: | Unicorn Face |
| U+1F985 | 🦅 | \:eagle: | Eagle |
| U+1F986 | 🦆 | \:duck: | Duck |
| U+1F987 | 🦇 | \:bat: | Bat |
| U+1F988 | 🦈 | \:shark: | Shark |
| U+1F989 | 🦉 | \:owl: | Owl |
| U+1F98A | 🦊 | \:fox\_face: | Fox Face |
| U+1F98B | 🦋 | \:butterfly: | Butterfly |
| U+1F98C | 🦌 | \:deer: | Deer |
| U+1F98D | 🦍 | \:gorilla: | Gorilla |
| U+1F98E | 🦎 | \:lizard: | Lizard |
| U+1F98F | 🦏 | \:rhinoceros: | Rhinoceros |
| U+1F990 | 🦐 | \:shrimp: | Shrimp |
| U+1F991 | 🦑 | \:squid: | Squid |
| U+1F992 | 🦒 | \:giraffe\_face: | Giraffe Face |
| U+1F993 | 🦓 | \:zebra\_face: | Zebra Face |
| U+1F994 | 🦔 | \:hedgehog: | Hedgehog |
| U+1F995 | 🦕 | \:sauropod: | Sauropod |
| U+1F996 | 🦖 | \:t-rex: | T-Rex |
| U+1F997 | 🦗 | \:cricket: | Cricket |
| U+1F998 | 🦘 | \:kangaroo: | Kangaroo |
| U+1F999 | 🦙 | \:llama: | Llama |
| U+1F99A | 🦚 | \:peacock: | Peacock |
| U+1F99B | 🦛 | \:hippopotamus: | Hippopotamus |
| U+1F99C | 🦜 | \:parrot: | Parrot |
| U+1F99D | 🦝 | \:raccoon: | Raccoon |
| U+1F99E | 🦞 | \:lobster: | Lobster |
| U+1F99F | 🦟 | \:mosquito: | Mosquito |
| U+1F9A0 | 🦠 | \:microbe: | Microbe |
| U+1F9A1 | 🦡 | \:badger: | Badger |
| U+1F9A2 | 🦢 | \:swan: | Swan |
| U+1F9A3 | 🦣 | \:mammoth: | Mammoth |
| U+1F9A4 | 🦤 | \:dodo: | Dodo |
| U+1F9A5 | 🦥 | \:sloth: | Sloth |
| U+1F9A6 | 🦦 | \:otter: | Otter |
| U+1F9A7 | 🦧 | \:orangutan: | Orangutan |
| U+1F9A8 | 🦨 | \:skunk: | Skunk |
| U+1F9A9 | 🦩 | \:flamingo: | Flamingo |
| U+1F9AA | 🦪 | \:oyster: | Oyster |
| U+1F9AB | 🦫 | \:beaver: | Beaver |
| U+1F9AC | 🦬 | \:bison: | Bison |
| U+1F9AD | 🦭 | \:seal: | Seal |
| U+1F9AE | 🦮 | \:guide\_dog: | Guide Dog |
| U+1F9AF | 🦯 | \:probing\_cane: | Probing Cane |
| U+1F9B4 | 🦴 | \:bone: | Bone |
| U+1F9B5 | 🦵 | \:leg: | Leg |
| U+1F9B6 | 🦶 | \:foot: | Foot |
| U+1F9B7 | 🦷 | \:tooth: | Tooth |
| U+1F9B8 | 🦸 | \:superhero: | Superhero |
| U+1F9B9 | 🦹 | \:supervillain: | Supervillain |
| U+1F9BA | 🦺 | \:safety\_vest: | Safety Vest |
| U+1F9BB | 🦻 | \:ear\_with\_hearing\_aid: | Ear With Hearing Aid |
| U+1F9BC | 🦼 | \:motorized\_wheelchair: | Motorized Wheelchair |
| U+1F9BD | 🦽 | \:manual\_wheelchair: | Manual Wheelchair |
| U+1F9BE | 🦾 | \:mechanical\_arm: | Mechanical Arm |
| U+1F9BF | 🦿 | \:mechanical\_leg: | Mechanical Leg |
| U+1F9C0 | 🧀 | \:cheese\_wedge: | Cheese Wedge |
| U+1F9C1 | 🧁 | \:cupcake: | Cupcake |
| U+1F9C2 | 🧂 | \:salt: | Salt Shaker |
| U+1F9C3 | 🧃 | \:beverage\_box: | Beverage Box |
| U+1F9C4 | 🧄 | \:garlic: | Garlic |
| U+1F9C5 | 🧅 | \:onion: | Onion |
| U+1F9C6 | 🧆 | \:falafel: | Falafel |
| U+1F9C7 | 🧇 | \:waffle: | Waffle |
| U+1F9C8 | 🧈 | \:butter: | Butter |
| U+1F9C9 | 🧉 | \:mate\_drink: | Mate Drink |
| U+1F9CA | 🧊 | \:ice\_cube: | Ice Cube |
| U+1F9CB | 🧋 | \:bubble\_tea: | Bubble Tea |
| U+1F9CD | 🧍 | \:standing\_person: | Standing Person |
| U+1F9CE | 🧎 | \:kneeling\_person: | Kneeling Person |
| U+1F9CF | 🧏 | \:deaf\_person: | Deaf Person |
| U+1F9D0 | 🧐 | \:face\_with\_monocle: | Face With Monocle |
| U+1F9D1 | 🧑 | \:adult: | Adult |
| U+1F9D2 | 🧒 | \:child: | Child |
| U+1F9D3 | 🧓 | \:older\_adult: | Older Adult |
| U+1F9D4 | 🧔 | \:bearded\_person: | Bearded Person |
| U+1F9D5 | 🧕 | \:person\_with\_headscarf: | Person With Headscarf |
| U+1F9D6 | 🧖 | \:person\_in\_steamy\_room: | Person In Steamy Room |
| U+1F9D7 | 🧗 | \:person\_climbing: | Person Climbing |
| U+1F9D8 | 🧘 | \:person\_in\_lotus\_position: | Person In Lotus Position |
| U+1F9D9 | 🧙 | \:mage: | Mage |
| U+1F9DA | 🧚 | \:fairy: | Fairy |
| U+1F9DB | 🧛 | \:vampire: | Vampire |
| U+1F9DC | 🧜 | \:merperson: | Merperson |
| U+1F9DD | 🧝 | \:elf: | Elf |
| U+1F9DE | 🧞 | \:genie: | Genie |
| U+1F9DF | 🧟 | \:zombie: | Zombie |
| U+1F9E0 | 🧠 | \:brain: | Brain |
| U+1F9E1 | 🧡 | \:orange\_heart: | Orange Heart |
| U+1F9E2 | 🧢 | \:billed\_cap: | Billed Cap |
| U+1F9E3 | 🧣 | \:scarf: | Scarf |
| U+1F9E4 | 🧤 | \:gloves: | Gloves |
| U+1F9E5 | 🧥 | \:coat: | Coat |
| U+1F9E6 | 🧦 | \:socks: | Socks |
| U+1F9E7 | 🧧 | \:red\_envelope: | Red Gift Envelope |
| U+1F9E8 | 🧨 | \:firecracker: | Firecracker |
| U+1F9E9 | 🧩 | \:jigsaw: | Jigsaw Puzzle Piece |
| U+1F9EA | 🧪 | \:test\_tube: | Test Tube |
| U+1F9EB | 🧫 | \:petri\_dish: | Petri Dish |
| U+1F9EC | 🧬 | \:dna: | Dna Double Helix |
| U+1F9ED | 🧭 | \:compass: | Compass |
| U+1F9EE | 🧮 | \:abacus: | Abacus |
| U+1F9EF | 🧯 | \:fire\_extinguisher: | Fire Extinguisher |
| U+1F9F0 | 🧰 | \:toolbox: | Toolbox |
| U+1F9F1 | 🧱 | \:bricks: | Brick |
| U+1F9F2 | 🧲 | \:magnet: | Magnet |
| U+1F9F3 | 🧳 | \:luggage: | Luggage |
| U+1F9F4 | 🧴 | \:lotion\_bottle: | Lotion Bottle |
| U+1F9F5 | 🧵 | \:thread: | Spool Of Thread |
| U+1F9F6 | 🧶 | \:yarn: | Ball Of Yarn |
| U+1F9F7 | 🧷 | \:safety\_pin: | Safety Pin |
| U+1F9F8 | 🧸 | \:teddy\_bear: | Teddy Bear |
| U+1F9F9 | 🧹 | \:broom: | Broom |
| U+1F9FA | 🧺 | \:basket: | Basket |
| U+1F9FB | 🧻 | \:roll\_of\_paper: | Roll Of Paper |
| U+1F9FC | 🧼 | \:soap: | Bar Of Soap |
| U+1F9FD | 🧽 | \:sponge: | Sponge |
| U+1F9FE | 🧾 | \:receipt: | Receipt |
| U+1F9FF | 🧿 | \:nazar\_amulet: | Nazar Amulet |
| U+1FA70 | 🩰 | \:ballet\_shoes: | Ballet Shoes |
| U+1FA71 | 🩱 | \:one-piece\_swimsuit: | One-Piece Swimsuit |
| U+1FA72 | 🩲 | \:briefs: | Briefs |
| U+1FA73 | 🩳 | \:shorts: | Shorts |
| U+1FA74 | 🩴 | \:thong\_sandal: | Thong Sandal |
| U+1FA78 | 🩸 | \:drop\_of\_blood: | Drop Of Blood |
| U+1FA79 | 🩹 | \:adhesive\_bandage: | Adhesive Bandage |
| U+1FA7A | 🩺 | \:stethoscope: | Stethoscope |
| U+1FA80 | 🪀 | \:yo-yo: | Yo-Yo |
| U+1FA81 | 🪁 | \:kite: | Kite |
| U+1FA82 | 🪂 | \:parachute: | Parachute |
| U+1FA83 | 🪃 | \:boomerang: | Boomerang |
| U+1FA84 | 🪄 | \:magic\_wand: | Magic Wand |
| U+1FA85 | 🪅 | \:pinata: | Pinata |
| U+1FA86 | 🪆 | \:nesting\_dolls: | Nesting Dolls |
| U+1FA90 | 🪐 | \:ringed\_planet: | Ringed Planet |
| U+1FA91 | 🪑 | \:chair: | Chair |
| U+1FA92 | 🪒 | \:razor: | Razor |
| U+1FA93 | 🪓 | \:axe: | Axe |
| U+1FA94 | 🪔 | \:diya\_lamp: | Diya Lamp |
| U+1FA95 | 🪕 | \:banjo: | Banjo |
| U+1FA96 | 🪖 | \:military\_helmet: | Military Helmet |
| U+1FA97 | 🪗 | \:accordion: | Accordion |
| U+1FA98 | 🪘 | \:long\_drum: | Long Drum |
| U+1FA99 | 🪙 | \:coin: | Coin |
| U+1FA9A | 🪚 | \:carpentry\_saw: | Carpentry Saw |
| U+1FA9B | 🪛 | \:screwdriver: | Screwdriver |
| U+1FA9C | 🪜 | \:ladder: | Ladder |
| U+1FA9D | 🪝 | \:hook: | Hook |
| U+1FA9E | 🪞 | \:mirror: | Mirror |
| U+1FA9F | 🪟 | \:window: | Window |
| U+1FAA0 | 🪠 | \:plunger: | Plunger |
| U+1FAA1 | 🪡 | \:sewing\_needle: | Sewing Needle |
| U+1FAA2 | 🪢 | \:knot: | Knot |
| U+1FAA3 | 🪣 | \:bucket: | Bucket |
| U+1FAA4 | 🪤 | \:mouse\_trap: | Mouse Trap |
| U+1FAA5 | 🪥 | \:toothbrush: | Toothbrush |
| U+1FAA6 | 🪦 | \:headstone: | Headstone |
| U+1FAA7 | 🪧 | \:placard: | Placard |
| U+1FAA8 | 🪨 | \:rock: | Rock |
| U+1FAB0 | 🪰 | \:fly: | Fly |
| U+1FAB1 | 🪱 | \:worm: | Worm |
| U+1FAB2 | 🪲 | \:beetle: | Beetle |
| U+1FAB3 | 🪳 | \:cockroach: | Cockroach |
| U+1FAB4 | 🪴 | \:potted\_plant: | Potted Plant |
| U+1FAB5 | 🪵 | \:wood: | Wood |
| U+1FAB6 | 🪶 | \:feather: | Feather |
| U+1FAC0 | 🫀 | \:anatomical\_heart: | Anatomical Heart |
| U+1FAC1 | 🫁 | \:lungs: | Lungs |
| U+1FAC2 | 🫂 | \:people\_hugging: | People Hugging |
| U+1FAD0 | 🫐 | \:blueberries: | Blueberries |
| U+1FAD1 | 🫑 | \:bell\_pepper: | Bell Pepper |
| U+1FAD2 | 🫒 | \:olive: | Olive |
| U+1FAD3 | 🫓 | \:flatbread: | Flatbread |
| U+1FAD4 | 🫔 | \:tamale: | Tamale |
| U+1FAD5 | 🫕 | \:fondue: | Fondue |
| U+1FAD6 | 🫖 | \:teapot: | Teapot |
| programming_docs |
julia Integers and Floating-Point Numbers Integers and Floating-Point Numbers
===================================
Integers and floating-point values are the basic building blocks of arithmetic and computation. Built-in representations of such values are called numeric primitives, while representations of integers and floating-point numbers as immediate values in code are known as numeric literals. For example, `1` is an integer literal, while `1.0` is a floating-point literal; their binary in-memory representations as objects are numeric primitives.
Julia provides a broad range of primitive numeric types, and a full complement of arithmetic and bitwise operators as well as standard mathematical functions are defined over them. These map directly onto numeric types and operations that are natively supported on modern computers, thus allowing Julia to take full advantage of computational resources. Additionally, Julia provides software support for [Arbitrary Precision Arithmetic](#Arbitrary-Precision-Arithmetic), which can handle operations on numeric values that cannot be represented effectively in native hardware representations, but at the cost of relatively slower performance.
The following are Julia's primitive numeric types:
* **Integer types:**
| Type | Signed? | Number of bits | Smallest value | Largest value |
| --- | --- | --- | --- | --- |
| [`Int8`](../../base/numbers/index#Core.Int8) | ✓ | 8 | -2^7 | 2^7 - 1 |
| [`UInt8`](../../base/numbers/index#Core.UInt8) | | 8 | 0 | 2^8 - 1 |
| [`Int16`](../../base/numbers/index#Core.Int16) | ✓ | 16 | -2^15 | 2^15 - 1 |
| [`UInt16`](../../base/numbers/index#Core.UInt16) | | 16 | 0 | 2^16 - 1 |
| [`Int32`](../../base/numbers/index#Core.Int32) | ✓ | 32 | -2^31 | 2^31 - 1 |
| [`UInt32`](../../base/numbers/index#Core.UInt32) | | 32 | 0 | 2^32 - 1 |
| [`Int64`](../../base/numbers/index#Core.Int64) | ✓ | 64 | -2^63 | 2^63 - 1 |
| [`UInt64`](../../base/numbers/index#Core.UInt64) | | 64 | 0 | 2^64 - 1 |
| [`Int128`](../../base/numbers/index#Core.Int128) | ✓ | 128 | -2^127 | 2^127 - 1 |
| [`UInt128`](../../base/numbers/index#Core.UInt128) | | 128 | 0 | 2^128 - 1 |
| [`Bool`](../../base/numbers/index#Core.Bool) | N/A | 8 | `false` (0) | `true` (1) |
* **Floating-point types:**
| Type | Precision | Number of bits |
| --- | --- | --- |
| [`Float16`](../../base/numbers/index#Core.Float16) | [half](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) | 16 |
| [`Float32`](../../base/numbers/index#Core.Float32) | [single](https://en.wikipedia.org/wiki/Single_precision_floating-point_format) | 32 |
| [`Float64`](../../base/numbers/index#Core.Float64) | [double](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) | 64 |
Additionally, full support for [Complex and Rational Numbers](../complex-and-rational-numbers/index#Complex-and-Rational-Numbers) is built on top of these primitive numeric types. All numeric types interoperate naturally without explicit casting, thanks to a flexible, user-extensible [type promotion system](../conversion-and-promotion/index#conversion-and-promotion).
[Integers](#Integers)
----------------------
Literal integers are represented in the standard manner:
```
julia> 1
1
julia> 1234
1234
```
The default type for an integer literal depends on whether the target system has a 32-bit architecture or a 64-bit architecture:
```
# 32-bit system:
julia> typeof(1)
Int32
# 64-bit system:
julia> typeof(1)
Int64
```
The Julia internal variable [`Sys.WORD_SIZE`](../../base/constants/index#Base.Sys.WORD_SIZE) indicates whether the target system is 32-bit or 64-bit:
```
# 32-bit system:
julia> Sys.WORD_SIZE
32
# 64-bit system:
julia> Sys.WORD_SIZE
64
```
Julia also defines the types `Int` and `UInt`, which are aliases for the system's signed and unsigned native integer types respectively:
```
# 32-bit system:
julia> Int
Int32
julia> UInt
UInt32
# 64-bit system:
julia> Int
Int64
julia> UInt
UInt64
```
Larger integer literals that cannot be represented using only 32 bits but can be represented in 64 bits always create 64-bit integers, regardless of the system type:
```
# 32-bit or 64-bit system:
julia> typeof(3000000000)
Int64
```
Unsigned integers are input and output using the `0x` prefix and hexadecimal (base 16) digits `0-9a-f` (the capitalized digits `A-F` also work for input). The size of the unsigned value is determined by the number of hex digits used:
```
julia> x = 0x1
0x01
julia> typeof(x)
UInt8
julia> x = 0x123
0x0123
julia> typeof(x)
UInt16
julia> x = 0x1234567
0x01234567
julia> typeof(x)
UInt32
julia> x = 0x123456789abcdef
0x0123456789abcdef
julia> typeof(x)
UInt64
julia> x = 0x11112222333344445555666677778888
0x11112222333344445555666677778888
julia> typeof(x)
UInt128
```
This behavior is based on the observation that when one uses unsigned hex literals for integer values, one typically is using them to represent a fixed numeric byte sequence, rather than just an integer value.
Binary and octal literals are also supported:
```
julia> x = 0b10
0x02
julia> typeof(x)
UInt8
julia> x = 0o010
0x08
julia> typeof(x)
UInt8
julia> x = 0x00000000000000001111222233334444
0x00000000000000001111222233334444
julia> typeof(x)
UInt128
```
As for hexadecimal literals, binary and octal literals produce unsigned integer types. The size of the binary data item is the minimal needed size, if the leading digit of the literal is not `0`. In the case of leading zeros, the size is determined by the minimal needed size for a literal, which has the same length but leading digit `1`. It means that:
* `0x1` and `0x12` are `UInt8` literals,
* `0x123` and `0x1234` are `UInt16` literals,
* `0x12345` and `0x12345678` are `UInt32` literals,
* `0x123456789` and `0x1234567890adcdef` are `UInt64` literals, etc.
Even if there are leading zero digits which don’t contribute to the value, they count for determining storage size of a literal. So `0x01` is a `UInt8` while `0x0001` is a `UInt16`.
That allows the user to control the size.
Values which cannot be stored in `UInt128` cannot be written as such literals.
Binary, octal, and hexadecimal literals may be signed by a `-` immediately preceding the unsigned literal. They produce an unsigned integer of the same size as the unsigned literal would do, with the two's complement of the value:
```
julia> -0x2
0xfe
julia> -0x0002
0xfffe
```
The minimum and maximum representable values of primitive numeric types such as integers are given by the [`typemin`](../../base/base/index#Base.typemin) and [`typemax`](../../base/base/index#Base.typemax) functions:
```
julia> (typemin(Int32), typemax(Int32))
(-2147483648, 2147483647)
julia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128]
println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]")
end
Int8: [-128,127]
Int16: [-32768,32767]
Int32: [-2147483648,2147483647]
Int64: [-9223372036854775808,9223372036854775807]
Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727]
UInt8: [0,255]
UInt16: [0,65535]
UInt32: [0,4294967295]
UInt64: [0,18446744073709551615]
UInt128: [0,340282366920938463463374607431768211455]
```
The values returned by [`typemin`](../../base/base/index#Base.typemin) and [`typemax`](../../base/base/index#Base.typemax) are always of the given argument type. (The above expression uses several features that have yet to be introduced, including [for loops](../control-flow/index#man-loops), [Strings](../strings/index#man-strings), and [Interpolation](../strings/index#string-interpolation), but should be easy enough to understand for users with some existing programming experience.)
###
[Overflow behavior](#Overflow-behavior)
In Julia, exceeding the maximum representable value of a given type results in a wraparound behavior:
```
julia> x = typemax(Int64)
9223372036854775807
julia> x + 1
-9223372036854775808
julia> x + 1 == typemin(Int64)
true
```
Thus, arithmetic with Julia integers is actually a form of [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic). This reflects the characteristics of the underlying arithmetic of integers as implemented on modern computers. In applications where overflow is possible, explicit checking for wraparound produced by overflow is essential; otherwise, the [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) type in [Arbitrary Precision Arithmetic](#Arbitrary-Precision-Arithmetic) is recommended instead.
An example of overflow behavior and how to potentially resolve it is as follows:
```
julia> 10^19
-8446744073709551616
julia> big(10)^19
10000000000000000000
```
###
[Division errors](#Division-errors)
Integer division (the `div` function) has two exceptional cases: dividing by zero, and dividing the lowest negative number ([`typemin`](../../base/base/index#Base.typemin)) by -1. Both of these cases throw a [`DivideError`](../../base/base/index#Core.DivideError). The remainder and modulus functions (`rem` and `mod`) throw a [`DivideError`](../../base/base/index#Core.DivideError) when their second argument is zero.
[Floating-Point Numbers](#Floating-Point-Numbers)
--------------------------------------------------
Literal floating-point numbers are represented in the standard formats, using [E-notation](https://en.wikipedia.org/wiki/Scientific_notation#E_notation) when necessary:
```
julia> 1.0
1.0
julia> 1.
1.0
julia> 0.5
0.5
julia> .5
0.5
julia> -1.23
-1.23
julia> 1e10
1.0e10
julia> 2.5e-4
0.00025
```
The above results are all [`Float64`](../../base/numbers/index#Core.Float64) values. Literal [`Float32`](../../base/numbers/index#Core.Float32) values can be entered by writing an `f` in place of `e`:
```
julia> x = 0.5f0
0.5f0
julia> typeof(x)
Float32
julia> 2.5f-4
0.00025f0
```
Values can be converted to [`Float32`](../../base/numbers/index#Core.Float32) easily:
```
julia> x = Float32(-1.5)
-1.5f0
julia> typeof(x)
Float32
```
Hexadecimal floating-point literals are also valid, but only as [`Float64`](../../base/numbers/index#Core.Float64) values, with `p` preceding the base-2 exponent:
```
julia> 0x1p0
1.0
julia> 0x1.8p3
12.0
julia> x = 0x.4p-1
0.125
julia> typeof(x)
Float64
```
Half-precision floating-point numbers are also supported ([`Float16`](../../base/numbers/index#Core.Float16)), but they are implemented in software and use [`Float32`](../../base/numbers/index#Core.Float32) for calculations.
```
julia> sizeof(Float16(4.))
2
julia> 2*Float16(4.)
Float16(8.0)
```
The underscore `_` can be used as digit separator:
```
julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010
(10000, 5.0e-9, 0xdeadbeef, 0xb2)
```
###
[Floating-point zero](#Floating-point-zero)
Floating-point numbers have [two zeros](https://en.wikipedia.org/wiki/Signed_zero), positive zero and negative zero. They are equal to each other but have different binary representations, as can be seen using the [`bitstring`](../../base/numbers/index#Base.bitstring) function:
```
julia> 0.0 == -0.0
true
julia> bitstring(0.0)
"0000000000000000000000000000000000000000000000000000000000000000"
julia> bitstring(-0.0)
"1000000000000000000000000000000000000000000000000000000000000000"
```
###
[Special floating-point values](#Special-floating-point-values)
There are three specified standard floating-point values that do not correspond to any point on the real number line:
| `Float16` | `Float32` | `Float64` | Name | Description |
| --- | --- | --- | --- | --- |
| `Inf16` | `Inf32` | `Inf` | positive infinity | a value greater than all finite floating-point values |
| `-Inf16` | `-Inf32` | `-Inf` | negative infinity | a value less than all finite floating-point values |
| `NaN16` | `NaN32` | `NaN` | not a number | a value not `==` to any floating-point value (including itself) |
For further discussion of how these non-finite floating-point values are ordered with respect to each other and other floats, see [Numeric Comparisons](../mathematical-operations/index#Numeric-Comparisons). By the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754-2008), these floating-point values are the results of certain arithmetic operations:
```
julia> 1/Inf
0.0
julia> 1/0
Inf
julia> -5/0
-Inf
julia> 0.000001/0
Inf
julia> 0/0
NaN
julia> 500 + Inf
Inf
julia> 500 - Inf
-Inf
julia> Inf + Inf
Inf
julia> Inf - Inf
NaN
julia> Inf * Inf
Inf
julia> Inf / Inf
NaN
julia> 0 * Inf
NaN
julia> NaN == NaN
false
julia> NaN != NaN
true
julia> NaN < NaN
false
julia> NaN > NaN
false
```
The [`typemin`](../../base/base/index#Base.typemin) and [`typemax`](../../base/base/index#Base.typemax) functions also apply to floating-point types:
```
julia> (typemin(Float16),typemax(Float16))
(-Inf16, Inf16)
julia> (typemin(Float32),typemax(Float32))
(-Inf32, Inf32)
julia> (typemin(Float64),typemax(Float64))
(-Inf, Inf)
```
###
[Machine epsilon](#Machine-epsilon)
Most real numbers cannot be represented exactly with floating-point numbers, and so for many purposes it is important to know the distance between two adjacent representable floating-point numbers, which is often known as [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon).
Julia provides [`eps`](#), which gives the distance between `1.0` and the next larger representable floating-point value:
```
julia> eps(Float32)
1.1920929f-7
julia> eps(Float64)
2.220446049250313e-16
julia> eps() # same as eps(Float64)
2.220446049250313e-16
```
These values are `2.0^-23` and `2.0^-52` as [`Float32`](../../base/numbers/index#Core.Float32) and [`Float64`](../../base/numbers/index#Core.Float64) values, respectively. The [`eps`](#) function can also take a floating-point value as an argument, and gives the absolute difference between that value and the next representable floating point value. That is, `eps(x)` yields a value of the same type as `x` such that `x + eps(x)` is the next representable floating-point value larger than `x`:
```
julia> eps(1.0)
2.220446049250313e-16
julia> eps(1000.)
1.1368683772161603e-13
julia> eps(1e-27)
1.793662034335766e-43
julia> eps(0.0)
5.0e-324
```
The distance between two adjacent representable floating-point numbers is not constant, but is smaller for smaller values and larger for larger values. In other words, the representable floating-point numbers are densest in the real number line near zero, and grow sparser exponentially as one moves farther away from zero. By definition, `eps(1.0)` is the same as `eps(Float64)` since `1.0` is a 64-bit floating-point value.
Julia also provides the [`nextfloat`](../../base/numbers/index#Base.nextfloat) and [`prevfloat`](../../base/numbers/index#Base.prevfloat) functions which return the next largest or smallest representable floating-point number to the argument respectively:
```
julia> x = 1.25f0
1.25f0
julia> nextfloat(x)
1.2500001f0
julia> prevfloat(x)
1.2499999f0
julia> bitstring(prevfloat(x))
"00111111100111111111111111111111"
julia> bitstring(x)
"00111111101000000000000000000000"
julia> bitstring(nextfloat(x))
"00111111101000000000000000000001"
```
This example highlights the general principle that the adjacent representable floating-point numbers also have adjacent binary integer representations.
###
[Rounding modes](#Rounding-modes)
If a number doesn't have an exact floating-point representation, it must be rounded to an appropriate representable value. However, the manner in which this rounding is done can be changed if required according to the rounding modes presented in the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754-2008).
The default mode used is always [`RoundNearest`](../../base/math/index#Base.Rounding.RoundNearest), which rounds to the nearest representable value, with ties rounded towards the nearest value with an even least significant bit.
###
[Background and References](#Background-and-References)
Floating-point arithmetic entails many subtleties which can be surprising to users who are unfamiliar with the low-level implementation details. However, these subtleties are described in detail in most books on scientific computation, and also in the following references:
* The definitive guide to floating point arithmetic is the [IEEE 754-2008 Standard](https://standards.ieee.org/standard/754-2008.html); however, it is not available for free online.
* For a brief but lucid presentation of how floating-point numbers are represented, see John D. Cook's [article](https://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/) on the subject as well as his [introduction](https://www.johndcook.com/blog/2009/04/06/numbers-are-a-leaky-abstraction/) to some of the issues arising from how this representation differs in behavior from the idealized abstraction of real numbers.
* Also recommended is Bruce Dawson's [series of blog posts on floating-point numbers](https://randomascii.wordpress.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats/).
* For an excellent, in-depth discussion of floating-point numbers and issues of numerical accuracy encountered when computing with them, see David Goldberg's paper [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.6768&rep=rep1&type=pdf).
* For even more extensive documentation of the history of, rationale for, and issues with floating-point numbers, as well as discussion of many other topics in numerical computing, see the [collected writings](https://people.eecs.berkeley.edu/~wkahan/) of [William Kahan](https://en.wikipedia.org/wiki/William_Kahan), commonly known as the "Father of Floating-Point". Of particular interest may be [An Interview with the Old Man of Floating-Point](https://people.eecs.berkeley.edu/~wkahan/ieee754status/754story.html).
[Arbitrary Precision Arithmetic](#Arbitrary-Precision-Arithmetic)
------------------------------------------------------------------
To allow computations with arbitrary-precision integers and floating point numbers, Julia wraps the [GNU Multiple Precision Arithmetic Library (GMP)](https://gmplib.org) and the [GNU MPFR Library](https://www.mpfr.org), respectively. The [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) and [`BigFloat`](../../base/numbers/index#Base.MPFR.BigFloat) types are available in Julia for arbitrary precision integer and floating point numbers respectively.
Constructors exist to create these types from primitive numerical types, and the [string literal](../strings/index#non-standard-string-literals) [`@big_str`](../../base/numbers/index#Core.@big_str) or [`parse`](../../base/numbers/index#Base.parse) can be used to construct them from `AbstractString`s. `BigInt`s can also be input as integer literals when they are too big for other built-in integer types. Note that as there is no unsigned arbitrary-precision integer type in `Base` (`BigInt` is sufficient in most cases), hexadecimal, octal and binary literals can be used (in addition to decimal literals).
Once created, they participate in arithmetic with all other numeric types thanks to Julia's [type promotion and conversion mechanism](../conversion-and-promotion/index#conversion-and-promotion):
```
julia> BigInt(typemax(Int64)) + 1
9223372036854775808
julia> big"123456789012345678901234567890" + 1
123456789012345678901234567891
julia> parse(BigInt, "123456789012345678901234567890") + 1
123456789012345678901234567891
julia> string(big"2"^200, base=16)
"100000000000000000000000000000000000000000000000000"
julia> 0x100000000000000000000000000000000-1 == typemax(UInt128)
true
julia> 0x000000000000000000000000000000000
0
julia> typeof(ans)
BigInt
julia> big"1.23456789012345678901"
1.234567890123456789010000000000000000000000000000000000000000000000000000000004
julia> parse(BigFloat, "1.23456789012345678901")
1.234567890123456789010000000000000000000000000000000000000000000000000000000004
julia> BigFloat(2.0^66) / 3
2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19
julia> factorial(BigInt(40))
815915283247897734345611269596115894272000000000
```
However, type promotion between the primitive types above and [`BigInt`](../../base/numbers/index#Base.GMP.BigInt)/[`BigFloat`](../../base/numbers/index#Base.MPFR.BigFloat) is not automatic and must be explicitly stated.
```
julia> x = typemin(Int64)
-9223372036854775808
julia> x = x - 1
9223372036854775807
julia> typeof(x)
Int64
julia> y = BigInt(typemin(Int64))
-9223372036854775808
julia> y = y - 1
-9223372036854775809
julia> typeof(y)
BigInt
```
The default precision (in number of bits of the significand) and rounding mode of [`BigFloat`](../../base/numbers/index#Base.MPFR.BigFloat) operations can be changed globally by calling [`setprecision`](../../base/numbers/index#Base.MPFR.setprecision) and [`setrounding`](#), and all further calculations will take these changes in account. Alternatively, the precision or the rounding can be changed only within the execution of a particular block of code by using the same functions with a `do` block:
```
julia> setrounding(BigFloat, RoundUp) do
BigFloat(1) + parse(BigFloat, "0.1")
end
1.100000000000000000000000000000000000000000000000000000000000000000000000000003
julia> setrounding(BigFloat, RoundDown) do
BigFloat(1) + parse(BigFloat, "0.1")
end
1.099999999999999999999999999999999999999999999999999999999999999999999999999986
julia> setprecision(40) do
BigFloat(1) + parse(BigFloat, "0.1")
end
1.1000000000004
```
[Numeric Literal Coefficients](#man-numeric-literal-coefficients)
------------------------------------------------------------------
To make common numeric formulae and expressions clearer, Julia allows variables to be immediately preceded by a numeric literal, implying multiplication. This makes writing polynomial expressions much cleaner:
```
julia> x = 3
3
julia> 2x^2 - 3x + 1
10
julia> 1.5x^2 - .5x + 1
13.0
```
It also makes writing exponential functions more elegant:
```
julia> 2^2x
64
```
The precedence of numeric literal coefficients is slightly lower than that of unary operators such as negation. So `-2x` is parsed as `(-2) * x` and `√2x` is parsed as `(√2) * x`. However, numeric literal coefficients parse similarly to unary operators when combined with exponentiation. For example `2^3x` is parsed as `2^(3x)`, and `2x^3` is parsed as `2*(x^3)`.
Numeric literals also work as coefficients to parenthesized expressions:
```
julia> 2(x-1)^2 - 3(x-1) + 1
3
```
The precedence of numeric literal coefficients used for implicit multiplication is higher than other binary operators such as multiplication (`*`), and division (`/`, `\`, and `//`). This means, for example, that `1 / 2im` equals `-0.5im` and `6 // 2(2 + 1)` equals `1 // 1`.
Additionally, parenthesized expressions can be used as coefficients to variables, implying multiplication of the expression by the variable:
```
julia> (x-1)x
6
```
Neither juxtaposition of two parenthesized expressions, nor placing a variable before a parenthesized expression, however, can be used to imply multiplication:
```
julia> (x-1)(x+1)
ERROR: MethodError: objects of type Int64 are not callable
julia> x(x+1)
ERROR: MethodError: objects of type Int64 are not callable
```
Both expressions are interpreted as function application: any expression that is not a numeric literal, when immediately followed by a parenthetical, is interpreted as a function applied to the values in parentheses (see [Functions](../faq/index#Functions) for more about functions). Thus, in both of these cases, an error occurs since the left-hand value is not a function.
The above syntactic enhancements significantly reduce the visual noise incurred when writing common mathematical formulae. Note that no whitespace may come between a numeric literal coefficient and the identifier or parenthesized expression which it multiplies.
###
[Syntax Conflicts](#Syntax-Conflicts)
Juxtaposed literal coefficient syntax may conflict with some numeric literal syntaxes: hexadecimal, octal and binary integer literals and engineering notation for floating-point literals. Here are some situations where syntactic conflicts arise:
* The hexadecimal integer literal expression `0xff` could be interpreted as the numeric literal `0` multiplied by the variable `xff`. Similar ambiguities arise with octal and binary literals like `0o777` or `0b01001010`.
* The floating-point literal expression `1e10` could be interpreted as the numeric literal `1` multiplied by the variable `e10`, and similarly with the equivalent `E` form.
* The 32-bit floating-point literal expression `1.5f22` could be interpreted as the numeric literal `1.5` multiplied by the variable `f22`.
In all cases the ambiguity is resolved in favor of interpretation as numeric literals:
* Expressions starting with `0x`/`0o`/`0b` are always hexadecimal/octal/binary literals.
* Expressions starting with a numeric literal followed by `e` or `E` are always floating-point literals.
* Expressions starting with a numeric literal followed by `f` are always 32-bit floating-point literals.
Unlike `E`, which is equivalent to `e` in numeric literals for historical reasons, `F` is just another letter and does not behave like `f` in numeric literals. Hence, expressions starting with a numeric literal followed by `F` are interpreted as the numerical literal multiplied by a variable, which means that, for example, `1.5F22` is equal to `1.5 * F22`.
[Literal zero and one](#Literal-zero-and-one)
----------------------------------------------
Julia provides functions which return literal 0 and 1 corresponding to a specified type or the type of a given variable.
| Function | Description |
| --- | --- |
| [`zero(x)`](../../base/numbers/index#Base.zero) | Literal zero of type `x` or type of variable `x` |
| [`one(x)`](../../base/numbers/index#Base.one) | Literal one of type `x` or type of variable `x` |
These functions are useful in [Numeric Comparisons](../mathematical-operations/index#Numeric-Comparisons) to avoid overhead from unnecessary [type conversion](../conversion-and-promotion/index#conversion-and-promotion).
Examples:
```
julia> zero(Float32)
0.0f0
julia> zero(1.0)
0.0
julia> one(Int32)
1
julia> one(BigFloat)
1.0
```
| programming_docs |
julia Workflow Tips Workflow Tips
=============
Here are some tips for working with Julia efficiently.
[REPL-based workflow](#REPL-based-workflow)
--------------------------------------------
As already elaborated in [The Julia REPL](../../stdlib/repl/index#The-Julia-REPL), Julia's REPL provides rich functionality that facilitates an efficient interactive workflow. Here are some tips that might further enhance your experience at the command line.
###
[A basic editor/REPL workflow](#A-basic-editor/REPL-workflow)
The most basic Julia workflows involve using a text editor in conjunction with the `julia` command line. A common pattern includes the following elements:
* **Put code under development in a temporary module.** Create a file, say `Tmp.jl`, and include within it
```
module Tmp
export say_hello
say_hello() = println("Hello!")
# your other definitions here
end
```
* **Put your test code in another file.** Create another file, say `tst.jl`, which looks like
```
include("Tmp.jl")
import .Tmp
# using .Tmp # we can use `using` to bring the exported symbols in `Tmp` into our namespace
Tmp.say_hello()
# say_hello()
# your other test code here
```
and includes tests for the contents of `Tmp`. Alternatively, you can wrap the contents of your test file in a module, as
```
module Tst
include("Tmp.jl")
import .Tmp
#using .Tmp
Tmp.say_hello()
# say_hello()
# your other test code here
end
```
The advantage is that your testing code is now contained in a module and does not use the global scope in `Main` for definitions, which is a bit more tidy.
* `include` the `tst.jl` file in the Julia REPL with `include("tst.jl")`.
* **Lather. Rinse. Repeat.** Explore ideas at the `julia` command prompt. Save good ideas in `tst.jl`. To execute `tst.jl` after it has been changed, just `include` it again.
[Browser-based workflow](#Browser-based-workflow)
--------------------------------------------------
It is also possible to interact with a Julia REPL in the browser via [IJulia](https://github.com/JuliaLang/IJulia.jl). See the package home for details.
[Revise-based workflows](#Revise-based-workflows)
--------------------------------------------------
Whether you're at the REPL or in IJulia, you can typically improve your development experience with [Revise](https://github.com/timholy/Revise.jl). It is common to configure Revise to start whenever julia is started, as per the instructions in the [Revise documentation](https://timholy.github.io/Revise.jl/stable/). Once configured, Revise will track changes to files in any loaded modules, and to any files loaded in to the REPL with `includet` (but not with plain `include`); you can then edit the files and the changes take effect without restarting your julia session. A standard workflow is similar to the REPL-based workflow above, with the following modifications:
1. Put your code in a module somewhere on your load path. There are several options for achieving this, of which two recommended choices are:
* For long-term projects, use [PkgTemplates](https://github.com/invenia/PkgTemplates.jl):
```
using PkgTemplates
t = Template()
t("MyPkg")
```
This will create a blank package, `"MyPkg"`, in your `.julia/dev` directory. Note that PkgTemplates allows you to control many different options through its `Template` constructor.
In step 2 below, edit `MyPkg/src/MyPkg.jl` to change the source code, and `MyPkg/test/runtests.jl` for the tests.
* For "throw-away" projects, you can avoid any need for cleanup by doing your work in your temporary directory (e.g., `/tmp`).
Navigate to your temporary directory and launch Julia, then do the following:
```
pkg> generate MyPkg # type ] to enter pkg mode
julia> push!(LOAD_PATH, pwd()) # hit backspace to exit pkg mode
```
If you restart your Julia session you'll have to re-issue that command modifying `LOAD_PATH`.
In step 2 below, edit `MyPkg/src/MyPkg.jl` to change the source code, and create any test file of your choosing.
2. Develop your package
*Before* loading any code, make sure you're running Revise: say `using Revise` or follow its documentation on configuring it to run automatically.
Then navigate to the directory containing your test file (here assumed to be `"runtests.jl"`) and do the following:
```
julia> using MyPkg
julia> include("runtests.jl")
```
You can iteratively modify the code in MyPkg in your editor and re-run the tests with `include("runtests.jl")`. You generally should not need to restart your Julia session to see the changes take effect (subject to a few [limitations](https://timholy.github.io/Revise.jl/stable/limitations/)).
julia Frequently Asked Questions Frequently Asked Questions
==========================
[General](#General)
--------------------
###
[Is Julia named after someone or something?](#Is-Julia-named-after-someone-or-something?)
No.
###
[Why don't you compile Matlab/Python/R/… code to Julia?](#Why-don't-you-compile-Matlab/Python/R/%E2%80%A6-code-to-Julia?)
Since many people are familiar with the syntax of other dynamic languages, and lots of code has already been written in those languages, it is natural to wonder why we didn't just plug a Matlab or Python front-end into a Julia back-end (or “transpile” code to Julia) in order to get all the performance benefits of Julia without requiring programmers to learn a new language. Simple, right?
The basic issue is that there is *nothing special about Julia's compiler*: we use a commonplace compiler (LLVM) with no “secret sauce” that other language developers don't know about. Indeed, Julia's compiler is in many ways much simpler than those of other dynamic languages (e.g. PyPy or LuaJIT). Julia's performance advantage derives almost entirely from its front-end: its language semantics allow a [well-written Julia program](../performance-tips/index#man-performance-tips) to *give more opportunities to the compiler* to generate efficient code and memory layouts. If you tried to compile Matlab or Python code to Julia, our compiler would be limited by the semantics of Matlab or Python to producing code no better than that of existing compilers for those languages (and probably worse). The key role of semantics is also why several existing Python compilers (like Numba and Pythran) only attempt to optimize a small subset of the language (e.g. operations on Numpy arrays and scalars), and for this subset they are already doing at least as well as we could for the same semantics. The people working on those projects are incredibly smart and have accomplished amazing things, but retrofitting a compiler onto a language that was designed to be interpreted is a very difficult problem.
Julia's advantage is that good performance is not limited to a small subset of “built-in” types and operations, and one can write high-level type-generic code that works on arbitrary user-defined types while remaining fast and memory-efficient. Types in languages like Python simply don't provide enough information to the compiler for similar capabilities, so as soon as you used those languages as a Julia front-end you would be stuck.
For similar reasons, automated translation to Julia would also typically generate unreadable, slow, non-idiomatic code that would not be a good starting point for a native Julia port from another language.
On the other hand, language *interoperability* is extremely useful: we want to exploit existing high-quality code in other languages from Julia (and vice versa)! The best way to enable this is not a transpiler, but rather via easy inter-language calling facilities. We have worked hard on this, from the built-in `ccall` intrinsic (to call C and Fortran libraries) to [JuliaInterop](https://github.com/JuliaInterop) packages that connect Julia to Python, Matlab, C++, and more.
[Public API](#man-api)
-----------------------
###
[How does Julia define its public API?](#How-does-Julia-define-its-public-API?)
The only interfaces that are stable with respect to [SemVer](https://semver.org/) of `julia` version are the Julia `Base` and standard libraries interfaces described in [the documentation](https://docs.julialang.org/) and not marked as unstable (e.g., experimental and internal). Functions, types, and constants are not part of the public API if they are not included in the documentation, *even if they have docstrings*.
###
[There is a useful undocumented function/type/constant. Can I use it?](#There-is-a-useful-undocumented-function/type/constant.-Can-I-use-it?)
Updating Julia may break your code if you use non-public API. If the code is self-contained, it may be a good idea to copy it into your project. If you want to rely on a complex non-public API, especially when using it from a stable package, it is a good idea to open an [issue](https://github.com/JuliaLang/julia/issues) or [pull request](https://github.com/JuliaLang/julia/pulls) to start a discussion for turning it into a public API. However, we do not discourage the attempt to create packages that expose stable public interfaces while relying on non-public implementation details of `julia` and buffering the differences across different `julia` versions.
###
[The documentation is not accurate enough. Can I rely on the existing behavior?](#The-documentation-is-not-accurate-enough.-Can-I-rely-on-the-existing-behavior?)
Please open an [issue](https://github.com/JuliaLang/julia/issues) or [pull request](https://github.com/JuliaLang/julia/pulls) to start a discussion for turning the existing behavior into a public API.
[Sessions and the REPL](#Sessions-and-the-REPL)
------------------------------------------------
###
[How do I delete an object in memory?](#How-do-I-delete-an-object-in-memory?)
Julia does not have an analog of MATLAB's `clear` function; once a name is defined in a Julia session (technically, in module `Main`), it is always present.
If memory usage is your concern, you can always replace objects with ones that consume less memory. For example, if `A` is a gigabyte-sized array that you no longer need, you can free the memory with `A = nothing`. The memory will be released the next time the garbage collector runs; you can force this to happen with [`GC.gc()`](../../base/base/index#Base.GC.gc). Moreover, an attempt to use `A` will likely result in an error, because most methods are not defined on type `Nothing`.
###
[How can I modify the declaration of a type in my session?](#How-can-I-modify-the-declaration-of-a-type-in-my-session?)
Perhaps you've defined a type and then realize you need to add a new field. If you try this at the REPL, you get the error:
```
ERROR: invalid redefinition of constant MyType
```
Types in module `Main` cannot be redefined.
While this can be inconvenient when you are developing new code, there's an excellent workaround. Modules can be replaced by redefining them, and so if you wrap all your new code inside a module you can redefine types and constants. You can't import the type names into `Main` and then expect to be able to redefine them there, but you can use the module name to resolve the scope. In other words, while developing you might use a workflow something like this:
```
include("mynewcode.jl") # this defines a module MyModule
obj1 = MyModule.ObjConstructor(a, b)
obj2 = MyModule.somefunction(obj1)
# Got an error. Change something in "mynewcode.jl"
include("mynewcode.jl") # reload the module
obj1 = MyModule.ObjConstructor(a, b) # old objects are no longer valid, must reconstruct
obj2 = MyModule.somefunction(obj1) # this time it worked!
obj3 = MyModule.someotherfunction(obj2, c)
...
```
[Scripting](#man-scripting)
----------------------------
###
[How do I check if the current file is being run as the main script?](#How-do-I-check-if-the-current-file-is-being-run-as-the-main-script?)
When a file is run as the main script using `julia file.jl` one might want to activate extra functionality like command line argument handling. A way to determine that a file is run in this fashion is to check if `abspath(PROGRAM_FILE) == @__FILE__` is `true`.
###
[How do I catch CTRL-C in a script?](#catch-ctrl-c)
Running a Julia script using `julia file.jl` does not throw [`InterruptException`](../../base/base/index#Core.InterruptException) when you try to terminate it with CTRL-C (SIGINT). To run a certain code before terminating a Julia script, which may or may not be caused by CTRL-C, use [`atexit`](../../base/base/index#Base.atexit). Alternatively, you can use `julia -e 'include(popfirst!(ARGS))' file.jl` to execute a script while being able to catch `InterruptException` in the [`try`](../../base/base/index#try) block.
###
[How do I pass options to `julia` using `#!/usr/bin/env`?](#How-do-I-pass-options-to-julia-using-#!/usr/bin/env?)
Passing options to `julia` in so-called shebang by, e.g., `#!/usr/bin/env julia --startup-file=no` may not work in some platforms such as Linux. This is because argument parsing in shebang is platform-dependent and not well-specified. In a Unix-like environment, a reliable way to pass options to `julia` in an executable script would be to start the script as a `bash` script and use `exec` to replace the process to `julia`:
```
#!/bin/bash
#=
exec julia --color=yes --startup-file=no "${BASH_SOURCE[0]}" "$@"
=#
@show ARGS # put any Julia code here
```
In the example above, the code between `#=` and `=#` is run as a `bash` script. Julia ignores this part since it is a multi-line comment for Julia. The Julia code after `=#` is ignored by `bash` since it stops parsing the file once it reaches to the `exec` statement.
In order to [catch CTRL-C](#catch-ctrl-c) in the script you can use
```
#!/bin/bash
#=
exec julia --color=yes --startup-file=no -e 'include(popfirst!(ARGS))' \
"${BASH_SOURCE[0]}" "$@"
=#
@show ARGS # put any Julia code here
```
instead. Note that with this strategy [`PROGRAM_FILE`](../../base/constants/index#Base.PROGRAM_FILE) will not be set.
###
[Why doesn't `run` support `*` or pipes for scripting external programs?](#Why-doesn't-run-support-*-or-pipes-for-scripting-external-programs?)
Julia's [`run`](../../base/base/index#Base.run) function launches external programs *directly*, without invoking an [operating-system shell](https://en.wikipedia.org/wiki/Shell_(computing)) (unlike the `system("...")` function in other languages like Python, R, or C). That means that `run` does not perform wildcard expansion of `*` (["globbing"](https://en.wikipedia.org/wiki/Glob_(programming))), nor does it interpret [shell pipelines](https://en.wikipedia.org/wiki/Pipeline_(Unix)) like `|` or `>`.
You can still do globbing and pipelines using Julia features, however. For example, the built-in [`pipeline`](#) function allows you to chain external programs and files, similar to shell pipes, and the [Glob.jl package](https://github.com/vtjnash/Glob.jl) implements POSIX-compatible globbing.
You can, of course, run programs through the shell by explicitly passing a shell and a command string to `run`, e.g. `run(`sh -c "ls > files.txt"`)` to use the Unix [Bourne shell](https://en.wikipedia.org/wiki/Bourne_shell), but you should generally prefer pure-Julia scripting like `run(pipeline(`ls`, "files.txt"))`. The reason why we avoid the shell by default is that [shelling out sucks](https://julialang.org/blog/2012/03/shelling-out-sucks/): launching processes via the shell is slow, fragile to quoting of special characters, has poor error handling, and is problematic for portability. (The Python developers came to a [similar conclusion](https://www.python.org/dev/peps/pep-0324/#motivation).)
[Variables and Assignments](#Variables-and-Assignments)
--------------------------------------------------------
###
[Why am I getting `UndefVarError` from a simple loop?](#Why-am-I-getting-UndefVarError-from-a-simple-loop?)
You might have something like:
```
x = 0
while x < 10
x += 1
end
```
and notice that it works fine in an interactive environment (like the Julia REPL), but gives `UndefVarError: x not defined` when you try to run it in script or other file. What is going on is that Julia generally requires you to **be explicit about assigning to global variables in a local scope**.
Here, `x` is a global variable, `while` defines a [local scope](../variables-and-scoping/index#scope-of-variables), and `x += 1` is an assignment to a global in that local scope.
As mentioned above, Julia (version 1.5 or later) allows you to omit the `global` keyword for code in the REPL (and many other interactive environments), to simplify exploration (e.g. copy-pasting code from a function to run interactively). However, once you move to code in files, Julia requires a more disciplined approach to global variables. You have least three options:
1. Put the code into a function (so that `x` is a *local* variable in a function). In general, it is good software engineering to use functions rather than global scripts (search online for "why global variables bad" to see many explanations). In Julia, global variables are also [slow](../performance-tips/index#man-performance-tips).
2. Wrap the code in a [`let`](../../base/base/index#let) block. (This makes `x` a local variable within the `let ... end` statement, again eliminating the need for `global`).
3. Explicitly mark `x` as `global` inside the local scope before assigning to it, e.g. write `global x += 1`.
More explanation can be found in the manual section [on soft scope](../variables-and-scoping/index#on-soft-scope).
[Functions](#Functions)
------------------------
###
[I passed an argument `x` to a function, modified it inside that function, but on the outside, the variable `x` is still unchanged. Why?](#I-passed-an-argument-x-to-a-function,-modified-it-inside-that-function,-but-on-the-outside,-the-variable-x-is-still-unchanged.-Why?)
Suppose you call a function like this:
```
julia> x = 10
10
julia> function change_value!(y)
y = 17
end
change_value! (generic function with 1 method)
julia> change_value!(x)
17
julia> x # x is unchanged!
10
```
In Julia, the binding of a variable `x` cannot be changed by passing `x` as an argument to a function. When calling `change_value!(x)` in the above example, `y` is a newly created variable, bound initially to the value of `x`, i.e. `10`; then `y` is rebound to the constant `17`, while the variable `x` of the outer scope is left untouched.
However, if `x` is bound to an object of type `Array` (or any other *mutable* type). From within the function, you cannot "unbind" `x` from this Array, but you *can* change its content. For example:
```
julia> x = [1,2,3]
3-element Vector{Int64}:
1
2
3
julia> function change_array!(A)
A[1] = 5
end
change_array! (generic function with 1 method)
julia> change_array!(x)
5
julia> x
3-element Vector{Int64}:
5
2
3
```
Here we created a function `change_array!`, that assigns `5` to the first element of the passed array (bound to `x` at the call site, and bound to `A` within the function). Notice that, after the function call, `x` is still bound to the same array, but the content of that array changed: the variables `A` and `x` were distinct bindings referring to the same mutable `Array` object.
###
[Can I use `using` or `import` inside a function?](#Can-I-use-using-or-import-inside-a-function?)
No, you are not allowed to have a `using` or `import` statement inside a function. If you want to import a module but only use its symbols inside a specific function or set of functions, you have two options:
1. Use `import`:
```
import Foo
function bar(...)
# ... refer to Foo symbols via Foo.baz ...
end
```
This loads the module `Foo` and defines a variable `Foo` that refers to the module, but does not import any of the other symbols from the module into the current namespace. You refer to the `Foo` symbols by their qualified names `Foo.bar` etc.
2. Wrap your function in a module:
```
module Bar
export bar
using Foo
function bar(...)
# ... refer to Foo.baz as simply baz ....
end
end
using Bar
```
This imports all the symbols from `Foo`, but only inside the module `Bar`.
###
[What does the `...` operator do?](#What-does-the-...-operator-do?)
####
[The two uses of the `...` operator: slurping and splatting](#The-two-uses-of-the-...-operator:-slurping-and-splatting)
Many newcomers to Julia find the use of `...` operator confusing. Part of what makes the `...` operator confusing is that it means two different things depending on context.
####
[`...` combines many arguments into one argument in function definitions](#...-combines-many-arguments-into-one-argument-in-function-definitions)
In the context of function definitions, the `...` operator is used to combine many different arguments into a single argument. This use of `...` for combining many different arguments into a single argument is called slurping:
```
julia> function printargs(args...)
println(typeof(args))
for (i, arg) in enumerate(args)
println("Arg #$i = $arg")
end
end
printargs (generic function with 1 method)
julia> printargs(1, 2, 3)
Tuple{Int64, Int64, Int64}
Arg #1 = 1
Arg #2 = 2
Arg #3 = 3
```
If Julia were a language that made more liberal use of ASCII characters, the slurping operator might have been written as `<-...` instead of `...`.
####
[`...` splits one argument into many different arguments in function calls](#...-splits-one-argument-into-many-different-arguments-in-function-calls)
In contrast to the use of the `...` operator to denote slurping many different arguments into one argument when defining a function, the `...` operator is also used to cause a single function argument to be split apart into many different arguments when used in the context of a function call. This use of `...` is called splatting:
```
julia> function threeargs(a, b, c)
println("a = $a::$(typeof(a))")
println("b = $b::$(typeof(b))")
println("c = $c::$(typeof(c))")
end
threeargs (generic function with 1 method)
julia> x = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> threeargs(x...)
a = 1::Int64
b = 2::Int64
c = 3::Int64
```
If Julia were a language that made more liberal use of ASCII characters, the splatting operator might have been written as `...->` instead of `...`.
###
[What is the return value of an assignment?](#What-is-the-return-value-of-an-assignment?)
The operator `=` always returns the right-hand side, therefore:
```
julia> function threeint()
x::Int = 3.0
x # returns variable x
end
threeint (generic function with 1 method)
julia> function threefloat()
x::Int = 3.0 # returns 3.0
end
threefloat (generic function with 1 method)
julia> threeint()
3
julia> threefloat()
3.0
```
and similarly:
```
julia> function twothreetup()
x, y = [2, 3] # assigns 2 to x and 3 to y
x, y # returns a tuple
end
twothreetup (generic function with 1 method)
julia> function twothreearr()
x, y = [2, 3] # returns an array
end
twothreearr (generic function with 1 method)
julia> twothreetup()
(2, 3)
julia> twothreearr()
2-element Vector{Int64}:
2
3
```
[Types, type declarations, and constructors](#Types,-type-declarations,-and-constructors)
------------------------------------------------------------------------------------------
###
[What does "type-stable" mean?](#man-type-stability)
It means that the type of the output is predictable from the types of the inputs. In particular, it means that the type of the output cannot vary depending on the *values* of the inputs. The following code is *not* type-stable:
```
julia> function unstable(flag::Bool)
if flag
return 1
else
return 1.0
end
end
unstable (generic function with 1 method)
```
It returns either an `Int` or a [`Float64`](../../base/numbers/index#Core.Float64) depending on the value of its argument. Since Julia can't predict the return type of this function at compile-time, any computation that uses it must be able to cope with values of both types, which makes it hard to produce fast machine code.
###
[Why does Julia give a `DomainError` for certain seemingly-sensible operations?](#faq-domain-errors)
Certain operations make mathematical sense but result in errors:
```
julia> sqrt(-2.0)
ERROR: DomainError with -2.0:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
```
This behavior is an inconvenient consequence of the requirement for type-stability. In the case of [`sqrt`](#), most users want `sqrt(2.0)` to give a real number, and would be unhappy if it produced the complex number `1.4142135623730951 + 0.0im`. One could write the [`sqrt`](#) function to switch to a complex-valued output only when passed a negative number (which is what [`sqrt`](#) does in some other languages), but then the result would not be [type-stable](#man-type-stability) and the [`sqrt`](#) function would have poor performance.
In these and other cases, you can get the result you want by choosing an *input type* that conveys your willingness to accept an *output type* in which the result can be represented:
```
julia> sqrt(-2.0+0im)
0.0 + 1.4142135623730951im
```
###
[How can I constrain or compute type parameters?](#How-can-I-constrain-or-compute-type-parameters?)
The parameters of a [parametric type](../types/index#Parametric-Types) can hold either types or bits values, and the type itself chooses how it makes use of these parameters. For example, `Array{Float64, 2}` is parameterized by the type `Float64` to express its element type and the integer value `2` to express its number of dimensions. When defining your own parametric type, you can use subtype constraints to declare that a certain parameter must be a subtype ([`<:`](#)) of some abstract type or a previous type parameter. There is not, however, a dedicated syntax to declare that a parameter must be a *value* of a given type — that is, you cannot directly declare that a dimensionality-like parameter [`isa`](../../base/base/index#Core.isa) `Int` within the `struct` definition, for example. Similarly, you cannot do computations (including simple things like addition or subtraction) on type parameters. Instead, these sorts of constraints and relationships may be expressed through additional type parameters that are computed and enforced within the type's [constructors](../constructors/index#man-constructors).
As an example, consider
```
struct ConstrainedType{T,N,N+1} # NOTE: INVALID SYNTAX
A::Array{T,N}
B::Array{T,N+1}
end
```
where the user would like to enforce that the third type parameter is always the second plus one. This can be implemented with an explicit type parameter that is checked by an [inner constructor method](../constructors/index#man-inner-constructor-methods) (where it can be combined with other checks):
```
struct ConstrainedType{T,N,M}
A::Array{T,N}
B::Array{T,M}
function ConstrainedType(A::Array{T,N}, B::Array{T,M}) where {T,N,M}
N + 1 == M || throw(ArgumentError("second argument should have one more axis" ))
new{T,N,M}(A, B)
end
end
```
This check is usually *costless*, as the compiler can elide the check for valid concrete types. If the second argument is also computed, it may be advantageous to provide an [outer constructor method](../constructors/index#man-outer-constructor-methods) that performs this calculation:
```
ConstrainedType(A) = ConstrainedType(A, compute_B(A))
```
###
[Why does Julia use native machine integer arithmetic?](#faq-integer-arithmetic)
Julia uses machine arithmetic for integer computations. This means that the range of `Int` values is bounded and wraps around at either end so that adding, subtracting and multiplying integers can overflow or underflow, leading to some results that can be unsettling at first:
```
julia> x = typemax(Int)
9223372036854775807
julia> y = x+1
-9223372036854775808
julia> z = -y
-9223372036854775808
julia> 2*z
0
```
Clearly, this is far from the way mathematical integers behave, and you might think it less than ideal for a high-level programming language to expose this to the user. For numerical work where efficiency and transparency are at a premium, however, the alternatives are worse.
One alternative to consider would be to check each integer operation for overflow and promote results to bigger integer types such as [`Int128`](../../base/numbers/index#Core.Int128) or [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) in the case of overflow. Unfortunately, this introduces major overhead on every integer operation (think incrementing a loop counter) – it requires emitting code to perform run-time overflow checks after arithmetic instructions and branches to handle potential overflows. Worse still, this would cause every computation involving integers to be type-unstable. As we mentioned above, [type-stability is crucial](#man-type-stability) for effective generation of efficient code. If you can't count on the results of integer operations being integers, it's impossible to generate fast, simple code the way C and Fortran compilers do.
A variation on this approach, which avoids the appearance of type instability is to merge the `Int` and [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) types into a single hybrid integer type, that internally changes representation when a result no longer fits into the size of a machine integer. While this superficially avoids type-instability at the level of Julia code, it just sweeps the problem under the rug by foisting all of the same difficulties onto the C code implementing this hybrid integer type. This approach *can* be made to work and can even be made quite fast in many cases, but has several drawbacks. One problem is that the in-memory representation of integers and arrays of integers no longer match the natural representation used by C, Fortran and other languages with native machine integers. Thus, to interoperate with those languages, we would ultimately need to introduce native integer types anyway. Any unbounded representation of integers cannot have a fixed number of bits, and thus cannot be stored inline in an array with fixed-size slots – large integer values will always require separate heap-allocated storage. And of course, no matter how clever a hybrid integer implementation one uses, there are always performance traps – situations where performance degrades unexpectedly. Complex representation, lack of interoperability with C and Fortran, the inability to represent integer arrays without additional heap storage, and unpredictable performance characteristics make even the cleverest hybrid integer implementations a poor choice for high-performance numerical work.
An alternative to using hybrid integers or promoting to BigInts is to use saturating integer arithmetic, where adding to the largest integer value leaves it unchanged and likewise for subtracting from the smallest integer value. This is precisely what Matlab™ does:
```
>> int64(9223372036854775807)
ans =
9223372036854775807
>> int64(9223372036854775807) + 1
ans =
9223372036854775807
>> int64(-9223372036854775808)
ans =
-9223372036854775808
>> int64(-9223372036854775808) - 1
ans =
-9223372036854775808
```
At first blush, this seems reasonable enough since 9223372036854775807 is much closer to 9223372036854775808 than -9223372036854775808 is and integers are still represented with a fixed size in a natural way that is compatible with C and Fortran. Saturated integer arithmetic, however, is deeply problematic. The first and most obvious issue is that this is not the way machine integer arithmetic works, so implementing saturated operations requires emitting instructions after each machine integer operation to check for underflow or overflow and replace the result with [`typemin(Int)`](../../base/base/index#Base.typemin) or [`typemax(Int)`](../../base/base/index#Base.typemax) as appropriate. This alone expands each integer operation from a single, fast instruction into half a dozen instructions, probably including branches. Ouch. But it gets worse – saturating integer arithmetic isn't associative. Consider this Matlab computation:
```
>> n = int64(2)^62
4611686018427387904
>> n + (n - 1)
9223372036854775807
>> (n + n) - 1
9223372036854775806
```
This makes it hard to write many basic integer algorithms since a lot of common techniques depend on the fact that machine addition with overflow *is* associative. Consider finding the midpoint between integer values `lo` and `hi` in Julia using the expression `(lo + hi) >>> 1`:
```
julia> n = 2^62
4611686018427387904
julia> (n + 2n) >>> 1
6917529027641081856
```
See? No problem. That's the correct midpoint between 2^62 and 2^63, despite the fact that `n + 2n` is -4611686018427387904. Now try it in Matlab:
```
>> (n + 2*n)/2
ans =
4611686018427387904
```
Oops. Adding a `>>>` operator to Matlab wouldn't help, because saturation that occurs when adding `n` and `2n` has already destroyed the information necessary to compute the correct midpoint.
Not only is lack of associativity unfortunate for programmers who cannot rely it for techniques like this, but it also defeats almost anything compilers might want to do to optimize integer arithmetic. For example, since Julia integers use normal machine integer arithmetic, LLVM is free to aggressively optimize simple little functions like `f(k) = 5k-1`. The machine code for this function is just this:
```
julia> code_native(f, Tuple{Int})
.text
Filename: none
pushq %rbp
movq %rsp, %rbp
Source line: 1
leaq -1(%rdi,%rdi,4), %rax
popq %rbp
retq
nopl (%rax,%rax)
```
The actual body of the function is a single `leaq` instruction, which computes the integer multiply and add at once. This is even more beneficial when `f` gets inlined into another function:
```
julia> function g(k, n)
for i = 1:n
k = f(k)
end
return k
end
g (generic function with 1 methods)
julia> code_native(g, Tuple{Int,Int})
.text
Filename: none
pushq %rbp
movq %rsp, %rbp
Source line: 2
testq %rsi, %rsi
jle L26
nopl (%rax)
Source line: 3
L16:
leaq -1(%rdi,%rdi,4), %rdi
Source line: 2
decq %rsi
jne L16
Source line: 5
L26:
movq %rdi, %rax
popq %rbp
retq
nop
```
Since the call to `f` gets inlined, the loop body ends up being just a single `leaq` instruction. Next, consider what happens if we make the number of loop iterations fixed:
```
julia> function g(k)
for i = 1:10
k = f(k)
end
return k
end
g (generic function with 2 methods)
julia> code_native(g,(Int,))
.text
Filename: none
pushq %rbp
movq %rsp, %rbp
Source line: 3
imulq $9765625, %rdi, %rax # imm = 0x9502F9
addq $-2441406, %rax # imm = 0xFFDABF42
Source line: 5
popq %rbp
retq
nopw %cs:(%rax,%rax)
```
Because the compiler knows that integer addition and multiplication are associative and that multiplication distributes over addition – neither of which is true of saturating arithmetic – it can optimize the entire loop down to just a multiply and an add. Saturated arithmetic completely defeats this kind of optimization since associativity and distributivity can fail at each loop iteration, causing different outcomes depending on which iteration the failure occurs in. The compiler can unroll the loop, but it cannot algebraically reduce multiple operations into fewer equivalent operations.
The most reasonable alternative to having integer arithmetic silently overflow is to do checked arithmetic everywhere, raising errors when adds, subtracts, and multiplies overflow, producing values that are not value-correct. In this [blog post](https://danluu.com/integer-overflow/), Dan Luu analyzes this and finds that rather than the trivial cost that this approach should in theory have, it ends up having a substantial cost due to compilers (LLVM and GCC) not gracefully optimizing around the added overflow checks. If this improves in the future, we could consider defaulting to checked integer arithmetic in Julia, but for now, we have to live with the possibility of overflow.
In the meantime, overflow-safe integer operations can be achieved through the use of external libraries such as [SaferIntegers.jl](https://github.com/JeffreySarnoff/SaferIntegers.jl). Note that, as stated previously, the use of these libraries significantly increases the execution time of code using the checked integer types. However, for limited usage, this is far less of an issue than if it were used for all integer operations. You can follow the status of the discussion [here](https://github.com/JuliaLang/julia/issues/855).
###
[What are the possible causes of an `UndefVarError` during remote execution?](#What-are-the-possible-causes-of-an-UndefVarError-during-remote-execution?)
As the error states, an immediate cause of an `UndefVarError` on a remote node is that a binding by that name does not exist. Let us explore some of the possible causes.
```
julia> module Foo
foo() = remotecall_fetch(x->x, 2, "Hello")
end
julia> Foo.foo()
ERROR: On worker 2:
UndefVarError: Foo not defined
Stacktrace:
[...]
```
The closure `x->x` carries a reference to `Foo`, and since `Foo` is unavailable on node 2, an `UndefVarError` is thrown.
Globals under modules other than `Main` are not serialized by value to the remote node. Only a reference is sent. Functions which create global bindings (except under `Main`) may cause an `UndefVarError` to be thrown later.
```
julia> @everywhere module Foo
function foo()
global gvar = "Hello"
remotecall_fetch(()->gvar, 2)
end
end
julia> Foo.foo()
ERROR: On worker 2:
UndefVarError: gvar not defined
Stacktrace:
[...]
```
In the above example, `@everywhere module Foo` defined `Foo` on all nodes. However the call to `Foo.foo()` created a new global binding `gvar` on the local node, but this was not found on node 2 resulting in an `UndefVarError` error.
Note that this does not apply to globals created under module `Main`. Globals under module `Main` are serialized and new bindings created under `Main` on the remote node.
```
julia> gvar_self = "Node1"
"Node1"
julia> remotecall_fetch(()->gvar_self, 2)
"Node1"
julia> remotecall_fetch(varinfo, 2)
name size summary
––––––––– –––––––– –––––––
Base Module
Core Module
Main Module
gvar_self 13 bytes String
```
This does not apply to `function` or `struct` declarations. However, anonymous functions bound to global variables are serialized as can be seen below.
```
julia> bar() = 1
bar (generic function with 1 method)
julia> remotecall_fetch(bar, 2)
ERROR: On worker 2:
UndefVarError: #bar not defined
[...]
julia> anon_bar = ()->1
(::#21) (generic function with 1 method)
julia> remotecall_fetch(anon_bar, 2)
1
```
[Troubleshooting "method not matched": parametric type invariance and `MethodError`s](#Troubleshooting-%22method-not-matched%22:-parametric-type-invariance-and-MethodErrors)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
###
[Why doesn't it work to declare `foo(bar::Vector{Real}) = 42` and then call `foo([1])`?](#Why-doesn't-it-work-to-declare-foo(bar::Vector%7BReal%7D)-42-and-then-call-foo(%5B1%5D)?)
As you'll see if you try this, the result is a `MethodError`:
```
julia> foo(x::Vector{Real}) = 42
foo (generic function with 1 method)
julia> foo([1])
ERROR: MethodError: no method matching foo(::Vector{Int64})
Closest candidates are:
foo(!Matched::Vector{Real}) at none:1
```
This is because `Vector{Real}` is not a supertype of `Vector{Int}`! You can solve this problem with something like `foo(bar::Vector{T}) where {T<:Real}` (or the short form `foo(bar::Vector{<:Real})` if the static parameter `T` is not needed in the body of the function). The `T` is a wild card: you first specify that it must be a subtype of Real, then specify the function takes a Vector of with elements of that type.
This same issue goes for any composite type `Comp`, not just `Vector`. If `Comp` has a parameter declared of type `Y`, then another type `Comp2` with a parameter of type `X<:Y` is not a subtype of `Comp`. This is type-invariance (by contrast, Tuple is type-covariant in its parameters). See [Parametric Composite Types](../types/index#man-parametric-composite-types) for more explanation of these.
###
[Why does Julia use `*` for string concatenation? Why not `+` or something else?](#Why-does-Julia-use-*-for-string-concatenation?-Why-not-or-something-else?)
The [main argument](../strings/index#man-concatenation) against `+` is that string concatenation is not commutative, while `+` is generally used as a commutative operator. While the Julia community recognizes that other languages use different operators and `*` may be unfamiliar for some users, it communicates certain algebraic properties.
Note that you can also use `string(...)` to concatenate strings (and other values converted to strings); similarly, `repeat` can be used instead of `^` to repeat strings. The [interpolation syntax](../strings/index#string-interpolation) is also useful for constructing strings.
[Packages and Modules](#Packages-and-Modules)
----------------------------------------------
###
[What is the difference between "using" and "import"?](#What-is-the-difference-between-%22using%22-and-%22import%22?)
There is only one difference, and on the surface (syntax-wise) it may seem very minor. The difference between `using` and `import` is that with `using` you need to say `function Foo.bar(..` to extend module Foo's function bar with a new method, but with `import Foo.bar`, you only need to say `function bar(...` and it automatically extends module Foo's function bar.
The reason this is important enough to have been given separate syntax is that you don't want to accidentally extend a function that you didn't know existed, because that could easily cause a bug. This is most likely to happen with a method that takes a common type like a string or integer, because both you and the other module could define a method to handle such a common type. If you use `import`, then you'll replace the other module's implementation of `bar(s::AbstractString)` with your new implementation, which could easily do something completely different (and break all/many future usages of the other functions in module Foo that depend on calling bar).
[Nothingness and missing values](#Nothingness-and-missing-values)
------------------------------------------------------------------
###
[How does "null", "nothingness" or "missingness" work in Julia?](#faq-nothing)
Unlike many languages (for example, C and Java), Julia objects cannot be "null" by default. When a reference (variable, object field, or array element) is uninitialized, accessing it will immediately throw an error. This situation can be detected using the [`isdefined`](../../base/base/index#Core.isdefined) or [`isassigned`](../../base/arrays/index#Base.isassigned) functions.
Some functions are used only for their side effects, and do not need to return a value. In these cases, the convention is to return the value `nothing`, which is just a singleton object of type `Nothing`. This is an ordinary type with no fields; there is nothing special about it except for this convention, and that the REPL does not print anything for it. Some language constructs that would not otherwise have a value also yield `nothing`, for example `if false; end`.
For situations where a value `x` of type `T` exists only sometimes, the `Union{T, Nothing}` type can be used for function arguments, object fields and array element types as the equivalent of [`Nullable`, `Option` or `Maybe`](https://en.wikipedia.org/wiki/Nullable_type) in other languages. If the value itself can be `nothing` (notably, when `T` is `Any`), the `Union{Some{T}, Nothing}` type is more appropriate since `x == nothing` then indicates the absence of a value, and `x == Some(nothing)` indicates the presence of a value equal to `nothing`. The [`something`](../../base/base/index#Base.something) function allows unwrapping `Some` objects and using a default value instead of `nothing` arguments. Note that the compiler is able to generate efficient code when working with `Union{T, Nothing}` arguments or fields.
To represent missing data in the statistical sense (`NA` in R or `NULL` in SQL), use the [`missing`](../../base/base/index#Base.missing) object. See the [`Missing Values`](../missing/index#missing) section for more details.
In some languages, the empty tuple (`()`) is considered the canonical form of nothingness. However, in julia it is best thought of as just a regular tuple that happens to contain zero values.
The empty (or "bottom") type, written as `Union{}` (an empty union type), is a type with no values and no subtypes (except itself). You will generally not need to use this type.
[Memory](#Memory)
------------------
###
[Why does `x += y` allocate memory when `x` and `y` are arrays?](#Why-does-x-y-allocate-memory-when-x-and-y-are-arrays?)
In Julia, `x += y` gets replaced during lowering by `x = x + y`. For arrays, this has the consequence that, rather than storing the result in the same location in memory as `x`, it allocates a new array to store the result. If you prefer to mutate `x`, use `x .+= y` to update each element individually.
While this behavior might surprise some, the choice is deliberate. The main reason is the presence of immutable objects within Julia, which cannot change their value once created. Indeed, a number is an immutable object; the statements `x = 5; x += 1` do not modify the meaning of `5`, they modify the value bound to `x`. For an immutable, the only way to change the value is to reassign it.
To amplify a bit further, consider the following function:
```
function power_by_squaring(x, n::Int)
ispow2(n) || error("This implementation only works for powers of 2")
while n >= 2
x *= x
n >>= 1
end
x
end
```
After a call like `x = 5; y = power_by_squaring(x, 4)`, you would get the expected result: `x == 5 && y == 625`. However, now suppose that `*=`, when used with matrices, instead mutated the left hand side. There would be two problems:
* For general square matrices, `A = A*B` cannot be implemented without temporary storage: `A[1,1]` gets computed and stored on the left hand side before you're done using it on the right hand side.
* Suppose you were willing to allocate a temporary for the computation (which would eliminate most of the point of making `*=` work in-place); if you took advantage of the mutability of `x`, then this function would behave differently for mutable vs. immutable inputs. In particular, for immutable `x`, after the call you'd have (in general) `y != x`, but for mutable `x` you'd have `y == x`.
Because supporting generic programming is deemed more important than potential performance optimizations that can be achieved by other means (e.g., using broadcasting or explicit loops), operators like `+=` and `*=` work by rebinding new values.
[Asynchronous IO and concurrent synchronous writes](#faq-async-io)
-------------------------------------------------------------------
###
[Why do concurrent writes to the same stream result in inter-mixed output?](#Why-do-concurrent-writes-to-the-same-stream-result-in-inter-mixed-output?)
While the streaming I/O API is synchronous, the underlying implementation is fully asynchronous.
Consider the printed output from the following:
```
julia> @sync for i in 1:3
@async write(stdout, string(i), " Foo ", " Bar ")
end
123 Foo Foo Foo Bar Bar Bar
```
This is happening because, while the `write` call is synchronous, the writing of each argument yields to other tasks while waiting for that part of the I/O to complete.
`print` and `println` "lock" the stream during a call. Consequently changing `write` to `println` in the above example results in:
```
julia> @sync for i in 1:3
@async println(stdout, string(i), " Foo ", " Bar ")
end
1 Foo Bar
2 Foo Bar
3 Foo Bar
```
You can lock your writes with a `ReentrantLock` like this:
```
julia> l = ReentrantLock();
julia> @sync for i in 1:3
@async begin
lock(l)
try
write(stdout, string(i), " Foo ", " Bar ")
finally
unlock(l)
end
end
end
1 Foo Bar 2 Foo Bar 3 Foo Bar
```
[Arrays](#Arrays)
------------------
###
[What are the differences between zero-dimensional arrays and scalars?](#faq-array-0dim)
Zero-dimensional arrays are arrays of the form `Array{T,0}`. They behave similar to scalars, but there are important differences. They deserve a special mention because they are a special case which makes logical sense given the generic definition of arrays, but might be a bit unintuitive at first. The following line defines a zero-dimensional array:
```
julia> A = zeros()
0-dimensional Array{Float64,0}:
0.0
```
In this example, `A` is a mutable container that contains one element, which can be set by `A[] = 1.0` and retrieved with `A[]`. All zero-dimensional arrays have the same size (`size(A) == ()`), and length (`length(A) == 1`). In particular, zero-dimensional arrays are not empty. If you find this unintuitive, here are some ideas that might help to understand Julia's definition.
* Zero-dimensional arrays are the "point" to vector's "line" and matrix's "plane". Just as a line has no area (but still represents a set of things), a point has no length or any dimensions at all (but still represents a thing).
* We define `prod(())` to be 1, and the total number of elements in an array is the product of the size. The size of a zero-dimensional array is `()`, and therefore its length is `1`.
* Zero-dimensional arrays don't natively have any dimensions into which you index – they’re just `A[]`. We can apply the same "trailing one" rule for them as for all other array dimensionalities, so you can indeed index them as `A[1]`, `A[1,1]`, etc; see [Omitted and extra indices](../arrays/index#Omitted-and-extra-indices).
It is also important to understand the differences to ordinary scalars. Scalars are not mutable containers (even though they are iterable and define things like `length`, `getindex`, *e.g.* `1[] == 1`). In particular, if `x = 0.0` is defined as a scalar, it is an error to attempt to change its value via `x[] = 1.0`. A scalar `x` can be converted into a zero-dimensional array containing it via `fill(x)`, and conversely, a zero-dimensional array `a` can be converted to the contained scalar via `a[]`. Another difference is that a scalar can participate in linear algebra operations such as `2 * rand(2,2)`, but the analogous operation with a zero-dimensional array `fill(2) * rand(2,2)` is an error.
###
[Why are my Julia benchmarks for linear algebra operations different from other languages?](#Why-are-my-Julia-benchmarks-for-linear-algebra-operations-different-from-other-languages?)
You may find that simple benchmarks of linear algebra building blocks like
```
using BenchmarkTools
A = randn(1000, 1000)
B = randn(1000, 1000)
@btime $A \ $B
@btime $A * $B
```
can be different when compared to other languages like Matlab or R.
Since operations like this are very thin wrappers over the relevant BLAS functions, the reason for the discrepancy is very likely to be
1. the BLAS library each language is using,
2. the number of concurrent threads.
Julia compiles and uses its own copy of OpenBLAS, with threads currently capped at `8` (or the number of your cores).
Modifying OpenBLAS settings or compiling Julia with a different BLAS library, eg [Intel MKL](https://software.intel.com/en-us/mkl), may provide performance improvements. You can use [MKL.jl](https://github.com/JuliaComputing/MKL.jl), a package that makes Julia's linear algebra use Intel MKL BLAS and LAPACK instead of OpenBLAS, or search the discussion forum for suggestions on how to set this up manually. Note that Intel MKL cannot be bundled with Julia, as it is not open source.
[Computing cluster](#Computing-cluster)
----------------------------------------
###
[How do I manage precompilation caches in distributed file systems?](#How-do-I-manage-precompilation-caches-in-distributed-file-systems?)
When using `julia` in high-performance computing (HPC) facilities, invoking *n* `julia` processes simultaneously creates at most *n* temporary copies of precompilation cache files. If this is an issue (slow and/or small distributed file system), you may:
1. Use `julia` with `--compiled-modules=no` flag to turn off precompilation.
2. Configure a private writable depot using `pushfirst!(DEPOT_PATH, private_path)` where `private_path` is a path unique to this `julia` process. This can also be done by setting environment variable `JULIA_DEPOT_PATH` to `$private_path:$HOME/.julia`.
3. Create a symlink from `~/.julia/compiled` to a directory in a scratch space.
[Julia Releases](#Julia-Releases)
----------------------------------
###
[Do I want to use the Stable, LTS, or nightly version of Julia?](#Do-I-want-to-use-the-Stable,-LTS,-or-nightly-version-of-Julia?)
The Stable version of Julia is the latest released version of Julia, this is the version most people will want to run. It has the latest features, including improved performance. The Stable version of Julia is versioned according to [SemVer](https://semver.org/) as v1.x.y. A new minor release of Julia corresponding to a new Stable version is made approximately every 4-5 months after a few weeks of testing as a release candidate. Unlike the LTS version the a Stable version will not normally receive bugfixes after another Stable version of Julia has been released. However, upgrading to the next Stable release will always be possible as each release of Julia v1.x will continue to run code written for earlier versions.
You may prefer the LTS (Long Term Support) version of Julia if you are looking for a very stable code base. The current LTS version of Julia is versioned according to SemVer as v1.0.x; this branch will continue to receive bugfixes until a new LTS branch is chosen, at which point the v1.0.x series will no longer received regular bug fixes and all but the most conservative users will be advised to upgrade to the new LTS version series. As a package developer, you may prefer to develop for the LTS version, to maximize the number of users who can use your package. As per SemVer, code written for v1.0 will continue to work for all future LTS and Stable versions. In general, even if targeting the LTS, one can develop and run code in the latest Stable version, to take advantage of the improved performance; so long as one avoids using new features (such as added library functions or new methods).
You may prefer the nightly version of Julia if you want to take advantage of the latest updates to the language, and don't mind if the version available today occasionally doesn't actually work. As the name implies, releases to the nightly version are made roughly every night (depending on build infrastructure stability). In general nightly released are fairly safe to use—your code will not catch on fire. However, they may be occasional regressions and or issues that will not be found until more thorough pre-release testing. You may wish to test against the nightly version to ensure that such regressions that affect your use case are caught before a release is made.
Finally, you may also consider building Julia from source for yourself. This option is mainly for those individuals who are comfortable at the command line, or interested in learning. If this describes you, you may also be interested in reading our [guidelines for contributing](https://github.com/JuliaLang/julia/blob/master/CONTRIBUTING.md).
Links to each of these download types can be found on the download page at <https://julialang.org/downloads/>. Note that not all versions of Julia are available for all platforms.
###
[How can I transfer the list of installed packages after updating my version of Julia?](#How-can-I-transfer-the-list-of-installed-packages-after-updating-my-version-of-Julia?)
Each minor version of julia has its own default [environment](https://docs.julialang.org/en/v1/manual/code-loading/#Environments-1). As a result, upon installing a new minor version of Julia, the packages you added using the previous minor version will not be available by default. The environment for a given julia version is defined by the files `Project.toml` and `Manifest.toml` in a folder matching the version number in `.julia/environments/`, for instance, `.julia/environments/v1.3`.
If you install a new minor version of Julia, say `1.4`, and want to use in its default environment the same packages as in a previous version (e.g. `1.3`), you can copy the contents of the file `Project.toml` from the `1.3` folder to `1.4`. Then, in a session of the new Julia version, enter the "package management mode" by typing the key `]`, and run the command [`instantiate`](https://julialang.github.io/Pkg.jl/v1/api/#Pkg.instantiate).
This operation will resolve a set of feasible packages from the copied file that are compatible with the target Julia version, and will install or update them if suitable. If you want to reproduce not only the set of packages, but also the versions you were using in the previous Julia version, you should also copy the `Manifest.toml` file before running the Pkg command `instantiate`. However, note that packages may define compatibility constraints that may be affected by changing the version of Julia, so the exact set of versions you had in `1.3` may not work for `1.4`.
| programming_docs |
julia Stack Traces Stack Traces
============
The `StackTraces` module provides simple stack traces that are both human readable and easy to use programmatically.
[Viewing a stack trace](#Viewing-a-stack-trace)
------------------------------------------------
The primary function used to obtain a stack trace is [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace):
```
6-element Array{Base.StackTraces.StackFrame,1}:
top-level scope
eval at boot.jl:317 [inlined]
eval(::Module, ::Expr) at REPL.jl:5
eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85
macro expansion at REPL.jl:116 [inlined]
(::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92
```
Calling [`stacktrace()`](../../base/stacktraces/index#Base.StackTraces.stacktrace) returns a vector of [`StackTraces.StackFrame`](../../base/stacktraces/index#Base.StackTraces.StackFrame) s. For ease of use, the alias [`StackTraces.StackTrace`](../../base/stacktraces/index#Base.StackTraces.StackTrace) can be used in place of `Vector{StackFrame}`. (Examples with `[...]` indicate that output may vary depending on how the code is run.)
```
julia> example() = stacktrace()
example (generic function with 1 method)
julia> example()
7-element Array{Base.StackTraces.StackFrame,1}:
example() at REPL[1]:1
top-level scope
eval at boot.jl:317 [inlined]
[...]
julia> @noinline child() = stacktrace()
child (generic function with 1 method)
julia> @noinline parent() = child()
parent (generic function with 1 method)
julia> grandparent() = parent()
grandparent (generic function with 1 method)
julia> grandparent()
9-element Array{Base.StackTraces.StackFrame,1}:
child() at REPL[3]:1
parent() at REPL[4]:1
grandparent() at REPL[5]:1
[...]
```
Note that when calling [`stacktrace()`](../../base/stacktraces/index#Base.StackTraces.stacktrace) you'll typically see a frame with `eval at boot.jl`. When calling [`stacktrace()`](../../base/stacktraces/index#Base.StackTraces.stacktrace) from the REPL you'll also have a few extra frames in the stack from `REPL.jl`, usually looking something like this:
```
julia> example() = stacktrace()
example (generic function with 1 method)
julia> example()
7-element Array{Base.StackTraces.StackFrame,1}:
example() at REPL[1]:1
top-level scope
eval at boot.jl:317 [inlined]
eval(::Module, ::Expr) at REPL.jl:5
eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85
macro expansion at REPL.jl:116 [inlined]
(::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92
```
[Extracting useful information](#Extracting-useful-information)
----------------------------------------------------------------
Each [`StackTraces.StackFrame`](../../base/stacktraces/index#Base.StackTraces.StackFrame) contains the function name, file name, line number, lambda info, a flag indicating whether the frame has been inlined, a flag indicating whether it is a C function (by default C functions do not appear in the stack trace), and an integer representation of the pointer returned by [`backtrace`](../../base/base/index#Base.backtrace):
```
julia> frame = stacktrace()[3]
eval(::Module, ::Expr) at REPL.jl:5
julia> frame.func
:eval
julia> frame.file
Symbol("~/julia/usr/share/julia/stdlib/v0.7/REPL/src/REPL.jl")
julia> frame.line
5
julia> frame.linfo
MethodInstance for eval(::Module, ::Expr)
julia> frame.inlined
false
julia> frame.from_c
false
julia> frame.pointer
0x00007f92d6293171
```
This makes stack trace information available programmatically for logging, error handling, and more.
[Error handling](#Error-handling)
----------------------------------
While having easy access to information about the current state of the callstack can be helpful in many places, the most obvious application is in error handling and debugging.
```
julia> @noinline bad_function() = undeclared_variable
bad_function (generic function with 1 method)
julia> @noinline example() = try
bad_function()
catch
stacktrace()
end
example (generic function with 1 method)
julia> example()
7-element Array{Base.StackTraces.StackFrame,1}:
example() at REPL[2]:4
top-level scope
eval at boot.jl:317 [inlined]
[...]
```
You may notice that in the example above the first stack frame points at line 4, where [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace) is called, rather than line 2, where *bad\_function* is called, and `bad_function`'s frame is missing entirely. This is understandable, given that [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace) is called from the context of the *catch*. While in this example it's fairly easy to find the actual source of the error, in complex cases tracking down the source of the error becomes nontrivial.
This can be remedied by passing the result of [`catch_backtrace`](../../base/base/index#Base.catch_backtrace) to [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace). Instead of returning callstack information for the current context, [`catch_backtrace`](../../base/base/index#Base.catch_backtrace) returns stack information for the context of the most recent exception:
```
julia> @noinline bad_function() = undeclared_variable
bad_function (generic function with 1 method)
julia> @noinline example() = try
bad_function()
catch
stacktrace(catch_backtrace())
end
example (generic function with 1 method)
julia> example()
8-element Array{Base.StackTraces.StackFrame,1}:
bad_function() at REPL[1]:1
example() at REPL[2]:2
[...]
```
Notice that the stack trace now indicates the appropriate line number and the missing frame.
```
julia> @noinline child() = error("Whoops!")
child (generic function with 1 method)
julia> @noinline parent() = child()
parent (generic function with 1 method)
julia> @noinline function grandparent()
try
parent()
catch err
println("ERROR: ", err.msg)
stacktrace(catch_backtrace())
end
end
grandparent (generic function with 1 method)
julia> grandparent()
ERROR: Whoops!
10-element Array{Base.StackTraces.StackFrame,1}:
error at error.jl:33 [inlined]
child() at REPL[1]:1
parent() at REPL[2]:1
grandparent() at REPL[3]:3
[...]
```
[Exception stacks and](#Exception-stacks-and-%5Bcurrent_exceptions%5D(@ref)) [`current_exceptions`](../../base/base/index#Base.current_exceptions)
---------------------------------------------------------------------------------------------------------------------------------------------------
Exception stacks requires at least Julia 1.1.
While handling an exception further exceptions may be thrown. It can be useful to inspect all these exceptions to identify the root cause of a problem. The julia runtime supports this by pushing each exception onto an internal *exception stack* as it occurs. When the code exits a `catch` normally, any exceptions which were pushed onto the stack in the associated `try` are considered to be successfully handled and are removed from the stack.
The stack of current exceptions can be accessed using the [`current_exceptions`](../../base/base/index#Base.current_exceptions) function. For example,
```
julia> try
error("(A) The root cause")
catch
try
error("(B) An exception while handling the exception")
catch
for (exc, bt) in current_exceptions()
showerror(stdout, exc, bt)
println(stdout)
end
end
end
(A) The root cause
Stacktrace:
[1] error(::String) at error.jl:33
[2] top-level scope at REPL[7]:2
[3] eval(::Module, ::Any) at boot.jl:319
[4] eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85
[5] macro expansion at REPL.jl:117 [inlined]
[6] (::getfield(REPL, Symbol("##26#27")){REPL.REPLBackend})() at task.jl:259
(B) An exception while handling the exception
Stacktrace:
[1] error(::String) at error.jl:33
[2] top-level scope at REPL[7]:5
[3] eval(::Module, ::Any) at boot.jl:319
[4] eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85
[5] macro expansion at REPL.jl:117 [inlined]
[6] (::getfield(REPL, Symbol("##26#27")){REPL.REPLBackend})() at task.jl:259
```
In this example the root cause exception (A) is first on the stack, with a further exception (B) following it. After exiting both catch blocks normally (i.e., without throwing a further exception) all exceptions are removed from the stack and are no longer accessible.
The exception stack is stored on the `Task` where the exceptions occurred. When a task fails with uncaught exceptions, `current_exceptions(task)` may be used to inspect the exception stack for that task.
[Comparison with](#Comparison-with-%5Bbacktrace%5D(@ref)) [`backtrace`](../../base/base/index#Base.backtrace)
--------------------------------------------------------------------------------------------------------------
A call to [`backtrace`](../../base/base/index#Base.backtrace) returns a vector of `Union{Ptr{Nothing}, Base.InterpreterIP}`, which may then be passed into [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace) for translation:
```
julia> trace = backtrace()
18-element Array{Union{Ptr{Nothing}, Base.InterpreterIP},1}:
Ptr{Nothing} @0x00007fd8734c6209
Ptr{Nothing} @0x00007fd87362b342
Ptr{Nothing} @0x00007fd87362c136
Ptr{Nothing} @0x00007fd87362c986
Ptr{Nothing} @0x00007fd87362d089
Base.InterpreterIP(CodeInfo(:(begin
Core.SSAValue(0) = backtrace()
trace = Core.SSAValue(0)
return Core.SSAValue(0)
end)), 0x0000000000000000)
Ptr{Nothing} @0x00007fd87362e4cf
[...]
julia> stacktrace(trace)
6-element Array{Base.StackTraces.StackFrame,1}:
top-level scope
eval at boot.jl:317 [inlined]
eval(::Module, ::Expr) at REPL.jl:5
eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85
macro expansion at REPL.jl:116 [inlined]
(::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92
```
Notice that the vector returned by [`backtrace`](../../base/base/index#Base.backtrace) had 18 elements, while the vector returned by [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace) only has 6. This is because, by default, [`stacktrace`](../../base/stacktraces/index#Base.StackTraces.stacktrace) removes any lower-level C functions from the stack. If you want to include stack frames from C calls, you can do it like this:
```
julia> stacktrace(trace, true)
21-element Array{Base.StackTraces.StackFrame,1}:
jl_apply_generic at gf.c:2167
do_call at interpreter.c:324
eval_value at interpreter.c:416
eval_body at interpreter.c:559
jl_interpret_toplevel_thunk_callback at interpreter.c:798
top-level scope
jl_interpret_toplevel_thunk at interpreter.c:807
jl_toplevel_eval_flex at toplevel.c:856
jl_toplevel_eval_in at builtins.c:624
eval at boot.jl:317 [inlined]
eval(::Module, ::Expr) at REPL.jl:5
jl_apply_generic at gf.c:2167
eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85
jl_apply_generic at gf.c:2167
macro expansion at REPL.jl:116 [inlined]
(::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92
jl_fptr_trampoline at gf.c:1838
jl_apply_generic at gf.c:2167
jl_apply at julia.h:1540 [inlined]
start_task at task.c:268
ip:0xffffffffffffffff
```
Individual pointers returned by [`backtrace`](../../base/base/index#Base.backtrace) can be translated into [`StackTraces.StackFrame`](../../base/stacktraces/index#Base.StackTraces.StackFrame) s by passing them into [`StackTraces.lookup`](../../base/stacktraces/index#Base.StackTraces.lookup):
```
julia> pointer = backtrace()[1];
julia> frame = StackTraces.lookup(pointer)
1-element Array{Base.StackTraces.StackFrame,1}:
jl_apply_generic at gf.c:2167
julia> println("The top frame is from $(frame[1].func)!")
The top frame is from jl_apply_generic!
```
julia Embedding Julia Embedding Julia
===============
As we have seen in [Calling C and Fortran Code](../calling-c-and-fortran-code/index#Calling-C-and-Fortran-Code), Julia has a simple and efficient way to call functions written in C. But there are situations where the opposite is needed: calling Julia function from C code. This can be used to integrate Julia code into a larger C/C++ project, without the need to rewrite everything in C/C++. Julia has a C API to make this possible. As almost all programming languages have some way to call C functions, the Julia C API can also be used to build further language bridges (e.g. calling Julia from Python or C#).
[High-Level Embedding](#High-Level-Embedding)
----------------------------------------------
**Note**: This section covers embedding Julia code in C on Unix-like operating systems. For doing this on Windows, please see the section following this.
We start with a simple C program that initializes Julia and calls some Julia code:
```
#include <julia.h>
JULIA_DEFINE_FAST_TLS // only define this once, in an executable (not in a shared library) if you want fast code.
int main(int argc, char *argv[])
{
/* required: setup the Julia context */
jl_init();
/* run Julia commands */
jl_eval_string("print(sqrt(2.0))");
/* strongly recommended: notify Julia that the
program is about to terminate. this allows
Julia time to cleanup pending write requests
and run all finalizers
*/
jl_atexit_hook(0);
return 0;
}
```
In order to build this program you have to put the path to the Julia header into the include path and link against `libjulia`. For instance, when Julia is installed to `$JULIA_DIR`, one can compile the above test program `test.c` with `gcc` using:
```
gcc -o test -fPIC -I$JULIA_DIR/include/julia -L$JULIA_DIR/lib -Wl,-rpath,$JULIA_DIR/lib test.c -ljulia
```
Alternatively, look at the `embedding.c` program in the Julia source tree in the `test/embedding/` folder. The file `cli/loader_exe.c` program is another simple example of how to set `jl_options` options while linking against `libjulia`.
The first thing that has to be done before calling any other Julia C function is to initialize Julia. This is done by calling `jl_init`, which tries to automatically determine Julia's install location. If you need to specify a custom location, or specify which system image to load, use `jl_init_with_image` instead.
The second statement in the test program evaluates a Julia statement using a call to `jl_eval_string`.
Before the program terminates, it is strongly recommended to call `jl_atexit_hook`. The above example program calls this before returning from `main`.
Currently, dynamically linking with the `libjulia` shared library requires passing the `RTLD_GLOBAL` option. In Python, this looks like:
```
>>> julia=CDLL('./libjulia.dylib',RTLD_GLOBAL)
>>> julia.jl_init.argtypes = []
>>> julia.jl_init()
250593296
```
If the julia program needs to access symbols from the main executable, it may be necessary to add `-Wl,--export-dynamic` linker flag at compile time on Linux in addition to the ones generated by `julia-config.jl` described below. This is not necessary when compiling a shared library.
###
[Using julia-config to automatically determine build parameters](#Using-julia-config-to-automatically-determine-build-parameters)
The script `julia-config.jl` was created to aid in determining what build parameters are required by a program that uses embedded Julia. This script uses the build parameters and system configuration of the particular Julia distribution it is invoked by to export the necessary compiler flags for an embedding program to interact with that distribution. This script is located in the Julia shared data directory.
####
[Example](#Example)
```
#include <julia.h>
int main(int argc, char *argv[])
{
jl_init();
(void)jl_eval_string("println(sqrt(2.0))");
jl_atexit_hook(0);
return 0;
}
```
####
[On the command line](#On-the-command-line)
A simple use of this script is from the command line. Assuming that `julia-config.jl` is located in `/usr/local/julia/share/julia`, it can be invoked on the command line directly and takes any combination of 3 flags:
```
/usr/local/julia/share/julia/julia-config.jl
Usage: julia-config [--cflags|--ldflags|--ldlibs]
```
If the above example source is saved in the file `embed_example.c`, then the following command will compile it into a running program on Linux and Windows (MSYS2 environment), or if on OS/X, then substitute `clang` for `gcc`.:
```
/usr/local/julia/share/julia/julia-config.jl --cflags --ldflags --ldlibs | xargs gcc embed_example.c
```
####
[Use in Makefiles](#Use-in-Makefiles)
But in general, embedding projects will be more complicated than the above, and so the following allows general makefile support as well – assuming GNU make because of the use of the **shell** macro expansions. Additionally, though many times `julia-config.jl` may be found in the directory `/usr/local`, this is not necessarily the case, but Julia can be used to locate `julia-config.jl` too, and the makefile can be used to take advantage of that. The above example is extended to use a Makefile:
```
JL_SHARE = $(shell julia -e 'print(joinpath(Sys.BINDIR, Base.DATAROOTDIR, "julia"))')
CFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags)
CXXFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags)
LDFLAGS += $(shell $(JL_SHARE)/julia-config.jl --ldflags)
LDLIBS += $(shell $(JL_SHARE)/julia-config.jl --ldlibs)
all: embed_example
```
Now the build command is simply `make`.
[High-Level Embedding on Windows with Visual Studio](#High-Level-Embedding-on-Windows-with-Visual-Studio)
----------------------------------------------------------------------------------------------------------
If the `JULIA_DIR` environment variable hasn't been setup, add it using the System panel before starting Visual Studio. The `bin` folder under JULIA\_DIR should be on the system PATH.
We start by opening Visual Studio and creating a new Console Application project. To the 'stdafx.h' header file, add the following lines at the end:
```
#include <julia.h>
```
Then, replace the main() function in the project with this code:
```
int main(int argc, char *argv[])
{
/* required: setup the Julia context */
jl_init();
/* run Julia commands */
jl_eval_string("print(sqrt(2.0))");
/* strongly recommended: notify Julia that the
program is about to terminate. this allows
Julia time to cleanup pending write requests
and run all finalizers
*/
jl_atexit_hook(0);
return 0;
}
```
The next step is to set up the project to find the Julia include files and the libraries. It's important to know whether the Julia installation is 32- or 64-bits. Remove any platform configuration that doesn't correspond to the Julia installation before proceeding.
Using the project Properties dialog, go to `C/C++` | `General` and add `$(JULIA_DIR)\include\julia\` to the Additional Include Directories property. Then, go to the `Linker` | `General` section and add `$(JULIA_DIR)\lib` to the Additional Library Directories property. Finally, under `Linker` | `Input`, add `libjulia.dll.a;libopenlibm.dll.a;` to the list of libraries.
At this point, the project should build and run.
[Converting Types](#Converting-Types)
--------------------------------------
Real applications will not just need to execute expressions, but also return their values to the host program. `jl_eval_string` returns a `jl_value_t*`, which is a pointer to a heap-allocated Julia object. Storing simple data types like [`Float64`](../../base/numbers/index#Core.Float64) in this way is called `boxing`, and extracting the stored primitive data is called `unboxing`. Our improved sample program that calculates the square root of 2 in Julia and reads back the result in C looks as follows:
```
jl_value_t *ret = jl_eval_string("sqrt(2.0)");
if (jl_typeis(ret, jl_float64_type)) {
double ret_unboxed = jl_unbox_float64(ret);
printf("sqrt(2.0) in C: %e \n", ret_unboxed);
}
else {
printf("ERROR: unexpected return type from sqrt(::Float64)\n");
}
```
In order to check whether `ret` is of a specific Julia type, we can use the `jl_isa`, `jl_typeis`, or `jl_is_...` functions. By typing `typeof(sqrt(2.0))` into the Julia shell we can see that the return type is [`Float64`](../../base/numbers/index#Core.Float64) (`double` in C). To convert the boxed Julia value into a C double the `jl_unbox_float64` function is used in the above code snippet.
Corresponding `jl_box_...` functions are used to convert the other way:
```
jl_value_t *a = jl_box_float64(3.0);
jl_value_t *b = jl_box_float32(3.0f);
jl_value_t *c = jl_box_int32(3);
```
As we will see next, boxing is required to call Julia functions with specific arguments.
[Calling Julia Functions](#Calling-Julia-Functions)
----------------------------------------------------
While `jl_eval_string` allows C to obtain the result of a Julia expression, it does not allow passing arguments computed in C to Julia. For this you will need to invoke Julia functions directly, using `jl_call`:
```
jl_function_t *func = jl_get_function(jl_base_module, "sqrt");
jl_value_t *argument = jl_box_float64(2.0);
jl_value_t *ret = jl_call1(func, argument);
```
In the first step, a handle to the Julia function `sqrt` is retrieved by calling `jl_get_function`. The first argument passed to `jl_get_function` is a pointer to the `Base` module in which `sqrt` is defined. Then, the double value is boxed using `jl_box_float64`. Finally, in the last step, the function is called using `jl_call1`. `jl_call0`, `jl_call2`, and `jl_call3` functions also exist, to conveniently handle different numbers of arguments. To pass more arguments, use `jl_call`:
```
jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs)
```
Its second argument `args` is an array of `jl_value_t*` arguments and `nargs` is the number of arguments.
[Memory Management](#Memory-Management)
----------------------------------------
As we have seen, Julia objects are represented in C as pointers. This raises the question of who is responsible for freeing these objects.
Typically, Julia objects are freed by a garbage collector (GC), but the GC does not automatically know that we are holding a reference to a Julia value from C. This means the GC can free objects out from under you, rendering pointers invalid.
The GC can only run when Julia objects are allocated. Calls like `jl_box_float64` perform allocation, and allocation might also happen at any point in running Julia code. However, it is generally safe to use pointers in between `jl_...` calls. But in order to make sure that values can survive `jl_...` calls, we have to tell Julia that we still hold a reference to Julia [root](https://www.cs.purdue.edu/homes/hosking/690M/p611-fenichel.pdf) values, a process called "GC rooting". Rooting a value will ensure that the garbage collector does not accidentally identify this value as unused and free the memory backing that value. This can be done using the `JL_GC_PUSH` macros:
```
jl_value_t *ret = jl_eval_string("sqrt(2.0)");
JL_GC_PUSH1(&ret);
// Do something with ret
JL_GC_POP();
```
The `JL_GC_POP` call releases the references established by the previous `JL_GC_PUSH`. Note that `JL_GC_PUSH` stores references on the C stack, so it must be exactly paired with a `JL_GC_POP` before the scope is exited. That is, before the function returns, or control flow otherwise leaves the block in which the `JL_GC_PUSH` was invoked.
Several Julia values can be pushed at once using the `JL_GC_PUSH2` , `JL_GC_PUSH3` , `JL_GC_PUSH4` , `JL_GC_PUSH5` , and `JL_GC_PUSH6` macros. To push an array of Julia values one can use the `JL_GC_PUSHARGS` macro, which can be used as follows:
```
jl_value_t **args;
JL_GC_PUSHARGS(args, 2); // args can now hold 2 `jl_value_t*` objects
args[0] = some_value;
args[1] = some_other_value;
// Do something with args (e.g. call jl_... functions)
JL_GC_POP();
```
Each scope must have only one call to `JL_GC_PUSH*`. Hence, if all variables cannot be pushed once by a single call to `JL_GC_PUSH*`, or if there are more than 6 variables to be pushed and using an array of arguments is not an option, then one can use inner blocks:
```
jl_value_t *ret1 = jl_eval_string("sqrt(2.0)");
JL_GC_PUSH1(&ret1);
jl_value_t *ret2 = 0;
{
jl_function_t *func = jl_get_function(jl_base_module, "exp");
ret2 = jl_call1(func, ret1);
JL_GC_PUSH1(&ret2);
// Do something with ret2.
JL_GC_POP(); // This pops ret2.
}
JL_GC_POP(); // This pops ret1.
```
If it is required to hold the pointer to a variable between functions (or block scopes), then it is not possible to use `JL_GC_PUSH*`. In this case, it is necessary to create and keep a reference to the variable in the Julia global scope. One simple way to accomplish this is to use a global `IdDict` that will hold the references, avoiding deallocation by the GC. However, this method will only work properly with mutable types.
```
// This functions shall be executed only once, during the initialization.
jl_value_t* refs = jl_eval_string("refs = IdDict()");
jl_function_t* setindex = jl_get_function(jl_base_module, "setindex!");
...
// `var` is the variable we want to protect between function calls.
jl_value_t* var = 0;
...
// `var` is a `Vector{Float64}`, which is mutable.
var = jl_eval_string("[sqrt(2.0); sqrt(4.0); sqrt(6.0)]");
// To protect `var`, add its reference to `refs`.
jl_call3(setindex, refs, var, var);
```
If the variable is immutable, then it needs to be wrapped in an equivalent mutable container or, preferably, in a `RefValue{Any}` before it is pushed to `IdDict`. In this approach, the container has to be created or filled in via C code using, for example, the function `jl_new_struct`. If the container is created by `jl_call*`, then you will need to reload the pointer to be used in C code.
```
// This functions shall be executed only once, during the initialization.
jl_value_t* refs = jl_eval_string("refs = IdDict()");
jl_function_t* setindex = jl_get_function(jl_base_module, "setindex!");
jl_datatype_t* reft = (jl_datatype_t*)jl_eval_string("Base.RefValue{Any}");
...
// `var` is the variable we want to protect between function calls.
jl_value_t* var = 0;
...
// `var` is a `Float64`, which is immutable.
var = jl_eval_string("sqrt(2.0)");
// Protect `var` until we add its reference to `refs`.
JL_GC_PUSH1(&var);
// Wrap `var` in `RefValue{Any}` and push to `refs` to protect it.
jl_value_t* rvar = jl_new_struct(reft, var);
JL_GC_POP();
jl_call3(setindex, refs, rvar, rvar);
```
The GC can be allowed to deallocate a variable by removing the reference to it from `refs` using the function `delete!`, provided that no other reference to the variable is kept anywhere:
```
jl_function_t* delete = jl_get_function(jl_base_module, "delete!");
jl_call2(delete, refs, rvar);
```
As an alternative for very simple cases, it is possible to just create a global container of type `Vector{Any}` and fetch the elements from that when necessary, or even to create one global variable per pointer using
```
jl_set_global(jl_main_module, jl_symbol("var"), var);
```
###
[Updating fields of GC-managed objects](#Updating-fields-of-GC-managed-objects)
The garbage collector operates under the assumption that it is aware of every old-generation object pointing to a young-generation one. Any time a pointer is updated breaking that assumption, it must be signaled to the collector with the `jl_gc_wb` (write barrier) function like so:
```
jl_value_t *parent = some_old_value, *child = some_young_value;
((some_specific_type*)parent)->field = child;
jl_gc_wb(parent, child);
```
It is in general impossible to predict which values will be old at runtime, so the write barrier must be inserted after all explicit stores. One notable exception is if the `parent` object was just allocated and garbage collection was not run since then. Remember that most `jl_...` functions can sometimes invoke garbage collection.
The write barrier is also necessary for arrays of pointers when updating their data directly. For example:
```
jl_array_t *some_array = ...; // e.g. a Vector{Any}
void **data = (void**)jl_array_data(some_array);
jl_value_t *some_value = ...;
data[0] = some_value;
jl_gc_wb(some_array, some_value);
```
###
[Manipulating the Garbage Collector](#Manipulating-the-Garbage-Collector)
There are some functions to control the GC. In normal use cases, these should not be necessary.
| Function | Description |
| --- | --- |
| `jl_gc_collect()` | Force a GC run |
| `jl_gc_enable(0)` | Disable the GC, return previous state as int |
| `jl_gc_enable(1)` | Enable the GC, return previous state as int |
| `jl_gc_is_enabled()` | Return current state as int |
[Working with Arrays](#Working-with-Arrays)
--------------------------------------------
Julia and C can share array data without copying. The next example will show how this works.
Julia arrays are represented in C by the datatype `jl_array_t*`. Basically, `jl_array_t` is a struct that contains:
* Information about the datatype
* A pointer to the data block
* Information about the sizes of the array
To keep things simple, we start with a 1D array. Creating an array containing Float64 elements of length 10 is done by:
```
jl_value_t* array_type = jl_apply_array_type((jl_value_t*)jl_float64_type, 1);
jl_array_t* x = jl_alloc_array_1d(array_type, 10);
```
Alternatively, if you have already allocated the array you can generate a thin wrapper around its data:
```
double *existingArray = (double*)malloc(sizeof(double)*10);
jl_array_t *x = jl_ptr_to_array_1d(array_type, existingArray, 10, 0);
```
The last argument is a boolean indicating whether Julia should take ownership of the data. If this argument is non-zero, the GC will call `free` on the data pointer when the array is no longer referenced.
In order to access the data of x, we can use `jl_array_data`:
```
double *xData = (double*)jl_array_data(x);
```
Now we can fill the array:
```
for(size_t i=0; i<jl_array_len(x); i++)
xData[i] = i;
```
Now let us call a Julia function that performs an in-place operation on `x`:
```
jl_function_t *func = jl_get_function(jl_base_module, "reverse!");
jl_call1(func, (jl_value_t*)x);
```
By printing the array, one can verify that the elements of `x` are now reversed.
###
[Accessing Returned Arrays](#Accessing-Returned-Arrays)
If a Julia function returns an array, the return value of `jl_eval_string` and `jl_call` can be cast to a `jl_array_t*`:
```
jl_function_t *func = jl_get_function(jl_base_module, "reverse");
jl_array_t *y = (jl_array_t*)jl_call1(func, (jl_value_t*)x);
```
Now the content of `y` can be accessed as before using `jl_array_data`. As always, be sure to keep a reference to the array while it is in use.
###
[Multidimensional Arrays](#Multidimensional-Arrays)
Julia's multidimensional arrays are stored in memory in column-major order. Here is some code that creates a 2D array and accesses its properties:
```
// Create 2D array of float64 type
jl_value_t *array_type = jl_apply_array_type(jl_float64_type, 2);
jl_array_t *x = jl_alloc_array_2d(array_type, 10, 5);
// Get array pointer
double *p = (double*)jl_array_data(x);
// Get number of dimensions
int ndims = jl_array_ndims(x);
// Get the size of the i-th dim
size_t size0 = jl_array_dim(x,0);
size_t size1 = jl_array_dim(x,1);
// Fill array with data
for(size_t i=0; i<size1; i++)
for(size_t j=0; j<size0; j++)
p[j + size0*i] = i + j;
```
Notice that while Julia arrays use 1-based indexing, the C API uses 0-based indexing (for example in calling `jl_array_dim`) in order to read as idiomatic C code.
[Exceptions](#Exceptions)
--------------------------
Julia code can throw exceptions. For example, consider:
```
jl_eval_string("this_function_does_not_exist()");
```
This call will appear to do nothing. However, it is possible to check whether an exception was thrown:
```
if (jl_exception_occurred())
printf("%s \n", jl_typeof_str(jl_exception_occurred()));
```
If you are using the Julia C API from a language that supports exceptions (e.g. Python, C#, C++), it makes sense to wrap each call into `libjulia` with a function that checks whether an exception was thrown, and then rethrows the exception in the host language.
###
[Throwing Julia Exceptions](#Throwing-Julia-Exceptions)
When writing Julia callable functions, it might be necessary to validate arguments and throw exceptions to indicate errors. A typical type check looks like:
```
if (!jl_typeis(val, jl_float64_type)) {
jl_type_error(function_name, (jl_value_t*)jl_float64_type, val);
}
```
General exceptions can be raised using the functions:
```
void jl_error(const char *str);
void jl_errorf(const char *fmt, ...);
```
`jl_error` takes a C string, and `jl_errorf` is called like `printf`:
```
jl_errorf("argument x = %d is too large", x);
```
where in this example `x` is assumed to be an integer.
| programming_docs |
julia Parallel Computing Parallel Computing
==================
Julia supports these four categories of concurrent and parallel programming:
1. **Asynchronous "tasks", or coroutines**:
Julia Tasks allow suspending and resuming computations for I/O, event handling, producer-consumer processes, and similar patterns. Tasks can synchronize through operations like [`wait`](../../base/parallel/index#Base.wait) and [`fetch`](#), and communicate via [`Channel`](../../base/parallel/index#Base.Channel)s. While strictly not parallel computing by themselves, Julia lets you schedule [`Task`](../../base/parallel/index#Core.Task)s on several threads.
2. **Multi-threading**:
Julia's [multi-threading](../multi-threading/index#man-multithreading) provides the ability to schedule Tasks simultaneously on more than one thread or CPU core, sharing memory. This is usually the easiest way to get parallelism on one's PC or on a single large multi-core server. Julia's multi-threading is composable. When one multi-threaded function calls another multi-threaded function, Julia will schedule all the threads globally on available resources, without oversubscribing.
3. **Distributed computing**:
Distributed computing runs multiple Julia processes with separate memory spaces. These can be on the same computer or multiple computers. The [`Distributed`](../../stdlib/distributed/index#man-distributed) standard library provides the capability for remote execution of a Julia function. With this basic building block, it is possible to build many different kinds of distributed computing abstractions. Packages like [`DistributedArrays.jl`](https://github.com/JuliaParallel/DistributedArrays.jl) are an example of such an abstraction. On the other hand, packages like [`MPI.jl`](https://github.com/JuliaParallel/MPI.jl) and [`Elemental.jl`](https://github.com/JuliaParallel/Elemental.jl) provide access to the existing MPI ecosystem of libraries.
4. **GPU computing**:
The Julia GPU compiler provides the ability to run Julia code natively on GPUs. There is a rich ecosystem of Julia packages that target GPUs. The [JuliaGPU.org](https://juliagpu.org) website provides a list of capabilities, supported GPUs, related packages and documentation.
julia Missing Values Missing Values
==============
Julia provides support for representing missing values in the statistical sense. This is for situations where no value is available for a variable in an observation, but a valid value theoretically exists. Missing values are represented via the [`missing`](../../base/base/index#Base.missing) object, which is the singleton instance of the type [`Missing`](../../base/base/index#Base.Missing). `missing` is equivalent to [`NULL` in SQL](https://en.wikipedia.org/wiki/NULL_(SQL)) and [`NA` in R](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#NA-handling), and behaves like them in most situations.
[Propagation of Missing Values](#Propagation-of-Missing-Values)
----------------------------------------------------------------
`missing` values *propagate* automatically when passed to standard mathematical operators and functions. For these functions, uncertainty about the value of one of the operands induces uncertainty about the result. In practice, this means a math operation involving a `missing` value generally returns `missing`:
```
julia> missing + 1
missing
julia> "a" * missing
missing
julia> abs(missing)
missing
```
Since `missing` is a normal Julia object, this propagation rule only works for functions which have opted in to implement this behavior. This can be achieved by:
* adding a specific method defined for arguments of type `Missing`,
* accepting arguments of this type, and passing them to functions which propagate them (like standard math operators).
Packages should consider whether it makes sense to propagate missing values when defining new functions, and define methods appropriately if this is the case. Passing a `missing` value to a function which does not have a method accepting arguments of type `Missing` throws a [`MethodError`](../../base/base/index#Core.MethodError), just like for any other type.
Functions that do not propagate `missing` values can be made to do so by wrapping them in the `passmissing` function provided by the [Missings.jl](https://github.com/JuliaData/Missings.jl) package. For example, `f(x)` becomes `passmissing(f)(x)`.
[Equality and Comparison Operators](#Equality-and-Comparison-Operators)
------------------------------------------------------------------------
Standard equality and comparison operators follow the propagation rule presented above: if any of the operands is `missing`, the result is `missing`. Here are a few examples:
```
julia> missing == 1
missing
julia> missing == missing
missing
julia> missing < 1
missing
julia> 2 >= missing
missing
```
In particular, note that `missing == missing` returns `missing`, so `==` cannot be used to test whether a value is missing. To test whether `x` is `missing`, use [`ismissing(x)`](../../base/base/index#Base.ismissing).
Special comparison operators [`isequal`](../../base/base/index#Base.isequal) and [`===`](../../base/base/index#Core.:===) are exceptions to the propagation rule. They will always return a `Bool` value, even in the presence of `missing` values, considering `missing` as equal to `missing` and as different from any other value. They can therefore be used to test whether a value is `missing`:
```
julia> missing === 1
false
julia> isequal(missing, 1)
false
julia> missing === missing
true
julia> isequal(missing, missing)
true
```
The [`isless`](../../base/base/index#Base.isless) operator is another exception: `missing` is considered as greater than any other value. This operator is used by [`sort`](../../base/sort/index#Base.sort), which therefore places `missing` values after all other values:
```
julia> isless(1, missing)
true
julia> isless(missing, Inf)
false
julia> isless(missing, missing)
false
```
[Logical operators](#Logical-operators)
----------------------------------------
Logical (or boolean) operators [`|`](#), [`&`](../../base/math/index#Base.:&) and [`xor`](../../base/math/index#Base.xor) are another special case since they only propagate `missing` values when it is logically required. For these operators, whether or not the result is uncertain, depends on the particular operation. This follows the well-established rules of [*three-valued logic*](https://en.wikipedia.org/wiki/Three-valued_logic) which are implemented by e.g. `NULL` in SQL and `NA` in R. This abstract definition corresponds to a relatively natural behavior which is best explained via concrete examples.
Let us illustrate this principle with the logical "or" operator [`|`](#). Following the rules of boolean logic, if one of the operands is `true`, the value of the other operand does not have an influence on the result, which will always be `true`:
```
julia> true | true
true
julia> true | false
true
julia> false | true
true
```
Based on this observation, we can conclude if one of the operands is `true` and the other `missing`, we know that the result is `true` in spite of the uncertainty about the actual value of one of the operands. If we had been able to observe the actual value of the second operand, it could only be `true` or `false`, and in both cases the result would be `true`. Therefore, in this particular case, missingness does *not* propagate:
```
julia> true | missing
true
julia> missing | true
true
```
On the contrary, if one of the operands is `false`, the result could be either `true` or `false` depending on the value of the other operand. Therefore, if that operand is `missing`, the result has to be `missing` too:
```
julia> false | true
true
julia> true | false
true
julia> false | false
false
julia> false | missing
missing
julia> missing | false
missing
```
The behavior of the logical "and" operator [`&`](../../base/math/index#Base.:&) is similar to that of the `|` operator, with the difference that missingness does not propagate when one of the operands is `false`. For example, when that is the case of the first operand:
```
julia> false & false
false
julia> false & true
false
julia> false & missing
false
```
On the other hand, missingness propagates when one of the operands is `true`, for example the first one:
```
julia> true & true
true
julia> true & false
false
julia> true & missing
missing
```
Finally, the "exclusive or" logical operator [`xor`](../../base/math/index#Base.xor) always propagates `missing` values, since both operands always have an effect on the result. Also note that the negation operator [`!`](../../base/math/index#Base.:!) returns `missing` when the operand is `missing`, just like other unary operators.
[Control Flow and Short-Circuiting Operators](#Control-Flow-and-Short-Circuiting-Operators)
--------------------------------------------------------------------------------------------
Control flow operators including [`if`](../../base/base/index#if), [`while`](../../base/base/index#while) and the [ternary operator](../control-flow/index#man-conditional-evaluation) `x ? y : z` do not allow for missing values. This is because of the uncertainty about whether the actual value would be `true` or `false` if we could observe it. This implies we do not know how the program should behave. In this case, a [`TypeError`](../../base/base/index#Core.TypeError) is thrown as soon as a `missing` value is encountered in this context:
```
julia> if missing
println("here")
end
ERROR: TypeError: non-boolean (Missing) used in boolean context
```
For the same reason, contrary to logical operators presented above, the short-circuiting boolean operators [`&&`](../../base/math/index#&&) and [`||`](#) do not allow for `missing` values in situations where the value of the operand determines whether the next operand is evaluated or not. For example:
```
julia> missing || false
ERROR: TypeError: non-boolean (Missing) used in boolean context
julia> missing && false
ERROR: TypeError: non-boolean (Missing) used in boolean context
julia> true && missing && false
ERROR: TypeError: non-boolean (Missing) used in boolean context
```
In contrast, there is no error thrown when the result can be determined without the `missing` values. This is the case when the code short-circuits before evaluating the `missing` operand, and when the `missing` operand is the last one:
```
julia> true && missing
missing
julia> false && missing
false
```
[Arrays With Missing Values](#Arrays-With-Missing-Values)
----------------------------------------------------------
Arrays containing missing values can be created like other arrays:
```
julia> [1, missing]
2-element Vector{Union{Missing, Int64}}:
1
missing
```
As this example shows, the element type of such arrays is `Union{Missing, T}`, with `T` the type of the non-missing values. This reflects the fact that array entries can be either of type `T` (here, `Int64`) or of type `Missing`. This kind of array uses an efficient memory storage equivalent to an `Array{T}` holding the actual values combined with an `Array{UInt8}` indicating the type of the entry (i.e. whether it is `Missing` or `T`).
Arrays allowing for missing values can be constructed with the standard syntax. Use `Array{Union{Missing, T}}(missing, dims)` to create arrays filled with missing values:
```
julia> Array{Union{Missing, String}}(missing, 2, 3)
2×3 Matrix{Union{Missing, String}}:
missing missing missing
missing missing missing
```
Using `undef` or `similar` may currently give an array filled with `missing`, but this is not the correct way to obtain such an array. Use a `missing` constructor as shown above instead.
An array with element type allowing `missing` entries (e.g. `Vector{Union{Missing, T}}`) which does not contain any `missing` entries can be converted to an array type that does not allow for `missing` entries (e.g. `Vector{T}`) using [`convert`](../../base/base/index#Base.convert). If the array contains `missing` values, a `MethodError` is thrown during conversion:
```
julia> x = Union{Missing, String}["a", "b"]
2-element Vector{Union{Missing, String}}:
"a"
"b"
julia> convert(Array{String}, x)
2-element Vector{String}:
"a"
"b"
julia> y = Union{Missing, String}[missing, "b"]
2-element Vector{Union{Missing, String}}:
missing
"b"
julia> convert(Array{String}, y)
ERROR: MethodError: Cannot `convert` an object of type Missing to an object of type String
```
[Skipping Missing Values](#Skipping-Missing-Values)
----------------------------------------------------
Since `missing` values propagate with standard mathematical operators, reduction functions return `missing` when called on arrays which contain missing values:
```
julia> sum([1, missing])
missing
```
In this situation, use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to skip missing values:
```
julia> sum(skipmissing([1, missing]))
1
```
This convenience function returns an iterator which filters out `missing` values efficiently. It can therefore be used with any function which supports iterators:
```
julia> x = skipmissing([3, missing, 2, 1])
skipmissing(Union{Missing, Int64}[3, missing, 2, 1])
julia> maximum(x)
3
julia> mean(x)
2.0
julia> mapreduce(sqrt, +, x)
4.146264369941973
```
Objects created by calling `skipmissing` on an array can be indexed using indices from the parent array. Indices corresponding to missing values are not valid for these objects, and an error is thrown when trying to use them (they are also skipped by `keys` and `eachindex`):
```
julia> x[1]
3
julia> x[2]
ERROR: MissingException: the value at index (2,) is missing
[...]
```
This allows functions which operate on indices to work in combination with `skipmissing`. This is notably the case for search and find functions. These functions return indices valid for the object returned by `skipmissing`, and are also the indices of the matching entries *in the parent array*:
```
julia> findall(==(1), x)
1-element Vector{Int64}:
4
julia> findfirst(!iszero, x)
1
julia> argmax(x)
1
```
Use [`collect`](#) to extract non-`missing` values and store them in an array:
```
julia> collect(x)
3-element Vector{Int64}:
3
2
1
```
[Logical Operations on Arrays](#Logical-Operations-on-Arrays)
--------------------------------------------------------------
The three-valued logic described above for logical operators is also used by logical functions applied to arrays. Thus, array equality tests using the [`==`](../../base/math/index#Base.:==) operator return `missing` whenever the result cannot be determined without knowing the actual value of the `missing` entry. In practice, this means `missing` is returned if all non-missing values of the compared arrays are equal, but one or both arrays contain missing values (possibly at different positions):
```
julia> [1, missing] == [2, missing]
false
julia> [1, missing] == [1, missing]
missing
julia> [1, 2, missing] == [1, missing, 2]
missing
```
As for single values, use [`isequal`](../../base/base/index#Base.isequal) to treat `missing` values as equal to other `missing` values, but different from non-missing values:
```
julia> isequal([1, missing], [1, missing])
true
julia> isequal([1, 2, missing], [1, missing, 2])
false
```
Functions [`any`](#) and [`all`](#) also follow the rules of three-valued logic. Thus, returning `missing` when the result cannot be determined:
```
julia> all([true, missing])
missing
julia> all([false, missing])
false
julia> any([true, missing])
true
julia> any([false, missing])
missing
```
julia Conversion and Promotion Conversion and Promotion
========================
Julia has a system for promoting arguments of mathematical operators to a common type, which has been mentioned in various other sections, including [Integers and Floating-Point Numbers](../integers-and-floating-point-numbers/index#Integers-and-Floating-Point-Numbers), [Mathematical Operations and Elementary Functions](../mathematical-operations/index#Mathematical-Operations-and-Elementary-Functions), [Types](../types/index#man-types), and [Methods](../methods/index#Methods). In this section, we explain how this promotion system works, as well as how to extend it to new types and apply it to functions besides built-in mathematical operators. Traditionally, programming languages fall into two camps with respect to promotion of arithmetic arguments:
* **Automatic promotion for built-in arithmetic types and operators.** In most languages, built-in numeric types, when used as operands to arithmetic operators with infix syntax, such as `+`, `-`, `*`, and `/`, are automatically promoted to a common type to produce the expected results. C, Java, Perl, and Python, to name a few, all correctly compute the sum `1 + 1.5` as the floating-point value `2.5`, even though one of the operands to `+` is an integer. These systems are convenient and designed carefully enough that they are generally all-but-invisible to the programmer: hardly anyone consciously thinks of this promotion taking place when writing such an expression, but compilers and interpreters must perform conversion before addition since integers and floating-point values cannot be added as-is. Complex rules for such automatic conversions are thus inevitably part of specifications and implementations for such languages.
* **No automatic promotion.** This camp includes Ada and ML – very "strict" statically typed languages. In these languages, every conversion must be explicitly specified by the programmer. Thus, the example expression `1 + 1.5` would be a compilation error in both Ada and ML. Instead one must write `real(1) + 1.5`, explicitly converting the integer `1` to a floating-point value before performing addition. Explicit conversion everywhere is so inconvenient, however, that even Ada has some degree of automatic conversion: integer literals are promoted to the expected integer type automatically, and floating-point literals are similarly promoted to appropriate floating-point types.
In a sense, Julia falls into the "no automatic promotion" category: mathematical operators are just functions with special syntax, and the arguments of functions are never automatically converted. However, one may observe that applying mathematical operations to a wide variety of mixed argument types is just an extreme case of polymorphic multiple dispatch – something which Julia's dispatch and type systems are particularly well-suited to handle. "Automatic" promotion of mathematical operands simply emerges as a special application: Julia comes with pre-defined catch-all dispatch rules for mathematical operators, invoked when no specific implementation exists for some combination of operand types. These catch-all rules first promote all operands to a common type using user-definable promotion rules, and then invoke a specialized implementation of the operator in question for the resulting values, now of the same type. User-defined types can easily participate in this promotion system by defining methods for conversion to and from other types, and providing a handful of promotion rules defining what types they should promote to when mixed with other types.
[Conversion](#Conversion)
--------------------------
The standard way to obtain a value of a certain type `T` is to call the type's constructor, `T(x)`. However, there are cases where it's convenient to convert a value from one type to another without the programmer asking for it explicitly. One example is assigning a value into an array: if `A` is a `Vector{Float64}`, the expression `A[1] = 2` should work by automatically converting the `2` from `Int` to `Float64`, and storing the result in the array. This is done via the [`convert`](../../base/base/index#Base.convert) function.
The `convert` function generally takes two arguments: the first is a type object and the second is a value to convert to that type. The returned value is the value converted to an instance of given type. The simplest way to understand this function is to see it in action:
```
julia> x = 12
12
julia> typeof(x)
Int64
julia> xu = convert(UInt8, x)
0x0c
julia> typeof(xu)
UInt8
julia> xf = convert(AbstractFloat, x)
12.0
julia> typeof(xf)
Float64
julia> a = Any[1 2 3; 4 5 6]
2×3 Matrix{Any}:
1 2 3
4 5 6
julia> convert(Array{Float64}, a)
2×3 Matrix{Float64}:
1.0 2.0 3.0
4.0 5.0 6.0
```
Conversion isn't always possible, in which case a [`MethodError`](../../base/base/index#Core.MethodError) is thrown indicating that `convert` doesn't know how to perform the requested conversion:
```
julia> convert(AbstractFloat, "foo")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type AbstractFloat
[...]
```
Some languages consider parsing strings as numbers or formatting numbers as strings to be conversions (many dynamic languages will even perform conversion for you automatically). This is not the case in Julia. Even though some strings can be parsed as numbers, most strings are not valid representations of numbers, and only a very limited subset of them are. Therefore in Julia the dedicated [`parse`](../../base/numbers/index#Base.parse) function must be used to perform this operation, making it more explicit.
###
[When is `convert` called?](#When-is-convert-called?)
The following language constructs call `convert`:
* Assigning to an array converts to the array's element type.
* Assigning to a field of an object converts to the declared type of the field.
* Constructing an object with [`new`](../../base/base/index#new) converts to the object's declared field types.
* Assigning to a variable with a declared type (e.g. `local x::T`) converts to that type.
* A function with a declared return type converts its return value to that type.
* Passing a value to [`ccall`](../../base/c/index#ccall) converts it to the corresponding argument type.
###
[Conversion vs. Construction](#Conversion-vs.-Construction)
Note that the behavior of `convert(T, x)` appears to be nearly identical to `T(x)`. Indeed, it usually is. However, there is a key semantic difference: since `convert` can be called implicitly, its methods are restricted to cases that are considered "safe" or "unsurprising". `convert` will only convert between types that represent the same basic kind of thing (e.g. different representations of numbers, or different string encodings). It is also usually lossless; converting a value to a different type and back again should result in the exact same value.
There are four general kinds of cases where constructors differ from `convert`:
####
[Constructors for types unrelated to their arguments](#Constructors-for-types-unrelated-to-their-arguments)
Some constructors don't implement the concept of "conversion". For example, `Timer(2)` creates a 2-second timer, which is not really a "conversion" from an integer to a timer.
####
[Mutable collections](#Mutable-collections)
`convert(T, x)` is expected to return the original `x` if `x` is already of type `T`. In contrast, if `T` is a mutable collection type then `T(x)` should always make a new collection (copying elements from `x`).
####
[Wrapper types](#Wrapper-types)
For some types which "wrap" other values, the constructor may wrap its argument inside a new object even if it is already of the requested type. For example `Some(x)` wraps `x` to indicate that a value is present (in a context where the result might be a `Some` or `nothing`). However, `x` itself might be the object `Some(y)`, in which case the result is `Some(Some(y))`, with two levels of wrapping. `convert(Some, x)`, on the other hand, would just return `x` since it is already a `Some`.
####
[Constructors that don't return instances of their own type](#Constructors-that-don't-return-instances-of-their-own-type)
In *very rare* cases it might make sense for the constructor `T(x)` to return an object not of type `T`. This could happen if a wrapper type is its own inverse (e.g. `Flip(Flip(x)) === x`), or to support an old calling syntax for backwards compatibility when a library is restructured. But `convert(T, x)` should always return a value of type `T`.
###
[Defining New Conversions](#Defining-New-Conversions)
When defining a new type, initially all ways of creating it should be defined as constructors. If it becomes clear that implicit conversion would be useful, and that some constructors meet the above "safety" criteria, then `convert` methods can be added. These methods are typically quite simple, as they only need to call the appropriate constructor. Such a definition might look like this:
```
convert(::Type{MyType}, x) = MyType(x)
```
The type of the first argument of this method is [`Type{MyType}`](../types/index#man-typet-type), the only instance of which is `MyType`. Thus, this method is only invoked when the first argument is the type value `MyType`. Notice the syntax used for the first argument: the argument name is omitted prior to the `::` symbol, and only the type is given. This is the syntax in Julia for a function argument whose type is specified but whose value does not need to be referenced by name.
All instances of some abstract types are by default considered "sufficiently similar" that a universal `convert` definition is provided in Julia Base. For example, this definition states that it's valid to `convert` any `Number` type to any other by calling a 1-argument constructor:
```
convert(::Type{T}, x::Number) where {T<:Number} = T(x)
```
This means that new `Number` types only need to define constructors, since this definition will handle `convert` for them. An identity conversion is also provided to handle the case where the argument is already of the requested type:
```
convert(::Type{T}, x::T) where {T<:Number} = x
```
Similar definitions exist for `AbstractString`, [`AbstractArray`](../../base/arrays/index#Core.AbstractArray), and [`AbstractDict`](../../base/collections/index#Base.AbstractDict).
[Promotion](#Promotion)
------------------------
Promotion refers to converting values of mixed types to a single common type. Although it is not strictly necessary, it is generally implied that the common type to which the values are converted can faithfully represent all of the original values. In this sense, the term "promotion" is appropriate since the values are converted to a "greater" type – i.e. one which can represent all of the input values in a single common type. It is important, however, not to confuse this with object-oriented (structural) super-typing, or Julia's notion of abstract super-types: promotion has nothing to do with the type hierarchy, and everything to do with converting between alternate representations. For instance, although every [`Int32`](../../base/numbers/index#Core.Int32) value can also be represented as a [`Float64`](../../base/numbers/index#Core.Float64) value, `Int32` is not a subtype of `Float64`.
Promotion to a common "greater" type is performed in Julia by the [`promote`](../../base/base/index#Base.promote) function, which takes any number of arguments, and returns a tuple of the same number of values, converted to a common type, or throws an exception if promotion is not possible. The most common use case for promotion is to convert numeric arguments to a common type:
```
julia> promote(1, 2.5)
(1.0, 2.5)
julia> promote(1, 2.5, 3)
(1.0, 2.5, 3.0)
julia> promote(2, 3//4)
(2//1, 3//4)
julia> promote(1, 2.5, 3, 3//4)
(1.0, 2.5, 3.0, 0.75)
julia> promote(1.5, im)
(1.5 + 0.0im, 0.0 + 1.0im)
julia> promote(1 + 2im, 3//4)
(1//1 + 2//1*im, 3//4 + 0//1*im)
```
Floating-point values are promoted to the largest of the floating-point argument types. Integer values are promoted to the larger of either the native machine word size or the largest integer argument type. Mixtures of integers and floating-point values are promoted to a floating-point type big enough to hold all the values. Integers mixed with rationals are promoted to rationals. Rationals mixed with floats are promoted to floats. Complex values mixed with real values are promoted to the appropriate kind of complex value.
That is really all there is to using promotions. The rest is just a matter of clever application, the most typical "clever" application being the definition of catch-all methods for numeric operations like the arithmetic operators `+`, `-`, `*` and `/`. Here are some of the catch-all method definitions given in [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl):
```
+(x::Number, y::Number) = +(promote(x,y)...)
-(x::Number, y::Number) = -(promote(x,y)...)
*(x::Number, y::Number) = *(promote(x,y)...)
/(x::Number, y::Number) = /(promote(x,y)...)
```
These method definitions say that in the absence of more specific rules for adding, subtracting, multiplying and dividing pairs of numeric values, promote the values to a common type and then try again. That's all there is to it: nowhere else does one ever need to worry about promotion to a common numeric type for arithmetic operations – it just happens automatically. There are definitions of catch-all promotion methods for a number of other arithmetic and mathematical functions in [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl), but beyond that, there are hardly any calls to `promote` required in Julia Base. The most common usages of `promote` occur in outer constructors methods, provided for convenience, to allow constructor calls with mixed types to delegate to an inner type with fields promoted to an appropriate common type. For example, recall that [`rational.jl`](https://github.com/JuliaLang/julia/blob/master/base/rational.jl) provides the following outer constructor method:
```
Rational(n::Integer, d::Integer) = Rational(promote(n,d)...)
```
This allows calls like the following to work:
```
julia> x = Rational(Int8(15),Int32(-5))
-3//1
julia> typeof(x)
Rational{Int32}
```
For most user-defined types, it is better practice to require programmers to supply the expected types to constructor functions explicitly, but sometimes, especially for numeric problems, it can be convenient to do promotion automatically.
###
[Defining Promotion Rules](#Defining-Promotion-Rules)
Although one could, in principle, define methods for the `promote` function directly, this would require many redundant definitions for all possible permutations of argument types. Instead, the behavior of `promote` is defined in terms of an auxiliary function called [`promote_rule`](../../base/base/index#Base.promote_rule), which one can provide methods for. The `promote_rule` function takes a pair of type objects and returns another type object, such that instances of the argument types will be promoted to the returned type. Thus, by defining the rule:
```
promote_rule(::Type{Float64}, ::Type{Float32}) = Float64
```
one declares that when 64-bit and 32-bit floating-point values are promoted together, they should be promoted to 64-bit floating-point. The promotion type does not need to be one of the argument types. For example, the following promotion rules both occur in Julia Base:
```
promote_rule(::Type{BigInt}, ::Type{Float64}) = BigFloat
promote_rule(::Type{BigInt}, ::Type{Int8}) = BigInt
```
In the latter case, the result type is [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) since `BigInt` is the only type large enough to hold integers for arbitrary-precision integer arithmetic. Also note that one does not need to define both `promote_rule(::Type{A}, ::Type{B})` and `promote_rule(::Type{B}, ::Type{A})` – the symmetry is implied by the way `promote_rule` is used in the promotion process.
The `promote_rule` function is used as a building block to define a second function called [`promote_type`](../../base/base/index#Base.promote_type), which, given any number of type objects, returns the common type to which those values, as arguments to `promote` should be promoted. Thus, if one wants to know, in absence of actual values, what type a collection of values of certain types would promote to, one can use `promote_type`:
```
julia> promote_type(Int8, Int64)
Int64
```
Note that we do **not** overload `promote_type` directly: we overload `promote_rule` instead. `promote_type` uses `promote_rule`, and adds the symmetry. Overloading it directly can cause ambiguity errors. We overload `promote_rule` to define how things should be promoted, and we use `promote_type` to query that.
Internally, `promote_type` is used inside of `promote` to determine what type argument values should be converted to for promotion. The curious reader can read the code in [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl), which defines the complete promotion mechanism in about 35 lines.
###
[Case Study: Rational Promotions](#Case-Study:-Rational-Promotions)
Finally, we finish off our ongoing case study of Julia's rational number type, which makes relatively sophisticated use of the promotion mechanism with the following promotion rules:
```
promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)}
promote_rule(::Type{Rational{T}}, ::Type{Rational{S}}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)}
promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:AbstractFloat} = promote_type(T,S)
```
The first rule says that promoting a rational number with any other integer type promotes to a rational type whose numerator/denominator type is the result of promotion of its numerator/denominator type with the other integer type. The second rule applies the same logic to two different types of rational numbers, resulting in a rational of the promotion of their respective numerator/denominator types. The third and final rule dictates that promoting a rational with a float results in the same type as promoting the numerator/denominator type with the float.
This small handful of promotion rules, together with the type's constructors and the default `convert` method for numbers, are sufficient to make rational numbers interoperate completely naturally with all of Julia's other numeric types – integers, floating-point numbers, and complex numbers. By providing appropriate conversion methods and promotion rules in the same manner, any user-defined numeric type can interoperate just as naturally with Julia's predefined numerics.
| programming_docs |
julia Constructors Constructors
============
Constructors [[1]](#footnote-1) are functions that create new objects – specifically, instances of [Composite Types](../types/index#Composite-Types). In Julia, type objects also serve as constructor functions: they create new instances of themselves when applied to an argument tuple as a function. This much was already mentioned briefly when composite types were introduced. For example:
```
julia> struct Foo
bar
baz
end
julia> foo = Foo(1, 2)
Foo(1, 2)
julia> foo.bar
1
julia> foo.baz
2
```
For many types, forming new objects by binding their field values together is all that is ever needed to create instances. However, in some cases more functionality is required when creating composite objects. Sometimes invariants must be enforced, either by checking arguments or by transforming them. [Recursive data structures](https://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Recursive_data_structures_.28structural_recursion.29), especially those that may be self-referential, often cannot be constructed cleanly without first being created in an incomplete state and then altered programmatically to be made whole, as a separate step from object creation. Sometimes, it's just convenient to be able to construct objects with fewer or different types of parameters than they have fields. Julia's system for object construction addresses all of these cases and more.
[Outer Constructor Methods](#man-outer-constructor-methods)
------------------------------------------------------------
A constructor is just like any other function in Julia in that its overall behavior is defined by the combined behavior of its methods. Accordingly, you can add functionality to a constructor by simply defining new methods. For example, let's say you want to add a constructor method for `Foo` objects that takes only one argument and uses the given value for both the `bar` and `baz` fields. This is simple:
```
julia> Foo(x) = Foo(x,x)
Foo
julia> Foo(1)
Foo(1, 1)
```
You could also add a zero-argument `Foo` constructor method that supplies default values for both of the `bar` and `baz` fields:
```
julia> Foo() = Foo(0)
Foo
julia> Foo()
Foo(0, 0)
```
Here the zero-argument constructor method calls the single-argument constructor method, which in turn calls the automatically provided two-argument constructor method. For reasons that will become clear very shortly, additional constructor methods declared as normal methods like this are called *outer* constructor methods. Outer constructor methods can only ever create a new instance by calling another constructor method, such as the automatically provided default ones.
[Inner Constructor Methods](#man-inner-constructor-methods)
------------------------------------------------------------
While outer constructor methods succeed in addressing the problem of providing additional convenience methods for constructing objects, they fail to address the other two use cases mentioned in the introduction of this chapter: enforcing invariants, and allowing construction of self-referential objects. For these problems, one needs *inner* constructor methods. An inner constructor method is like an outer constructor method, except for two differences:
1. It is declared inside the block of a type declaration, rather than outside of it like normal methods.
2. It has access to a special locally existent function called [`new`](../../base/base/index#new) that creates objects of the block's type.
For example, suppose one wants to declare a type that holds a pair of real numbers, subject to the constraint that the first number is not greater than the second one. One could declare it like this:
```
julia> struct OrderedPair
x::Real
y::Real
OrderedPair(x,y) = x > y ? error("out of order") : new(x,y)
end
```
Now `OrderedPair` objects can only be constructed such that `x <= y`:
```
julia> OrderedPair(1, 2)
OrderedPair(1, 2)
julia> OrderedPair(2,1)
ERROR: out of order
Stacktrace:
[1] error at ./error.jl:33 [inlined]
[2] OrderedPair(::Int64, ::Int64) at ./none:4
[3] top-level scope
```
If the type were declared `mutable`, you could reach in and directly change the field values to violate this invariant. Of course, messing around with an object's internals uninvited is bad practice. You (or someone else) can also provide additional outer constructor methods at any later point, but once a type is declared, there is no way to add more inner constructor methods. Since outer constructor methods can only create objects by calling other constructor methods, ultimately, some inner constructor must be called to create an object. This guarantees that all objects of the declared type must come into existence by a call to one of the inner constructor methods provided with the type, thereby giving some degree of enforcement of a type's invariants.
If any inner constructor method is defined, no default constructor method is provided: it is presumed that you have supplied yourself with all the inner constructors you need. The default constructor is equivalent to writing your own inner constructor method that takes all of the object's fields as parameters (constrained to be of the correct type, if the corresponding field has a type), and passes them to `new`, returning the resulting object:
```
julia> struct Foo
bar
baz
Foo(bar,baz) = new(bar,baz)
end
```
This declaration has the same effect as the earlier definition of the `Foo` type without an explicit inner constructor method. The following two types are equivalent – one with a default constructor, the other with an explicit constructor:
```
julia> struct T1
x::Int64
end
julia> struct T2
x::Int64
T2(x) = new(x)
end
julia> T1(1)
T1(1)
julia> T2(1)
T2(1)
julia> T1(1.0)
T1(1)
julia> T2(1.0)
T2(1)
```
It is good practice to provide as few inner constructor methods as possible: only those taking all arguments explicitly and enforcing essential error checking and transformation. Additional convenience constructor methods, supplying default values or auxiliary transformations, should be provided as outer constructors that call the inner constructors to do the heavy lifting. This separation is typically quite natural.
[Incomplete Initialization](#Incomplete-Initialization)
--------------------------------------------------------
The final problem which has still not been addressed is construction of self-referential objects, or more generally, recursive data structures. Since the fundamental difficulty may not be immediately obvious, let us briefly explain it. Consider the following recursive type declaration:
```
julia> mutable struct SelfReferential
obj::SelfReferential
end
```
This type may appear innocuous enough, until one considers how to construct an instance of it. If `a` is an instance of `SelfReferential`, then a second instance can be created by the call:
```
julia> b = SelfReferential(a)
```
But how does one construct the first instance when no instance exists to provide as a valid value for its `obj` field? The only solution is to allow creating an incompletely initialized instance of `SelfReferential` with an unassigned `obj` field, and using that incomplete instance as a valid value for the `obj` field of another instance, such as, for example, itself.
To allow for the creation of incompletely initialized objects, Julia allows the [`new`](../../base/base/index#new) function to be called with fewer than the number of fields that the type has, returning an object with the unspecified fields uninitialized. The inner constructor method can then use the incomplete object, finishing its initialization before returning it. Here, for example, is another attempt at defining the `SelfReferential` type, this time using a zero-argument inner constructor returning instances having `obj` fields pointing to themselves:
```
julia> mutable struct SelfReferential
obj::SelfReferential
SelfReferential() = (x = new(); x.obj = x)
end
```
We can verify that this constructor works and constructs objects that are, in fact, self-referential:
```
julia> x = SelfReferential();
julia> x === x
true
julia> x === x.obj
true
julia> x === x.obj.obj
true
```
Although it is generally a good idea to return a fully initialized object from an inner constructor, it is possible to return incompletely initialized objects:
```
julia> mutable struct Incomplete
data
Incomplete() = new()
end
julia> z = Incomplete();
```
While you are allowed to create objects with uninitialized fields, any access to an uninitialized reference is an immediate error:
```
julia> z.data
ERROR: UndefRefError: access to undefined reference
```
This avoids the need to continually check for `null` values. However, not all object fields are references. Julia considers some types to be "plain data", meaning all of their data is self-contained and does not reference other objects. The plain data types consist of primitive types (e.g. `Int`) and immutable structs of other plain data types. The initial contents of a plain data type is undefined:
```
julia> struct HasPlain
n::Int
HasPlain() = new()
end
julia> HasPlain()
HasPlain(438103441441)
```
Arrays of plain data types exhibit the same behavior.
You can pass incomplete objects to other functions from inner constructors to delegate their completion:
```
julia> mutable struct Lazy
data
Lazy(v) = complete_me(new(), v)
end
```
As with incomplete objects returned from constructors, if `complete_me` or any of its callees try to access the `data` field of the `Lazy` object before it has been initialized, an error will be thrown immediately.
[Parametric Constructors](#Parametric-Constructors)
----------------------------------------------------
Parametric types add a few wrinkles to the constructor story. Recall from [Parametric Types](../types/index#Parametric-Types) that, by default, instances of parametric composite types can be constructed either with explicitly given type parameters or with type parameters implied by the types of the arguments given to the constructor. Here are some examples:
```
julia> struct Point{T<:Real}
x::T
y::T
end
julia> Point(1,2) ## implicit T ##
Point{Int64}(1, 2)
julia> Point(1.0,2.5) ## implicit T ##
Point{Float64}(1.0, 2.5)
julia> Point(1,2.5) ## implicit T ##
ERROR: MethodError: no method matching Point(::Int64, ::Float64)
Closest candidates are:
Point(::T, ::T) where T<:Real at none:2
julia> Point{Int64}(1, 2) ## explicit T ##
Point{Int64}(1, 2)
julia> Point{Int64}(1.0,2.5) ## explicit T ##
ERROR: InexactError: Int64(2.5)
Stacktrace:
[...]
julia> Point{Float64}(1.0, 2.5) ## explicit T ##
Point{Float64}(1.0, 2.5)
julia> Point{Float64}(1,2) ## explicit T ##
Point{Float64}(1.0, 2.0)
```
As you can see, for constructor calls with explicit type parameters, the arguments are converted to the implied field types: `Point{Int64}(1,2)` works, but `Point{Int64}(1.0,2.5)` raises an [`InexactError`](../../base/base/index#Core.InexactError) when converting `2.5` to [`Int64`](../../base/numbers/index#Core.Int64). When the type is implied by the arguments to the constructor call, as in `Point(1,2)`, then the types of the arguments must agree – otherwise the `T` cannot be determined – but any pair of real arguments with matching type may be given to the generic `Point` constructor.
What's really going on here is that `Point`, `Point{Float64}` and `Point{Int64}` are all different constructor functions. In fact, `Point{T}` is a distinct constructor function for each type `T`. Without any explicitly provided inner constructors, the declaration of the composite type `Point{T<:Real}` automatically provides an inner constructor, `Point{T}`, for each possible type `T<:Real`, that behaves just like non-parametric default inner constructors do. It also provides a single general outer `Point` constructor that takes pairs of real arguments, which must be of the same type. This automatic provision of constructors is equivalent to the following explicit declaration:
```
julia> struct Point{T<:Real}
x::T
y::T
Point{T}(x,y) where {T<:Real} = new(x,y)
end
julia> Point(x::T, y::T) where {T<:Real} = Point{T}(x,y);
```
Notice that each definition looks like the form of constructor call that it handles. The call `Point{Int64}(1,2)` will invoke the definition `Point{T}(x,y)` inside the `struct` block. The outer constructor declaration, on the other hand, defines a method for the general `Point` constructor which only applies to pairs of values of the same real type. This declaration makes constructor calls without explicit type parameters, like `Point(1,2)` and `Point(1.0,2.5)`, work. Since the method declaration restricts the arguments to being of the same type, calls like `Point(1,2.5)`, with arguments of different types, result in "no method" errors.
Suppose we wanted to make the constructor call `Point(1,2.5)` work by "promoting" the integer value `1` to the floating-point value `1.0`. The simplest way to achieve this is to define the following additional outer constructor method:
```
julia> Point(x::Int64, y::Float64) = Point(convert(Float64,x),y);
```
This method uses the [`convert`](../../base/base/index#Base.convert) function to explicitly convert `x` to [`Float64`](../../base/numbers/index#Core.Float64) and then delegates construction to the general constructor for the case where both arguments are [`Float64`](../../base/numbers/index#Core.Float64). With this method definition what was previously a [`MethodError`](../../base/base/index#Core.MethodError) now successfully creates a point of type `Point{Float64}`:
```
julia> p = Point(1,2.5)
Point{Float64}(1.0, 2.5)
julia> typeof(p)
Point{Float64}
```
However, other similar calls still don't work:
```
julia> Point(1.5,2)
ERROR: MethodError: no method matching Point(::Float64, ::Int64)
Closest candidates are:
Point(::T, !Matched::T) where T<:Real at none:1
```
For a more general way to make all such calls work sensibly, see [Conversion and Promotion](../conversion-and-promotion/index#conversion-and-promotion). At the risk of spoiling the suspense, we can reveal here that all it takes is the following outer method definition to make all calls to the general `Point` constructor work as one would expect:
```
julia> Point(x::Real, y::Real) = Point(promote(x,y)...);
```
The `promote` function converts all its arguments to a common type – in this case [`Float64`](../../base/numbers/index#Core.Float64). With this method definition, the `Point` constructor promotes its arguments the same way that numeric operators like [`+`](../../base/math/index#Base.:+) do, and works for all kinds of real numbers:
```
julia> Point(1.5,2)
Point{Float64}(1.5, 2.0)
julia> Point(1,1//2)
Point{Rational{Int64}}(1//1, 1//2)
julia> Point(1.0,1//2)
Point{Float64}(1.0, 0.5)
```
Thus, while the implicit type parameter constructors provided by default in Julia are fairly strict, it is possible to make them behave in a more relaxed but sensible manner quite easily. Moreover, since constructors can leverage all of the power of the type system, methods, and multiple dispatch, defining sophisticated behavior is typically quite simple.
[Case Study: Rational](#Case-Study:-Rational)
----------------------------------------------
Perhaps the best way to tie all these pieces together is to present a real world example of a parametric composite type and its constructor methods. To that end, we implement our own rational number type `OurRational`, similar to Julia's built-in [`Rational`](../../base/numbers/index#Base.Rational) type, defined in [`rational.jl`](https://github.com/JuliaLang/julia/blob/master/base/rational.jl):
```
julia> struct OurRational{T<:Integer} <: Real
num::T
den::T
function OurRational{T}(num::T, den::T) where T<:Integer
if num == 0 && den == 0
error("invalid rational: 0//0")
end
num = flipsign(num, den)
den = flipsign(den, den)
g = gcd(num, den)
num = div(num, g)
den = div(den, g)
new(num, den)
end
end
julia> OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d)
OurRational
julia> OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...)
OurRational
julia> OurRational(n::Integer) = OurRational(n,one(n))
OurRational
julia> ⊘(n::Integer, d::Integer) = OurRational(n,d)
⊘ (generic function with 1 method)
julia> ⊘(x::OurRational, y::Integer) = x.num ⊘ (x.den*y)
⊘ (generic function with 2 methods)
julia> ⊘(x::Integer, y::OurRational) = (x*y.den) ⊘ y.num
⊘ (generic function with 3 methods)
julia> ⊘(x::Complex, y::Real) = complex(real(x) ⊘ y, imag(x) ⊘ y)
⊘ (generic function with 4 methods)
julia> ⊘(x::Real, y::Complex) = (x*y') ⊘ real(y*y')
⊘ (generic function with 5 methods)
julia> function ⊘(x::Complex, y::Complex)
xy = x*y'
yy = real(y*y')
complex(real(xy) ⊘ yy, imag(xy) ⊘ yy)
end
⊘ (generic function with 6 methods)
```
The first line – `struct OurRational{T<:Integer} <: Real` – declares that `OurRational` takes one type parameter of an integer type, and is itself a real type. The field declarations `num::T` and `den::T` indicate that the data held in a `OurRational{T}` object are a pair of integers of type `T`, one representing the rational value's numerator and the other representing its denominator.
Now things get interesting. `OurRational` has a single inner constructor method which checks that `num` and `den` aren't both zero and ensures that every rational is constructed in "lowest terms" with a non-negative denominator. This is accomplished by first flipping the signs of numerator and denominator if the denominator is negative. Then, both are divided by their greatest common divisor (`gcd` always returns a non-negative number, regardless of the sign of its arguments). Because this is the only inner constructor for `OurRational`, we can be certain that `OurRational` objects are always constructed in this normalized form.
`OurRational` also provides several outer constructor methods for convenience. The first is the "standard" general constructor that infers the type parameter `T` from the type of the numerator and denominator when they have the same type. The second applies when the given numerator and denominator values have different types: it promotes them to a common type and then delegates construction to the outer constructor for arguments of matching type. The third outer constructor turns integer values into rationals by supplying a value of `1` as the denominator.
Following the outer constructor definitions, we defined a number of methods for the `⊘` operator, which provides a syntax for writing rationals (e.g. `1 ⊘ 2`). Julia's `Rational` type uses the [`//`](../../base/math/index#Base.://) operator for this purpose. Before these definitions, `⊘` is a completely undefined operator with only syntax and no meaning. Afterwards, it behaves just as described in [Rational Numbers](../complex-and-rational-numbers/index#Rational-Numbers) – its entire behavior is defined in these few lines. The first and most basic definition just makes `a ⊘ b` construct a `OurRational` by applying the `OurRational` constructor to `a` and `b` when they are integers. When one of the operands of `⊘` is already a rational number, we construct a new rational for the resulting ratio slightly differently; this behavior is actually identical to division of a rational with an integer. Finally, applying `⊘` to complex integral values creates an instance of `Complex{<:OurRational}` – a complex number whose real and imaginary parts are rationals:
```
julia> z = (1 + 2im) ⊘ (1 - 2im);
julia> typeof(z)
Complex{OurRational{Int64}}
julia> typeof(z) <: Complex{<:OurRational}
true
```
Thus, although the `⊘` operator usually returns an instance of `OurRational`, if either of its arguments are complex integers, it will return an instance of `Complex{<:OurRational}` instead. The interested reader should consider perusing the rest of [`rational.jl`](https://github.com/JuliaLang/julia/blob/master/base/rational.jl): it is short, self-contained, and implements an entire basic Julia type.
[Outer-only constructors](#Outer-only-constructors)
----------------------------------------------------
As we have seen, a typical parametric type has inner constructors that are called when type parameters are known; e.g. they apply to `Point{Int}` but not to `Point`. Optionally, outer constructors that determine type parameters automatically can be added, for example constructing a `Point{Int}` from the call `Point(1,2)`. Outer constructors call inner constructors to actually make instances. However, in some cases one would rather not provide inner constructors, so that specific type parameters cannot be requested manually.
For example, say we define a type that stores a vector along with an accurate representation of its sum:
```
julia> struct SummedArray{T<:Number,S<:Number}
data::Vector{T}
sum::S
end
julia> SummedArray(Int32[1; 2; 3], Int32(6))
SummedArray{Int32, Int32}(Int32[1, 2, 3], 6)
```
The problem is that we want `S` to be a larger type than `T`, so that we can sum many elements with less information loss. For example, when `T` is [`Int32`](../../base/numbers/index#Core.Int32), we would like `S` to be [`Int64`](../../base/numbers/index#Core.Int64). Therefore we want to avoid an interface that allows the user to construct instances of the type `SummedArray{Int32,Int32}`. One way to do this is to provide a constructor only for `SummedArray`, but inside the `struct` definition block to suppress generation of default constructors:
```
julia> struct SummedArray{T<:Number,S<:Number}
data::Vector{T}
sum::S
function SummedArray(a::Vector{T}) where T
S = widen(T)
new{T,S}(a, sum(S, a))
end
end
julia> SummedArray(Int32[1; 2; 3], Int32(6))
ERROR: MethodError: no method matching SummedArray(::Vector{Int32}, ::Int32)
Closest candidates are:
SummedArray(::Vector{T}) where T at none:4
Stacktrace:
[...]
```
This constructor will be invoked by the syntax `SummedArray(a)`. The syntax `new{T,S}` allows specifying parameters for the type to be constructed, i.e. this call will return a `SummedArray{T,S}`. `new{T,S}` can be used in any constructor definition, but for convenience the parameters to `new{}` are automatically derived from the type being constructed when possible.
* [1](#citeref-1)Nomenclature: while the term "constructor" generally refers to the entire function which constructs objects of a type, it is common to abuse terminology slightly and refer to specific constructor methods as "constructors". In such situations, it is generally clear from the context that the term is used to mean "constructor method" rather than "constructor function", especially as it is often used in the sense of singling out a particular method of the constructor from all of the others.
| programming_docs |
julia Command-line Options Command-line Options
====================
[Using arguments inside scripts](#Using-arguments-inside-scripts)
------------------------------------------------------------------
When running a script using `julia`, you can pass additional arguments to your script:
```
$ julia script.jl arg1 arg2...
```
These additional command-line arguments are passed in the global constant `ARGS`. The name of the script itself is passed in as the global `PROGRAM_FILE`. Note that `ARGS` is also set when a Julia expression is given using the `-e` option on the command line (see the `julia` help output below) but `PROGRAM_FILE` will be empty. For example, to just print the arguments given to a script, you could do this:
```
$ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar
foo
bar
```
Or you could put that code into a script and run it:
```
$ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl
$ julia script.jl foo bar
script.jl
foo
bar
```
The `--` delimiter can be used to separate command-line arguments intended for the script file from arguments intended for Julia:
```
$ julia --color=yes -O -- script.jl arg1 arg2..
```
See also [Scripting](../faq/index#man-scripting) for more information on writing Julia scripts.
Julia can be started in parallel mode with either the `-p` or the `--machine-file` options. `-p n` will launch an additional `n` worker processes, while `--machine-file file` will launch a worker for each line in file `file`. The machines defined in `file` must be accessible via a password-less `ssh` login, with Julia installed at the same location as the current host. Each machine definition takes the form `[count*][user@]host[:port] [bind_addr[:port]]`. `user` defaults to current user, `port` to the standard ssh port. `count` is the number of workers to spawn on the node, and defaults to 1. The optional `bind-to bind_addr[:port]` specifies the IP address and port that other workers should use to connect to this worker.
If you have code that you want executed whenever Julia is run, you can put it in `~/.julia/config/startup.jl`:
```
$ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl
$ julia
Greetings! 你好! 안녕하세요?
...
```
Note that although you should have a `~/.julia` directory once you've run Julia for the first time, you may need to create the `~/.julia/config` folder and the `~/.julia/config/startup.jl` file if you use it.
[Command-line switches for Julia](#Command-line-switches-for-Julia)
--------------------------------------------------------------------
There are various ways to run Julia code and provide options, similar to those available for the `perl` and `ruby` programs:
```
julia [switches] -- [programfile] [args...]
```
The following is a complete list of command-line switches available when launching julia (a '\*' marks the default value, if applicable):
| Switch | Description |
| --- | --- |
| `-v`, `--version` | Display version information |
| `-h`, `--help` | Print command-line options (this message). |
| `--help-hidden` | Uncommon options not shown by `-h` |
| `--project[={<dir>|@.}]` | Set `<dir>` as the home project/environment. The default `@.` option will search through parent directories until a `Project.toml` or `JuliaProject.toml` file is found. |
| `-J`, `--sysimage <file>` | Start up with the given system image file |
| `-H`, `--home <dir>` | Set location of `julia` executable |
| `--startup-file={yes*|no}` | Load `JULIA_DEPOT_PATH/config/startup.jl`; if `JULIA_DEPOT_PATH` environment variable is unset, load `~/.julia/config/startup.jl` |
| `--handle-signals={yes*|no}` | Enable or disable Julia's default signal handlers |
| `--sysimage-native-code={yes*|no}` | Use native code from system image if available |
| `--compiled-modules={yes*|no}` | Enable or disable incremental precompilation of modules |
| `-e`, `--eval <expr>` | Evaluate `<expr>` |
| `-E`, `--print <expr>` | Evaluate `<expr>` and display the result |
| `-L`, `--load <file>` | Load `<file>` immediately on all processors |
| `-t`, `--threads {N|auto`} | Enable N threads; `auto` currently sets N to the number of local CPU threads but this might change in the future |
| `-p`, `--procs {N|auto`} | Integer value N launches N additional local worker processes; `auto` launches as many workers as the number of local CPU threads (logical cores) |
| `--machine-file <file>` | Run processes on hosts listed in `<file>` |
| `-i` | Interactive mode; REPL runs and `isinteractive()` is true |
| `-q`, `--quiet` | Quiet startup: no banner, suppress REPL warnings |
| `--banner={yes|no|auto*}` | Enable or disable startup banner |
| `--color={yes|no|auto*}` | Enable or disable color text |
| `--history-file={yes*|no}` | Load or save history |
| `--depwarn={yes|no*|error}` | Enable or disable syntax and method deprecation warnings (`error` turns warnings into errors) |
| `--warn-overwrite={yes|no*}` | Enable or disable method overwrite warnings |
| `--warn-scope={yes*|no}` | Enable or disable warning for ambiguous top-level scope |
| `-C`, `--cpu-target <target>` | Limit usage of CPU features up to `<target>`; set to `help` to see the available options |
| `-O`, `--optimize={0,1,2*,3}` | Set the optimization level (level is 3 if `-O` is used without a level) |
| `--min-optlevel={0*,1,2,3}` | Set the lower bound on per-module optimization |
| `-g {0,1*,2}` | Set the level of debug info generation (level is 2 if `-g` is used without a level) |
| `--inline={yes|no}` | Control whether inlining is permitted, including overriding `@inline` declarations |
| `--check-bounds={yes|no|auto*}` | Emit bounds checks always, never, or respect `@inbounds` declarations |
| `--math-mode={ieee,fast}` | Disallow or enable unsafe floating point optimizations (overrides `@fastmath` declaration) |
| `--code-coverage[={none*|user|all}]` | Count executions of source lines (omitting setting is equivalent to `user`) |
| `--code-coverage=tracefile.info` | Append coverage information to the LCOV tracefile (filename supports format tokens). |
| `--track-allocation[={none*|user|all}]` | Count bytes allocated by each source line (omitting setting is equivalent to "user") |
| `--bug-report=KIND` | Launch a bug report session. It can be used to start a REPL, run a script, or evaluate expressions. It first tries to use BugReporting.jl installed in current environment and fallbacks to the latest compatible BugReporting.jl if not. For more nformation, see `--bug-report=help`. |
| `--compile={yes*|no|all|min}` | Enable or disable JIT compiler, or request exhaustive or minimal compilation |
| `--output-o <name>` | Generate an object file (including system image data) |
| `--output-ji <name>` | Generate a system image data file (.ji) |
| `--strip-metadata` | Remove docstrings and source location info from system image |
| `--strip-ir` | Remove IR (intermediate representation) of compiled functions |
| `--output-unopt-bc <name>` | Generate unoptimized LLVM bitcode (.bc) |
| `--output-bc <name>` | Generate LLVM bitcode (.bc) |
| `--output-asm <name>` | Generate an assembly file (.s) |
| `--output-incremental={yes|no*}` | Generate an incremental output file (rather than complete) |
| `--trace-compile={stderr,name}` | Print precompile statements for methods compiled during execution or save to a path |
| `--image-codegen` | Force generate code in imaging mode |
In Julia 1.0, the default `--project=@.` option did not search up from the root directory of a Git repository for the `Project.toml` file. From Julia 1.1 forward, it does.
julia Getting Started Getting Started
===============
Julia installation is straightforward, whether using precompiled binaries or compiling from source. Download and install Julia by following the instructions at <https://julialang.org/downloads/>.
If you are coming to Julia from one of the following languages, then you should start by reading the section on noteworthy differences from [MATLAB](../noteworthy-differences/index#Noteworthy-differences-from-MATLAB), [R](../noteworthy-differences/index#Noteworthy-differences-from-R), [Python](../noteworthy-differences/index#Noteworthy-differences-from-Python), [C/C++](../noteworthy-differences/index#Noteworthy-differences-from-C/C) or [Common Lisp](../noteworthy-differences/index#Noteworthy-differences-from-Common-Lisp). This will help you avoid some common pitfalls since Julia differs from those languages in many subtle ways.
The easiest way to learn and experiment with Julia is by starting an interactive session (also known as a read-eval-print loop or "REPL") by double-clicking the Julia executable or running `julia` from the command line:
```
$ julia
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.8.5 (2023-01-08)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
julia> 1 + 2
3
julia> ans
3
```
To exit the interactive session, type `CTRL-D` (press the Control/`^` key together with the `d` key), or type `exit()`. When run in interactive mode, `julia` displays a banner and prompts the user for input. Once the user has entered a complete expression, such as `1 + 2`, and hits enter, the interactive session evaluates the expression and shows its value. If an expression is entered into an interactive session with a trailing semicolon, its value is not shown. The variable `ans` is bound to the value of the last evaluated expression whether it is shown or not. The `ans` variable is only bound in interactive sessions, not when Julia code is run in other ways.
To evaluate expressions written in a source file `file.jl`, write `include("file.jl")`.
To run code in a file non-interactively, you can give it as the first argument to the `julia` command:
```
$ julia script.jl
```
You can pass additional arguments to Julia, and to your program `script.jl`. A detailed list of all the available switches can be found at [Command-line Options](../command-line-options/index#command-line-options).
[Resources](#Resources)
------------------------
A curated list of useful learning resources to help new users get started can be found on the [learning](https://julialang.org/learning/) page of the main Julia website.
You can use the REPL as a learning resource by switching into the help mode. Switch to help mode by pressing `?` at an empty `julia>` prompt, before typing anything else. Typing a keyword in help mode will fetch the documentation for it, along with examples. Similarly for most functions or other objects you might encounter!
```
help?> begin
search: begin disable_sigint reenable_sigint
begin
begin...end denotes a block of code.
```
If you already know Julia a bit, you might want to peek ahead at [Performance Tips](../performance-tips/index#man-performance-tips) and [Workflow Tips](../workflow-tips/index#man-workflow-tips).
julia Profiling Profiling
=========
The `Profile` module provides tools to help developers improve the performance of their code. When used, it takes measurements on running code, and produces output that helps you understand how much time is spent on individual line(s). The most common usage is to identify "bottlenecks" as targets for optimization.
`Profile` implements what is known as a "sampling" or [statistical profiler](https://en.wikipedia.org/wiki/Profiling_(computer_programming)). It works by periodically taking a backtrace during the execution of any task. Each backtrace captures the currently-running function and line number, plus the complete chain of function calls that led to this line, and hence is a "snapshot" of the current state of execution.
If much of your run time is spent executing a particular line of code, this line will show up frequently in the set of all backtraces. In other words, the "cost" of a given line–or really, the cost of the sequence of function calls up to and including this line–is proportional to how often it appears in the set of all backtraces.
A sampling profiler does not provide complete line-by-line coverage, because the backtraces occur at intervals (by default, 1 ms on Unix systems and 10 ms on Windows, although the actual scheduling is subject to operating system load). Moreover, as discussed further below, because samples are collected at a sparse subset of all execution points, the data collected by a sampling profiler is subject to statistical noise.
Despite these limitations, sampling profilers have substantial strengths:
* You do not have to make any modifications to your code to take timing measurements.
* It can profile into Julia's core code and even (optionally) into C and Fortran libraries.
* By running "infrequently" there is very little performance overhead; while profiling, your code can run at nearly native speed.
For these reasons, it's recommended that you try using the built-in sampling profiler before considering any alternatives.
[Basic usage](#Basic-usage)
----------------------------
Let's work with a simple test case:
```
julia> function myfunc()
A = rand(200, 200, 400)
maximum(A)
end
```
It's a good idea to first run the code you intend to profile at least once (unless you want to profile Julia's JIT-compiler):
```
julia> myfunc() # run once to force compilation
```
Now we're ready to profile this function:
```
julia> using Profile
julia> @profile myfunc()
```
To see the profiling results, there are several graphical browsers. One "family" of visualizers is based on [FlameGraphs.jl](https://github.com/timholy/FlameGraphs.jl), with each family member providing a different user interface:
* [Juno](https://junolab.org/) is a full IDE with built-in support for profile visualization
* [ProfileView.jl](https://github.com/timholy/ProfileView.jl) is a stand-alone visualizer based on GTK
* [ProfileVega.jl](https://github.com/davidanthoff/ProfileVega.jl) uses VegaLight and integrates well with Jupyter notebooks
* [StatProfilerHTML](https://github.com/tkluck/StatProfilerHTML.jl) produces HTML and presents some additional summaries, and also integrates well with Jupyter notebooks
* [ProfileSVG](https://github.com/timholy/ProfileSVG.jl) renders SVG
An entirely independent approach to profile visualization is [PProf.jl](https://github.com/vchuravy/PProf.jl), which uses the external `pprof` tool.
Here, though, we'll use the text-based display that comes with the standard library:
```
julia> Profile.print()
80 ./event.jl:73; (::Base.REPL.##1#2{Base.REPL.REPLBackend})()
80 ./REPL.jl:97; macro expansion
80 ./REPL.jl:66; eval_user_input(::Any, ::Base.REPL.REPLBackend)
80 ./boot.jl:235; eval(::Module, ::Any)
80 ./<missing>:?; anonymous
80 ./profile.jl:23; macro expansion
52 ./REPL[1]:2; myfunc()
38 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type{B...
38 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr{F...
14 ./random.jl:278; rand
14 ./random.jl:277; rand
14 ./random.jl:366; rand
14 ./random.jl:369; rand
28 ./REPL[1]:3; myfunc()
28 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinear,...
3 ./reduce.jl:426; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F...
25 ./reduce.jl:428; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F...
```
Each line of this display represents a particular spot (line number) in the code. Indentation is used to indicate the nested sequence of function calls, with more-indented lines being deeper in the sequence of calls. In each line, the first "field" is the number of backtraces (samples) taken *at this line or in any functions executed by this line*. The second field is the file name and line number and the third field is the function name. Note that the specific line numbers may change as Julia's code changes; if you want to follow along, it's best to run this example yourself.
In this example, we can see that the top level function called is in the file `event.jl`. This is the function that runs the REPL when you launch Julia. If you examine line 97 of `REPL.jl`, you'll see this is where the function `eval_user_input()` is called. This is the function that evaluates what you type at the REPL, and since we're working interactively these functions were invoked when we entered `@profile myfunc()`. The next line reflects actions taken in the [`@profile`](../../stdlib/profile/index#Profile.@profile) macro.
The first line shows that 80 backtraces were taken at line 73 of `event.jl`, but it's not that this line was "expensive" on its own: the third line reveals that all 80 of these backtraces were actually triggered inside its call to `eval_user_input`, and so on. To find out which operations are actually taking the time, we need to look deeper in the call chain.
The first "important" line in this output is this one:
```
52 ./REPL[1]:2; myfunc()
```
`REPL` refers to the fact that we defined `myfunc` in the REPL, rather than putting it in a file; if we had used a file, this would show the file name. The `[1]` shows that the function `myfunc` was the first expression evaluated in this REPL session. Line 2 of `myfunc()` contains the call to `rand`, and there were 52 (out of 80) backtraces that occurred at this line. Below that, you can see a call to `dsfmt_fill_array_close_open!` inside `dSFMT.jl`.
A little further down, you see:
```
28 ./REPL[1]:3; myfunc()
```
Line 3 of `myfunc` contains the call to `maximum`, and there were 28 (out of 80) backtraces taken here. Below that, you can see the specific places in `base/reduce.jl` that carry out the time-consuming operations in the `maximum` function for this type of input data.
Overall, we can tentatively conclude that generating the random numbers is approximately twice as expensive as finding the maximum element. We could increase our confidence in this result by collecting more samples:
```
julia> @profile (for i = 1:100; myfunc(); end)
julia> Profile.print()
[....]
3821 ./REPL[1]:2; myfunc()
3511 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type...
3511 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr...
310 ./random.jl:278; rand
[....]
2893 ./REPL[1]:3; myfunc()
2893 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinea...
[....]
```
In general, if you have `N` samples collected at a line, you can expect an uncertainty on the order of `sqrt(N)` (barring other sources of noise, like how busy the computer is with other tasks). The major exception to this rule is garbage collection, which runs infrequently but tends to be quite expensive. (Since Julia's garbage collector is written in C, such events can be detected using the `C=true` output mode described below, or by using [ProfileView.jl](https://github.com/timholy/ProfileView.jl).)
This illustrates the default "tree" dump; an alternative is the "flat" dump, which accumulates counts independent of their nesting:
```
julia> Profile.print(format=:flat)
Count File Line Function
6714 ./<missing> -1 anonymous
6714 ./REPL.jl 66 eval_user_input(::Any, ::Base.REPL.REPLBackend)
6714 ./REPL.jl 97 macro expansion
3821 ./REPL[1] 2 myfunc()
2893 ./REPL[1] 3 myfunc()
6714 ./REPL[7] 1 macro expansion
6714 ./boot.jl 235 eval(::Module, ::Any)
3511 ./dSFMT.jl 84 dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_s...
6714 ./event.jl 73 (::Base.REPL.##1#2{Base.REPL.REPLBackend})()
6714 ./profile.jl 23 macro expansion
3511 ./random.jl 431 rand!(::MersenneTwister, ::Array{Float64,3}, ::In...
310 ./random.jl 277 rand
310 ./random.jl 278 rand
310 ./random.jl 366 rand
310 ./random.jl 369 rand
2893 ./reduce.jl 270 _mapreduce(::Base.#identity, ::Base.#scalarmax, :...
5 ./reduce.jl 420 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
253 ./reduce.jl 426 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
2592 ./reduce.jl 428 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
43 ./reduce.jl 429 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
```
If your code has recursion, one potentially-confusing point is that a line in a "child" function can accumulate more counts than there are total backtraces. Consider the following function definitions:
```
dumbsum(n::Integer) = n == 1 ? 1 : 1 + dumbsum(n-1)
dumbsum3() = dumbsum(3)
```
If you were to profile `dumbsum3`, and a backtrace was taken while it was executing `dumbsum(1)`, the backtrace would look like this:
```
dumbsum3
dumbsum(3)
dumbsum(2)
dumbsum(1)
```
Consequently, this child function gets 3 counts, even though the parent only gets one. The "tree" representation makes this much clearer, and for this reason (among others) is probably the most useful way to view the results.
[Accumulation and clearing](#Accumulation-and-clearing)
--------------------------------------------------------
Results from [`@profile`](../../stdlib/profile/index#Profile.@profile) accumulate in a buffer; if you run multiple pieces of code under [`@profile`](../../stdlib/profile/index#Profile.@profile), then [`Profile.print()`](../../stdlib/profile/index#Profile.print) will show you the combined results. This can be very useful, but sometimes you want to start fresh; you can do so with [`Profile.clear()`](../../stdlib/profile/index#Profile.clear).
[Options for controlling the display of profile results](#Options-for-controlling-the-display-of-profile-results)
------------------------------------------------------------------------------------------------------------------
[`Profile.print`](../../stdlib/profile/index#Profile.print) has more options than we've described so far. Let's see the full declaration:
```
function print(io::IO = stdout, data = fetch(); kwargs...)
```
Let's first discuss the two positional arguments, and later the keyword arguments:
* `io` – Allows you to save the results to a buffer, e.g. a file, but the default is to print to `stdout` (the console).
* `data` – Contains the data you want to analyze; by default that is obtained from [`Profile.fetch()`](../../stdlib/profile/index#Profile.fetch), which pulls out the backtraces from a pre-allocated buffer. For example, if you want to profile the profiler, you could say:
```
data = copy(Profile.fetch())
Profile.clear()
@profile Profile.print(stdout, data) # Prints the previous results
Profile.print() # Prints results from Profile.print()
```
The keyword arguments can be any combination of:
* `format` – Introduced above, determines whether backtraces are printed with (default, `:tree`) or without (`:flat`) indentation indicating tree structure.
* `C` – If `true`, backtraces from C and Fortran code are shown (normally they are excluded). Try running the introductory example with `Profile.print(C = true)`. This can be extremely helpful in deciding whether it's Julia code or C code that is causing a bottleneck; setting `C = true` also improves the interpretability of the nesting, at the cost of longer profile dumps.
* `combine` – Some lines of code contain multiple operations; for example, `s += A[i]` contains both an array reference (`A[i]`) and a sum operation. These correspond to different lines in the generated machine code, and hence there may be two or more different addresses captured during backtraces on this line. `combine = true` lumps them together, and is probably what you typically want, but you can generate an output separately for each unique instruction pointer with `combine = false`.
* `maxdepth` – Limits frames at a depth higher than `maxdepth` in the `:tree` format.
* `sortedby` – Controls the order in `:flat` format. `:filefuncline` (default) sorts by the source line, whereas `:count` sorts in order of number of collected samples.
* `noisefloor` – Limits frames that are below the heuristic noise floor of the sample (only applies to format `:tree`). A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which `n <= noisefloor * √N`, where `n` is the number of samples on this line, and `N` is the number of samples for the callee.
* `mincount` – Limits frames with less than `mincount` occurrences.
File/function names are sometimes truncated (with `...`), and indentation is truncated with a `+n` at the beginning, where `n` is the number of extra spaces that would have been inserted, had there been room. If you want a complete profile of deeply-nested code, often a good idea is to save to a file using a wide `displaysize` in an [`IOContext`](../../base/io-network/index#Base.IOContext):
```
open("/tmp/prof.txt", "w") do s
Profile.print(IOContext(s, :displaysize => (24, 500)))
end
```
[Configuration](#Configuration)
--------------------------------
[`@profile`](../../stdlib/profile/index#Profile.@profile) just accumulates backtraces, and the analysis happens when you call [`Profile.print()`](../../stdlib/profile/index#Profile.print). For a long-running computation, it's entirely possible that the pre-allocated buffer for storing backtraces will be filled. If that happens, the backtraces stop but your computation continues. As a consequence, you may miss some important profiling data (you will get a warning when that happens).
You can obtain and configure the relevant parameters this way:
```
Profile.init() # returns the current settings
Profile.init(n = 10^7, delay = 0.01)
```
`n` is the total number of instruction pointers you can store, with a default value of `10^6`. If your typical backtrace is 20 instruction pointers, then you can collect 50000 backtraces, which suggests a statistical uncertainty of less than 1%. This may be good enough for most applications.
Consequently, you are more likely to need to modify `delay`, expressed in seconds, which sets the amount of time that Julia gets between snapshots to perform the requested computations. A very long-running job might not need frequent backtraces. The default setting is `delay = 0.001`. Of course, you can decrease the delay as well as increase it; however, the overhead of profiling grows once the delay becomes similar to the amount of time needed to take a backtrace (~30 microseconds on the author's laptop).
[Memory allocation analysis](#Memory-allocation-analysis)
----------------------------------------------------------
One of the most common techniques to improve performance is to reduce memory allocation. Julia provides several tools measure this:
###
[`@time`](#@time)
The total amount of allocation can be measured with [`@time`](../../base/base/index#Base.@time) and [`@allocated`](../../base/base/index#Base.@allocated), and specific lines triggering allocation can often be inferred from profiling via the cost of garbage collection that these lines incur. However, sometimes it is more efficient to directly measure the amount of memory allocated by each line of code.
###
[Line-by-Line Allocation Tracking](#Line-by-Line-Allocation-Tracking)
To measure allocation line-by-line, start Julia with the `--track-allocation=<setting>` command-line option, for which you can choose `none` (the default, do not measure allocation), `user` (measure memory allocation everywhere except Julia's core code), or `all` (measure memory allocation at each line of Julia code). Allocation gets measured for each line of compiled code. When you quit Julia, the cumulative results are written to text files with `.mem` appended after the file name, residing in the same directory as the source file. Each line lists the total number of bytes allocated. The [`Coverage` package](https://github.com/JuliaCI/Coverage.jl) contains some elementary analysis tools, for example to sort the lines in order of number of bytes allocated.
In interpreting the results, there are a few important details. Under the `user` setting, the first line of any function directly called from the REPL will exhibit allocation due to events that happen in the REPL code itself. More significantly, JIT-compilation also adds to allocation counts, because much of Julia's compiler is written in Julia (and compilation usually requires memory allocation). The recommended procedure is to force compilation by executing all the commands you want to analyze, then call [`Profile.clear_malloc_data()`](../../stdlib/profile/index#Profile.clear_malloc_data) to reset all allocation counters. Finally, execute the desired commands and quit Julia to trigger the generation of the `.mem` files.
###
[GC Logging](#GC-Logging)
While [`@time`](../../base/base/index#Base.@time) logs high-level stats about memory usage and garbage collection over the course of evaluating an expression, it can be useful to log each garbage collection event, to get an intuitive sense of how often the garbage collector is running, how long it's running each time, and how much garbage it collects each time. This can be enabled with [`GC.enable_logging(true)`](../../base/base/index#Base.GC.enable_logging), which causes Julia to log to stderr every time a garbage collection happens.
###
[Allocation Profiler](#Allocation-Profiler)
The allocation profiler records the stack trace, type, and size of each allocation while it is running. It can be invoked with [`Profile.Allocs.@profile`](../../stdlib/profile/index#Profile.Allocs.@profile).
This information about the allocations is returned as an array of `Alloc` objects, wrapped in an `AllocResults` object. The best way to visualize these is currently with the [PProf.jl](https://github.com/JuliaPerf/PProf.jl) library, which can visualize the call stacks which are making the most allocations.
The allocation profiler does have significant overhead, so a `sample_rate` argument can be passed to speed it up by making it skip some allocations. Passing `sample_rate=1.0` will make it record everything (which is slow); `sample_rate=0.1` will record only 10% of the allocations (faster), etc.
The current implementation of the Allocations Profiler *does not capture types for all allocations.* Allocations for which the profiler could not capture the type are represented as having type `Profile.Allocs.UnknownType`.
You can read more about the missing types and the plan to improve this, here: https://github.com/JuliaLang/julia/issues/43688.
[External Profiling](#External-Profiling)
------------------------------------------
Currently Julia supports `Intel VTune`, `OProfile` and `perf` as external profiling tools.
Depending on the tool you choose, compile with `USE_INTEL_JITEVENTS`, `USE_OPROFILE_JITEVENTS` and `USE_PERF_JITEVENTS` set to 1 in `Make.user`. Multiple flags are supported.
Before running Julia set the environment variable `ENABLE_JITPROFILING` to 1.
Now you have a multitude of ways to employ those tools! For example with `OProfile` you can try a simple recording :
```
>ENABLE_JITPROFILING=1 sudo operf -Vdebug ./julia test/fastmath.jl
>opreport -l `which ./julia`
```
Or similarly with `perf` :
```
$ ENABLE_JITPROFILING=1 perf record -o /tmp/perf.data --call-graph dwarf -k 1 ./julia /test/fastmath.jl
$ perf inject --jit --input /tmp/perf.data --output /tmp/perf-jit.data
$ perf report --call-graph -G -i /tmp/perf-jit.data
```
There are many more interesting things that you can measure about your program, to get a comprehensive list please read the [Linux perf examples page](https://www.brendangregg.com/perf.html).
Remember that perf saves for each execution a `perf.data` file that, even for small programs, can get quite large. Also the perf LLVM module saves temporarily debug objects in `~/.debug/jit`, remember to clean that folder frequently.
| programming_docs |
julia Scope of Variables Scope of Variables
==================
The *scope* of a variable is the region of code within which a variable is accessible. Variable scoping helps avoid variable naming conflicts. The concept is intuitive: two functions can both have arguments called `x` without the two `x`'s referring to the same thing. Similarly, there are many other cases where different blocks of code can use the same name without referring to the same thing. The rules for when the same variable name does or doesn't refer to the same thing are called scope rules; this section spells them out in detail.
Certain constructs in the language introduce *scope blocks*, which are regions of code that are eligible to be the scope of some set of variables. The scope of a variable cannot be an arbitrary set of source lines; instead, it will always line up with one of these blocks. There are two main types of scopes in Julia, *global scope* and *local scope*. The latter can be nested. There is also a distinction in Julia between constructs which introduce a "hard scope" and those which only introduce a "soft scope", which affects whether [shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) a global variable by the same name is allowed or not.
###
[Scope constructs](#man-scope-table)
The constructs introducing scope blocks are:
| Construct | Scope type | Allowed within |
| --- | --- | --- |
| [`module`](../../base/base/index#module), [`baremodule`](../../base/base/index#baremodule) | global | global |
| [`struct`](../../base/base/index#struct) | local (soft) | global |
| [`for`](../../base/base/index#for), [`while`](../../base/base/index#while), [`try`](../../base/base/index#try) | local (soft) | global, local |
| [`macro`](../../base/base/index#macro) | local (hard) | global |
| functions, [`do`](../../base/base/index#do) blocks, [`let`](../../base/base/index#let) blocks, comprehensions, generators | local (hard) | global, local |
Notably missing from this table are [begin blocks](../control-flow/index#man-compound-expressions) and [if blocks](../control-flow/index#man-conditional-evaluation) which do *not* introduce new scopes. The three types of scopes follow somewhat different rules which will be explained below.
Julia uses [lexical scoping](https://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scoping_vs._dynamic_scoping), meaning that a function's scope does not inherit from its caller's scope, but from the scope in which the function was defined. For example, in the following code the `x` inside `foo` refers to the `x` in the global scope of its module `Bar`:
```
julia> module Bar
x = 1
foo() = x
end;
```
and not a `x` in the scope where `foo` is used:
```
julia> import .Bar
julia> x = -1;
julia> Bar.foo()
1
```
Thus *lexical scope* means that what a variable in a particular piece of code refers to can be deduced from the code in which it appears alone and does not depend on how the program executes. A scope nested inside another scope can "see" variables in all the outer scopes in which it is contained. Outer scopes, on the other hand, cannot see variables in inner scopes.
[Global Scope](#Global-Scope)
------------------------------
Each module introduces a new global scope, separate from the global scope of all other modules—there is no all-encompassing global scope. Modules can introduce variables of other modules into their scope through the [using or import](../modules/index#modules) statements or through qualified access using the dot-notation, i.e. each module is a so-called *namespace* as well as a first-class data structure associating names with values. Note that while variable bindings can be read externally, they can only be changed within the module to which they belong. As an escape hatch, you can always evaluate code inside that module to modify a variable; this guarantees, in particular, that module bindings cannot be modified externally by code that never calls `eval`.
```
julia> module A
a = 1 # a global in A's scope
end;
julia> module B
module C
c = 2
end
b = C.c # can access the namespace of a nested global scope
# through a qualified access
import ..A # makes module A available
d = A.a
end;
julia> module D
b = a # errors as D's global scope is separate from A's
end;
ERROR: UndefVarError: a not defined
julia> module E
import ..A # make module A available
A.a = 2 # throws below error
end;
ERROR: cannot assign variables in other modules
```
If a top-level expression contains a variable declaration with keyword `local`, then that variable is not accessible outside that expression. The variable inside the expression does not affect global variables of the same name. An example is to declare `local x` in a `begin` or `if` block at the top-level:
```
julia> x = 1
begin
local x = 0
@show x
end
@show x;
x = 0
x = 1
```
Note that the interactive prompt (aka REPL) is in the global scope of the module `Main`.
[Local Scope](#Local-Scope)
----------------------------
A new local scope is introduced by most code blocks (see above [table](#man-scope-table) for a complete list). If such a block is syntactically nested inside of another local scope, the scope it creates is nested inside of all the local scopes that it appears within, which are all ultimately nested inside of the global scope of the module in which the code is evaluated. Variables in outer scopes are visible from any scope they contain — meaning that they can be read and written in inner scopes — unless there is a local variable with the same name that "shadows" the outer variable of the same name. This is true even if the outer local is declared after (in the sense of textually below) an inner block. When we say that a variable "exists" in a given scope, this means that a variable by that name exists in any of the scopes that the current scope is nested inside of, including the current one.
Some programming languages require explicitly declaring new variables before using them. Explicit declaration works in Julia too: in any local scope, writing `local x` declares a new local variable in that scope, regardless of whether there is already a variable named `x` in an outer scope or not. Declaring each new variable like this is somewhat verbose and tedious, however, so Julia, like many other languages, considers assignment to a variable name that doesn't already exist to implicitly declare that variable. If the current scope is global, the new variable is global; if the current scope is local, the new variable is local to the innermost local scope and will be visible inside of that scope but not outside of it. If you assign to an existing local, it *always* updates that existing local: you can only shadow a local by explicitly declaring a new local in a nested scope with the `local` keyword. In particular, this applies to variables assigned in inner functions, which may surprise users coming from Python where assignment in an inner function creates a new local unless the variable is explicitly declared to be non-local.
Mostly this is pretty intuitive, but as with many things that behave intuitively, the details are more subtle than one might naïvely imagine.
When `x = <value>` occurs in a local scope, Julia applies the following rules to decide what the expression means based on where the assignment expression occurs and what `x` already refers to at that location:
1. **Existing local:** If `x` is *already a local variable*, then the existing local `x` is assigned;
2. **Hard scope:** If `x` is *not already a local variable* and assignment occurs inside of any hard scope construct (i.e. within a `let` block, function or macro body, comprehension, or generator), a new local named `x` is created in the scope of the assignment;
3. **Soft scope:** If `x` is *not already a local variable* and all of the scope constructs containing the assignment are soft scopes (loops, `try`/`catch` blocks, or `struct` blocks), the behavior depends on whether the global variable `x` is defined:
* if global `x` is *undefined*, a new local named `x` is created in the scope of the assignment;
* if global `x` is *defined*, the assignment is considered ambiguous:
+ in *non-interactive* contexts (files, eval), an ambiguity warning is printed and a new local is created;
+ in *interactive* contexts (REPL, notebooks), the global variable `x` is assigned.
You may note that in non-interactive contexts the hard and soft scope behaviors are identical except that a warning is printed when an implicitly local variable (i.e. not declared with `local x`) shadows a global. In interactive contexts, the rules follow a more complex heuristic for the sake of convenience. This is covered in depth in examples that follow.
Now that you know the rules, let's look at some examples. Each example is assumed to be evaluated in a fresh REPL session so that the only globals in each snippet are the ones that are assigned in that block of code.
We'll begin with a nice and clear-cut situation—assignment inside of a hard scope, in this case a function body, when no local variable by that name already exists:
```
julia> function greet()
x = "hello" # new local
println(x)
end
greet (generic function with 1 method)
julia> greet()
hello
julia> x # global
ERROR: UndefVarError: x not defined
```
Inside of the `greet` function, the assignment `x = "hello"` causes `x` to be a new local variable in the function's scope. There are two relevant facts: the assignment occurs in local scope and there is no existing local `x` variable. Since `x` is local, it doesn't matter if there is a global named `x` or not. Here for example we define `x = 123` before defining and calling `greet`:
```
julia> x = 123 # global
123
julia> function greet()
x = "hello" # new local
println(x)
end
greet (generic function with 1 method)
julia> greet()
hello
julia> x # global
123
```
Since the `x` in `greet` is local, the value (or lack thereof) of the global `x` is unaffected by calling `greet`. The hard scope rule doesn't care whether a global named `x` exists or not: assignment to `x` in a hard scope is local (unless `x` is declared global).
The next clear cut situation we'll consider is when there is already a local variable named `x`, in which case `x = <value>` always assigns to this existing local `x`. This is true whether the assignment occurs in the same local scope, an inner local scope in the same function body, or in the body of a function nested inside of another function, also known as a [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)).
We'll use the `sum_to` function, which computes the sum of integers from one up to `n`, as an example:
```
function sum_to(n)
s = 0 # new local
for i = 1:n
s = s + i # assign existing local
end
return s # same local
end
```
As in the previous example, the first assignment to `s` at the top of `sum_to` causes `s` to be a new local variable in the body of the function. The `for` loop has its own inner local scope within the function scope. At the point where `s = s + i` occurs, `s` is already a local variable, so the assignment updates the existing `s` instead of creating a new local. We can test this out by calling `sum_to` in the REPL:
```
julia> function sum_to(n)
s = 0 # new local
for i = 1:n
s = s + i # assign existing local
end
return s # same local
end
sum_to (generic function with 1 method)
julia> sum_to(10)
55
julia> s # global
ERROR: UndefVarError: s not defined
```
Since `s` is local to the function `sum_to`, calling the function has no effect on the global variable `s`. We can also see that the update `s = s + i` in the `for` loop must have updated the same `s` created by the initialization `s = 0` since we get the correct sum of 55 for the integers 1 through 10.
Let's dig into the fact that the `for` loop body has its own scope for a second by writing a slightly more verbose variation which we'll call `sum_to_def`, in which we save the sum `s + i` in a variable `t` before updating `s`:
```
julia> function sum_to_def(n)
s = 0 # new local
for i = 1:n
t = s + i # new local `t`
s = t # assign existing local `s`
end
return s, @isdefined(t)
end
sum_to_def (generic function with 1 method)
julia> sum_to_def(10)
(55, false)
```
This version returns `s` as before but it also uses the `@isdefined` macro to return a boolean indicating whether there is a local variable named `t` defined in the function's outermost local scope. As you can see, there is no `t` defined outside of the `for` loop body. This is because of the hard scope rule again: since the assignment to `t` occurs inside of a function, which introduces a hard scope, the assignment causes `t` to become a new local variable in the local scope where it appears, i.e. inside of the loop body. Even if there were a global named `t`, it would make no difference—the hard scope rule isn't affected by anything in global scope.
Note that the local scope of a for loop body is no different from the local scope of an inner function. This means that we could rewrite this example so that the loop body is implemented as a call to an inner helper function and it behaves the same way:
```
julia> function sum_to_def_closure(n)
function loop_body(i)
t = s + i # new local `t`
s = t # assign same local `s` as below
end
s = 0 # new local
for i = 1:n
loop_body(i)
end
return s, @isdefined(t)
end
sum_to_def_closure (generic function with 1 method)
julia> sum_to_def_closure(10)
(55, false)
```
This example illustrates a couple of key points:
1. Inner function scopes are just like any other nested local scope. In particular, if a variable is already a local outside of an inner function and you assign to it in the inner function, the outer local variable is updated.
2. It doesn't matter if the definition of an outer local happens below where it is updated, the rule remains the same. The entire enclosing local scope is parsed and its locals determined before inner local meanings are resolved.
This design means that you can generally move code in or out of an inner function without changing its meaning, which facilitates a number of common idioms in the language using closures (see [do blocks](../functions/index#Do-Block-Syntax-for-Function-Arguments)).
Let's move onto some more ambiguous cases covered by the soft scope rule. We'll explore this by extracting the bodies of the `greet` and `sum_to_def` functions into soft scope contexts. First, let's put the body of `greet` in a `for` loop—which is soft, rather than hard—and evaluate it in the REPL:
```
julia> for i = 1:3
x = "hello" # new local
println(x)
end
hello
hello
hello
julia> x
ERROR: UndefVarError: x not defined
```
Since the global `x` is not defined when the `for` loop is evaluated, the first clause of the soft scope rule applies and `x` is created as local to the `for` loop and therefore global `x` remains undefined after the loop executes. Next, let's consider the body of `sum_to_def` extracted into global scope, fixing its argument to `n = 10`
```
s = 0
for i = 1:10
t = s + i
s = t
end
s
@isdefined(t)
```
What does this code do? Hint: it's a trick question. The answer is "it depends." If this code is entered interactively, it behaves the same way it does in a function body. But if the code appears in a file, it prints an ambiguity warning and throws an undefined variable error. Let's see it working in the REPL first:
```
julia> s = 0 # global
0
julia> for i = 1:10
t = s + i # new local `t`
s = t # assign global `s`
end
julia> s # global
55
julia> @isdefined(t) # global
false
```
The REPL approximates being in the body of a function by deciding whether assignment inside the loop assigns to a global or creates new local based on whether a global variable by that name is defined or not. If a global by the name exists, then the assignment updates it. If no global exists, then the assignment creates a new local variable. In this example we see both cases in action:
* There is no global named `t`, so `t = s + i` creates a new `t` that is local to the `for` loop;
* There is a global named `s`, so `s = t` assigns to it.
The second fact is why execution of the loop changes the global value of `s` and the first fact is why `t` is still undefined after the loop executes. Now, let's try evaluating this same code as though it were in a file instead:
```
julia> code = """
s = 0 # global
for i = 1:10
t = s + i # new local `t`
s = t # new local `s` with warning
end
s, # global
@isdefined(t) # global
""";
julia> include_string(Main, code)
┌ Warning: Assignment to `s` in soft scope is ambiguous because a global variable by the same name exists: `s` will be treated as a new local. Disambiguate by using `local s` to suppress this warning or `global s` to assign to the existing global variable.
└ @ string:4
ERROR: LoadError: UndefVarError: s not defined
```
Here we use [`include_string`](../../base/base/index#Base.include_string), to evaluate `code` as though it were the contents of a file. We could also save `code` to a file and then call `include` on that file—the result would be the same. As you can see, this behaves quite different from evaluating the same code in the REPL. Let's break down what's happening here:
* global `s` is defined with the value `0` before the loop is evaluated
* the assignment `s = t` occurs in a soft scope—a `for` loop outside of any function body or other hard scope construct
* therefore the second clause of the soft scope rule applies, and the assignment is ambiguous so a warning is emitted
* execution continues, making `s` local to the `for` loop body
* since `s` is local to the `for` loop, it is undefined when `t = s + i` is evaluated, causing an error
* evaluation stops there, but if it got to `s` and `@isdefined(t)`, it would return `0` and `false`.
This demonstrates some important aspects of scope: in a scope, each variable can only have one meaning, and that meaning is determined regardless of the order of expressions. The presence of the expression `s = t` in the loop causes `s` to be local to the loop, which means that it is also local when it appears on the right hand side of `t = s + i`, even though that expression appears first and is evaluated first. One might imagine that the `s` on the first line of the loop could be global while the `s` on the second line of the loop is local, but that's not possible since the two lines are in the same scope block and each variable can only mean one thing in a given scope.
####
[On Soft Scope](#on-soft-scope)
We have now covered all the local scope rules, but before wrapping up this section, perhaps a few words should be said about why the ambiguous soft scope case is handled differently in interactive and non-interactive contexts. There are two obvious questions one could ask:
1. Why doesn't it just work like the REPL everywhere?
2. Why doesn't it just work like in files everywhere? And maybe skip the warning?
In Julia ≤ 0.6, all global scopes did work like the current REPL: when `x = <value>` occurred in a loop (or `try`/`catch`, or `struct` body) but outside of a function body (or `let` block or comprehension), it was decided based on whether a global named `x` was defined or not whether `x` should be local to the loop. This behavior has the advantage of being intuitive and convenient since it approximates the behavior inside of a function body as closely as possible. In particular, it makes it easy to move code back and forth between a function body and the REPL when trying to debug the behavior of a function. However, it has some downsides. First, it's quite a complex behavior: many people over the years were confused about this behavior and complained that it was complicated and hard both to explain and understand. Fair point. Second, and arguably worse, is that it's bad for programming "at scale." When you see a small piece of code in one place like this, it's quite clear what's going on:
```
s = 0
for i = 1:10
s += i
end
```
Obviously the intention is to modify the existing global variable `s`. What else could it mean? However, not all real world code is so short or so clear. We found that code like the following often occurs in the wild:
```
x = 123
# much later
# maybe in a different file
for i = 1:10
x = "hello"
println(x)
end
# much later
# maybe in yet another file
# or maybe back in the first one where `x = 123`
y = x + 234
```
It's far less clear what should happen here. Since `x + "hello"` is a method error, it seems probable that the intention is for `x` to be local to the `for` loop. But runtime values and what methods happen to exist cannot be used to determine the scopes of variables. With the Julia ≤ 0.6 behavior, it's especially concerning that someone might have written the `for` loop first, had it working just fine, but later when someone else adds a new global far away—possibly in a different file—the code suddenly changes meaning and either breaks noisily or, worse still, silently does the wrong thing. This kind of ["spooky action at a distance"](https://en.wikipedia.org/wiki/Action_at_a_distance_(computer_programming)) is something that good programming language designs should prevent.
So in Julia 1.0, we simplified the rules for scope: in any local scope, assignment to a name that wasn't already a local variable created a new local variable. This eliminated the notion of soft scope entirely as well as removing the potential for spooky action. We uncovered and fixed a significant number of bugs due to the removal of soft scope, vindicating the choice to get rid of it. And there was much rejoicing! Well, no, not really. Because some people were angry that they now had to write:
```
s = 0
for i = 1:10
global s += i
end
```
Do you see that `global` annotation in there? Hideous. Obviously this situation could not be tolerated. But seriously, there are two main issues with requiring `global` for this kind of top-level code:
1. It's no longer convenient to copy and paste the code from inside a function body into the REPL to debug it—you have to add `global` annotations and then remove them again to go back;
2. Beginners will write this kind of code without the `global` and have no idea why their code doesn't work—the error that they get is that `s` is undefined, which does not seem to enlighten anyone who happens to make this mistake.
As of Julia 1.5, this code works without the `global` annotation in interactive contexts like the REPL or Jupyter notebooks (just like Julia 0.6) and in files and other non-interactive contexts, it prints this very direct warning:
> Assignment to `s` in soft scope is ambiguous because a global variable by the same name exists: `s` will be treated as a new local. Disambiguate by using `local s` to suppress this warning or `global s` to assign to the existing global variable.
>
>
This addresses both issues while preserving the "programming at scale" benefits of the 1.0 behavior: global variables have no spooky effect on the meaning of code that may be far away; in the REPL copy-and-paste debugging works and beginners don't have any issues; any time someone either forgets a `global` annotation or accidentally shadows an existing global with a local in a soft scope, which would be confusing anyway, they get a nice clear warning.
An important property of this design is that any code that executes in a file without a warning will behave the same way in a fresh REPL. And on the flip side, if you take a REPL session and save it to file, if it behaves differently than it did in the REPL, then you will get a warning.
###
[Let Blocks](#Let-Blocks)
`let` statements create a new *hard scope* block (see above) and introduce new variable bindings each time they run. The variable need not be immediately assigned:
```
julia> var1 = let x
for i in 1:5
(i == 4) && (x = i; break)
end
x
end
4
```
Whereas assignments might reassign a new value to an existing value location, `let` always creates a new location. This difference is usually not important, and is only detectable in the case of variables that outlive their scope via closures. The `let` syntax accepts a comma-separated series of assignments and variable names:
```
julia> x, y, z = -1, -1, -1;
julia> let x = 1, z
println("x: $x, y: $y") # x is local variable, y the global
println("z: $z") # errors as z has not been assigned yet but is local
end
x: 1, y: -1
ERROR: UndefVarError: z not defined
```
The assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like `let x = x` since the two `x` variables are distinct and have separate storage. Here is an example where the behavior of `let` is needed:
```
julia> Fs = Vector{Any}(undef, 2); i = 1;
julia> while i <= 2
Fs[i] = ()->i
global i += 1
end
julia> Fs[1]()
3
julia> Fs[2]()
3
```
Here we create and store two closures that return variable `i`. However, it is always the same variable `i`, so the two closures behave identically. We can use `let` to create a new binding for `i`:
```
julia> Fs = Vector{Any}(undef, 2); i = 1;
julia> while i <= 2
let i = i
Fs[i] = ()->i
end
global i += 1
end
julia> Fs[1]()
1
julia> Fs[2]()
2
```
Since the `begin` construct does not introduce a new scope, it can be useful to use a zero-argument `let` to just introduce a new scope block without creating any new bindings immediately:
```
julia> let
local x = 1
let
local x = 2
end
x
end
1
```
Since `let` introduces a new scope block, the inner local `x` is a different variable than the outer local `x`. This particular example is equivalent to:
```
julia> let x = 1
let x = 2
end
x
end
1
```
###
[Loops and Comprehensions](#Loops-and-Comprehensions)
In loops and [comprehensions](../arrays/index#man-comprehensions), new variables introduced in their body scopes are freshly allocated for each loop iteration, as if the loop body were surrounded by a `let` block, as demonstrated by this example:
```
julia> Fs = Vector{Any}(undef, 2);
julia> for j = 1:2
Fs[j] = ()->j
end
julia> Fs[1]()
1
julia> Fs[2]()
2
```
A `for` loop or comprehension iteration variable is always a new variable:
```
julia> function f()
i = 0
for i = 1:3
# empty
end
return i
end;
julia> f()
0
```
However, it is occasionally useful to reuse an existing local variable as the iteration variable. This can be done conveniently by adding the keyword `outer`:
```
julia> function f()
i = 0
for outer i = 1:3
# empty
end
return i
end;
julia> f()
3
```
[Constants](#Constants)
------------------------
A common use of variables is giving names to specific, unchanging values. Such variables are only assigned once. This intent can be conveyed to the compiler using the [`const`](../../base/base/index#const) keyword:
```
julia> const e = 2.71828182845904523536;
julia> const pi = 3.14159265358979323846;
```
Multiple variables can be declared in a single `const` statement:
```
julia> const a, b = 1, 2
(1, 2)
```
The `const` declaration should only be used in global scope on globals. It is difficult for the compiler to optimize code involving global variables, since their values (or even their types) might change at almost any time. If a global variable will not change, adding a `const` declaration solves this performance problem.
Local constants are quite different. The compiler is able to determine automatically when a local variable is constant, so local constant declarations are not necessary, and in fact are currently not supported.
Special top-level assignments, such as those performed by the `function` and `struct` keywords, are constant by default.
Note that `const` only affects the variable binding; the variable may be bound to a mutable object (such as an array), and that object may still be modified. Additionally when one tries to assign a value to a variable that is declared constant the following scenarios are possible:
* if a new value has a different type than the type of the constant then an error is thrown:
```
julia> const x = 1.0
1.0
julia> x = 1
ERROR: invalid redefinition of constant x
```
* if a new value has the same type as the constant then a warning is printed:
```
julia> const y = 1.0
1.0
julia> y = 2.0
WARNING: redefinition of constant y. This may fail, cause incorrect answers, or produce other errors.
2.0
```
* if an assignment would not result in the change of variable value no message is given:
```
julia> const z = 100
100
julia> z = 100
100
```
The last rule applies to immutable objects even if the variable binding would change, e.g.:
```
julia> const s1 = "1"
"1"
julia> s2 = "1"
"1"
julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
Ptr{UInt8} @0x00000000132c9638
Ptr{UInt8} @0x0000000013dd3d18
julia> s1 = s2
"1"
julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
Ptr{UInt8} @0x0000000013dd3d18
Ptr{UInt8} @0x0000000013dd3d18
```
However, for mutable objects the warning is printed as expected:
```
julia> const a = [1]
1-element Vector{Int64}:
1
julia> a = [1]
WARNING: redefinition of constant a. This may fail, cause incorrect answers, or produce other errors.
1-element Vector{Int64}:
1
```
Note that although sometimes possible, changing the value of a `const` variable is strongly discouraged, and is intended only for convenience during interactive use. Changing constants can cause various problems or unexpected behaviors. For instance, if a method references a constant and is already compiled before the constant is changed, then it might keep using the old value:
```
julia> const x = 1
1
julia> f() = x
f (generic function with 1 method)
julia> f()
1
julia> x = 2
WARNING: redefinition of constant x. This may fail, cause incorrect answers, or produce other errors.
2
julia> f()
1
```
[Typed Globals](#man-typed-globals)
------------------------------------
Support for typed globals was added in Julia 1.8
Similar to being declared as constants, global bindings can also be declared to always be of a constant type. This can either be done without assigning an actual value using the syntax `global x::T` or upon assignment as `x::T = 123`.
```
julia> x::Float64 = 2.718
2.718
julia> f() = x
f (generic function with 1 method)
julia> Base.return_types(f)
1-element Vector{Any}:
Float64
```
For any assignment to a global, Julia will first try to convert it to the appropriate type using [`convert`](../../base/base/index#Base.convert):
```
julia> global y::Int
julia> y = 1.0
1.0
julia> y
1
julia> y = 3.14
ERROR: InexactError: Int64(3.14)
Stacktrace:
[...]
```
The type does not need to be concrete, but annotations with abstract types typically have little performance benefit.
Once a global has either been assigned to or its type has been set, the binding type is not allowed to change:
```
julia> x = 1
1
julia> global x::Int
ERROR: cannot set type for global x. It already has a value or is already set to a different type.
Stacktrace:
[...]
```
| programming_docs |
julia Performance Tips Performance Tips
================
In the following sections, we briefly go through a few techniques that can help make your Julia code run as fast as possible.
[Performance critical code should be inside a function](#Performance-critical-code-should-be-inside-a-function)
----------------------------------------------------------------------------------------------------------------
Any code that is performance critical should be inside a function. Code inside functions tends to run much faster than top level code, due to how Julia's compiler works.
The use of functions is not only important for performance: functions are more reusable and testable, and clarify what steps are being done and what their inputs and outputs are, [Write functions, not just scripts](../style-guide/index#Write-functions,-not-just-scripts) is also a recommendation of Julia's Styleguide.
The functions should take arguments, instead of operating directly on global variables, see the next point.
[Avoid untyped global variables](#Avoid-untyped-global-variables)
------------------------------------------------------------------
An untyped global variable might have its value, and therefore possibly its type, changed at any point. This makes it difficult for the compiler to optimize code using global variables. This also applies to type-valued variables, i.e. type aliases on the global level. Variables should be local, or passed as arguments to functions, whenever possible.
We find that global names are frequently constants, and declaring them as such greatly improves performance:
```
const DEFAULT_VAL = 0
```
If a global is known to always be of the same type, [the type should be annotated](../variables-and-scoping/index#man-typed-globals).
Uses of untyped globals can be optimized by annotating their types at the point of use:
```
global x = rand(1000)
function loop_over_global()
s = 0.0
for i in x::Vector{Float64}
s += i
end
return s
end
```
Passing arguments to functions is better style. It leads to more reusable code and clarifies what the inputs and outputs are.
All code in the REPL is evaluated in global scope, so a variable defined and assigned at top level will be a **global** variable. Variables defined at top level scope inside modules are also global.
In the following REPL session:
```
julia> x = 1.0
```
is equivalent to:
```
julia> global x = 1.0
```
so all the performance issues discussed previously apply.
[Measure performance with](#Measure-performance-with-%5B@time%5D(@ref)-and-pay-attention-to-memory-allocation) [`@time`](../../base/base/index#Base.@time) and pay attention to memory allocation
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
A useful tool for measuring performance is the [`@time`](../../base/base/index#Base.@time) macro. We here repeat the example with the global variable above, but this time with the type annotation removed:
```
julia> x = rand(1000);
julia> function sum_global()
s = 0.0
for i in x
s += i
end
return s
end;
julia> @time sum_global()
0.011539 seconds (9.08 k allocations: 373.386 KiB, 98.69% compilation time)
523.0007221951678
julia> @time sum_global()
0.000091 seconds (3.49 k allocations: 70.156 KiB)
523.0007221951678
```
On the first call (`@time sum_global()`) the function gets compiled. (If you've not yet used [`@time`](../../base/base/index#Base.@time) in this session, it will also compile functions needed for timing.) You should not take the results of this run seriously. For the second run, note that in addition to reporting the time, it also indicated that a significant amount of memory was allocated. We are here just computing a sum over all elements in a vector of 64-bit floats so there should be no need to allocate memory (at least not on the heap which is what `@time` reports).
Unexpected memory allocation is almost always a sign of some problem with your code, usually a problem with type-stability or creating many small temporary arrays. Consequently, in addition to the allocation itself, it's very likely that the code generated for your function is far from optimal. Take such indications seriously and follow the advice below.
If we instead pass `x` as an argument to the function it no longer allocates memory (the allocation reported below is due to running the `@time` macro in global scope) and is significantly faster after the first call:
```
julia> x = rand(1000);
julia> function sum_arg(x)
s = 0.0
for i in x
s += i
end
return s
end;
julia> @time sum_arg(x)
0.007551 seconds (3.98 k allocations: 200.548 KiB, 99.77% compilation time)
523.0007221951678
julia> @time sum_arg(x)
0.000006 seconds (1 allocation: 16 bytes)
523.0007221951678
```
The 1 allocation seen is from running the `@time` macro itself in global scope. If we instead run the timing in a function, we can see that indeed no allocations are performed:
```
julia> time_sum(x) = @time sum_arg(x);
julia> time_sum(x)
0.000002 seconds
523.0007221951678
```
In some situations, your function may need to allocate memory as part of its operation, and this can complicate the simple picture above. In such cases, consider using one of the [tools](#tools) below to diagnose problems, or write a version of your function that separates allocation from its algorithmic aspects (see [Pre-allocating outputs](#Pre-allocating-outputs)).
For more serious benchmarking, consider the [BenchmarkTools.jl](https://github.com/JuliaCI/BenchmarkTools.jl) package which among other things evaluates the function multiple times in order to reduce noise.
[Tools](#tools)
----------------
Julia and its package ecosystem includes tools that may help you diagnose problems and improve the performance of your code:
* [Profiling](../profile/index#Profiling) allows you to measure the performance of your running code and identify lines that serve as bottlenecks. For complex projects, the [ProfileView](https://github.com/timholy/ProfileView.jl) package can help you visualize your profiling results.
* The [Traceur](https://github.com/JunoLab/Traceur.jl) package can help you find common performance problems in your code.
* Unexpectedly-large memory allocations–as reported by [`@time`](../../base/base/index#Base.@time), [`@allocated`](../../base/base/index#Base.@allocated), or the profiler (through calls to the garbage-collection routines)–hint that there might be issues with your code. If you don't see another reason for the allocations, suspect a type problem. You can also start Julia with the `--track-allocation=user` option and examine the resulting `*.mem` files to see information about where those allocations occur. See [Memory allocation analysis](../profile/index#Memory-allocation-analysis).
* `@code_warntype` generates a representation of your code that can be helpful in finding expressions that result in type uncertainty. See [`@code_warntype`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_warntype) below.
[Avoid containers with abstract type parameters](#man-performance-abstract-container)
--------------------------------------------------------------------------------------
When working with parameterized types, including arrays, it is best to avoid parameterizing with abstract types where possible.
Consider the following:
```
julia> a = Real[]
Real[]
julia> push!(a, 1); push!(a, 2.0); push!(a, π)
3-element Vector{Real}:
1
2.0
π = 3.1415926535897...
```
Because `a` is an array of abstract type [`Real`](../../base/numbers/index#Core.Real), it must be able to hold any `Real` value. Since `Real` objects can be of arbitrary size and structure, `a` must be represented as an array of pointers to individually allocated `Real` objects. However, if we instead only allow numbers of the same type, e.g. [`Float64`](../../base/numbers/index#Core.Float64), to be stored in `a` these can be stored more efficiently:
```
julia> a = Float64[]
Float64[]
julia> push!(a, 1); push!(a, 2.0); push!(a, π)
3-element Vector{Float64}:
1.0
2.0
3.141592653589793
```
Assigning numbers into `a` will now convert them to `Float64` and `a` will be stored as a contiguous block of 64-bit floating-point values that can be manipulated efficiently.
If you cannot avoid containers with abstract value types, it is sometimes better to parametrize with `Any` to avoid runtime type checking. E.g. `IdDict{Any, Any}` performs better than `IdDict{Type, Vector}`
See also the discussion under [Parametric Types](../types/index#Parametric-Types).
[Type declarations](#Type-declarations)
----------------------------------------
In many languages with optional type declarations, adding declarations is the principal way to make code run faster. This is *not* the case in Julia. In Julia, the compiler generally knows the types of all function arguments, local variables, and expressions. However, there are a few specific instances where declarations are helpful.
###
[Avoid fields with abstract type](#Avoid-fields-with-abstract-type)
Types can be declared without specifying the types of their fields:
```
julia> struct MyAmbiguousType
a
end
```
This allows `a` to be of any type. This can often be useful, but it does have a downside: for objects of type `MyAmbiguousType`, the compiler will not be able to generate high-performance code. The reason is that the compiler uses the types of objects, not their values, to determine how to build code. Unfortunately, very little can be inferred about an object of type `MyAmbiguousType`:
```
julia> b = MyAmbiguousType("Hello")
MyAmbiguousType("Hello")
julia> c = MyAmbiguousType(17)
MyAmbiguousType(17)
julia> typeof(b)
MyAmbiguousType
julia> typeof(c)
MyAmbiguousType
```
The values of `b` and `c` have the same type, yet their underlying representation of data in memory is very different. Even if you stored just numeric values in field `a`, the fact that the memory representation of a [`UInt8`](../../base/numbers/index#Core.UInt8) differs from a [`Float64`](../../base/numbers/index#Core.Float64) also means that the CPU needs to handle them using two different kinds of instructions. Since the required information is not available in the type, such decisions have to be made at run-time. This slows performance.
You can do better by declaring the type of `a`. Here, we are focused on the case where `a` might be any one of several types, in which case the natural solution is to use parameters. For example:
```
julia> mutable struct MyType{T<:AbstractFloat}
a::T
end
```
This is a better choice than
```
julia> mutable struct MyStillAmbiguousType
a::AbstractFloat
end
```
because the first version specifies the type of `a` from the type of the wrapper object. For example:
```
julia> m = MyType(3.2)
MyType{Float64}(3.2)
julia> t = MyStillAmbiguousType(3.2)
MyStillAmbiguousType(3.2)
julia> typeof(m)
MyType{Float64}
julia> typeof(t)
MyStillAmbiguousType
```
The type of field `a` can be readily determined from the type of `m`, but not from the type of `t`. Indeed, in `t` it's possible to change the type of the field `a`:
```
julia> typeof(t.a)
Float64
julia> t.a = 4.5f0
4.5f0
julia> typeof(t.a)
Float32
```
In contrast, once `m` is constructed, the type of `m.a` cannot change:
```
julia> m.a = 4.5f0
4.5f0
julia> typeof(m.a)
Float64
```
The fact that the type of `m.a` is known from `m`'s type—coupled with the fact that its type cannot change mid-function—allows the compiler to generate highly-optimized code for objects like `m` but not for objects like `t`.
Of course, all of this is true only if we construct `m` with a concrete type. We can break this by explicitly constructing it with an abstract type:
```
julia> m = MyType{AbstractFloat}(3.2)
MyType{AbstractFloat}(3.2)
julia> typeof(m.a)
Float64
julia> m.a = 4.5f0
4.5f0
julia> typeof(m.a)
Float32
```
For all practical purposes, such objects behave identically to those of `MyStillAmbiguousType`.
It's quite instructive to compare the sheer amount of code generated for a simple function
```
func(m::MyType) = m.a+1
```
using
```
code_llvm(func, Tuple{MyType{Float64}})
code_llvm(func, Tuple{MyType{AbstractFloat}})
```
For reasons of length the results are not shown here, but you may wish to try this yourself. Because the type is fully-specified in the first case, the compiler doesn't need to generate any code to resolve the type at run-time. This results in shorter and faster code.
One should also keep in mind that not-fully-parameterized types behave like abstract types. For example, even though a fully specified `Array{T,n}` is concrete, `Array` itself with no parameters given is not concrete:
```
julia> !isconcretetype(Array), !isabstracttype(Array), isstructtype(Array), !isconcretetype(Array{Int}), isconcretetype(Array{Int,1})
(true, true, true, true, true)
```
In this case, it would be better to avoid declaring `MyType` with a field `a::Array` and instead declare the field as `a::Array{T,N}` or as `a::A`, where `{T,N}` or `A` are parameters of `MyType`.
###
[Avoid fields with abstract containers](#Avoid-fields-with-abstract-containers)
The same best practices also work for container types:
```
julia> struct MySimpleContainer{A<:AbstractVector}
a::A
end
julia> struct MyAmbiguousContainer{T}
a::AbstractVector{T}
end
julia> struct MyAlsoAmbiguousContainer
a::Array
end
```
For example:
```
julia> c = MySimpleContainer(1:3);
julia> typeof(c)
MySimpleContainer{UnitRange{Int64}}
julia> c = MySimpleContainer([1:3;]);
julia> typeof(c)
MySimpleContainer{Vector{Int64}}
julia> b = MyAmbiguousContainer(1:3);
julia> typeof(b)
MyAmbiguousContainer{Int64}
julia> b = MyAmbiguousContainer([1:3;]);
julia> typeof(b)
MyAmbiguousContainer{Int64}
julia> d = MyAlsoAmbiguousContainer(1:3);
julia> typeof(d), typeof(d.a)
(MyAlsoAmbiguousContainer, Vector{Int64})
julia> d = MyAlsoAmbiguousContainer(1:1.0:3);
julia> typeof(d), typeof(d.a)
(MyAlsoAmbiguousContainer, Vector{Float64})
```
For `MySimpleContainer`, the object is fully-specified by its type and parameters, so the compiler can generate optimized functions. In most instances, this will probably suffice.
While the compiler can now do its job perfectly well, there are cases where *you* might wish that your code could do different things depending on the *element type* of `a`. Usually the best way to achieve this is to wrap your specific operation (here, `foo`) in a separate function:
```
julia> function sumfoo(c::MySimpleContainer)
s = 0
for x in c.a
s += foo(x)
end
s
end
sumfoo (generic function with 1 method)
julia> foo(x::Integer) = x
foo (generic function with 1 method)
julia> foo(x::AbstractFloat) = round(x)
foo (generic function with 2 methods)
```
This keeps things simple, while allowing the compiler to generate optimized code in all cases.
However, there are cases where you may need to declare different versions of the outer function for different element types or types of the `AbstractVector` of the field `a` in `MySimpleContainer`. You could do it like this:
```
julia> function myfunc(c::MySimpleContainer{<:AbstractArray{<:Integer}})
return c.a[1]+1
end
myfunc (generic function with 1 method)
julia> function myfunc(c::MySimpleContainer{<:AbstractArray{<:AbstractFloat}})
return c.a[1]+2
end
myfunc (generic function with 2 methods)
julia> function myfunc(c::MySimpleContainer{Vector{T}}) where T <: Integer
return c.a[1]+3
end
myfunc (generic function with 3 methods)
```
```
julia> myfunc(MySimpleContainer(1:3))
2
julia> myfunc(MySimpleContainer(1.0:3))
3.0
julia> myfunc(MySimpleContainer([1:3;]))
4
```
###
[Annotate values taken from untyped locations](#Annotate-values-taken-from-untyped-locations)
It is often convenient to work with data structures that may contain values of any type (arrays of type `Array{Any}`). But, if you're using one of these structures and happen to know the type of an element, it helps to share this knowledge with the compiler:
```
function foo(a::Array{Any,1})
x = a[1]::Int32
b = x+1
...
end
```
Here, we happened to know that the first element of `a` would be an [`Int32`](../../base/numbers/index#Core.Int32). Making an annotation like this has the added benefit that it will raise a run-time error if the value is not of the expected type, potentially catching certain bugs earlier.
In the case that the type of `a[1]` is not known precisely, `x` can be declared via `x = convert(Int32, a[1])::Int32`. The use of the [`convert`](../../base/base/index#Base.convert) function allows `a[1]` to be any object convertible to an `Int32` (such as `UInt8`), thus increasing the genericity of the code by loosening the type requirement. Notice that `convert` itself needs a type annotation in this context in order to achieve type stability. This is because the compiler cannot deduce the type of the return value of a function, even `convert`, unless the types of all the function's arguments are known.
Type annotation will not enhance (and can actually hinder) performance if the type is abstract, or constructed at run-time. This is because the compiler cannot use the annotation to specialize the subsequent code, and the type-check itself takes time. For example, in the code:
```
function nr(a, prec)
ctype = prec == 32 ? Float32 : Float64
b = Complex{ctype}(a)
c = (b + 1.0f0)::Complex{ctype}
abs(c)
end
```
the annotation of `c` harms performance. To write performant code involving types constructed at run-time, use the [function-barrier technique](#kernel-functions) discussed below, and ensure that the constructed type appears among the argument types of the kernel function so that the kernel operations are properly specialized by the compiler. For example, in the above snippet, as soon as `b` is constructed, it can be passed to another function `k`, the kernel. If, for example, function `k` declares `b` as an argument of type `Complex{T}`, where `T` is a type parameter, then a type annotation appearing in an assignment statement within `k` of the form:
```
c = (b + 1.0f0)::Complex{T}
```
does not hinder performance (but does not help either) since the compiler can determine the type of `c` at the time `k` is compiled.
###
[Be aware of when Julia avoids specializing](#Be-aware-of-when-Julia-avoids-specializing)
As a heuristic, Julia avoids automatically specializing on argument type parameters in three specific cases: `Type`, `Function`, and `Vararg`. Julia will always specialize when the argument is used within the method, but not if the argument is just passed through to another function. This usually has no performance impact at runtime and [improves compiler performance](https://docs.julialang.org/en/v1.8/devdocs/functions/#compiler-efficiency-issues). If you find it does have a performance impact at runtime in your case, you can trigger specialization by adding a type parameter to the method declaration. Here are some examples:
This will not specialize:
```
function f_type(t) # or t::Type
x = ones(t, 10)
return sum(map(sin, x))
end
```
but this will:
```
function g_type(t::Type{T}) where T
x = ones(T, 10)
return sum(map(sin, x))
end
```
These will not specialize:
```
f_func(f, num) = ntuple(f, div(num, 2))
g_func(g::Function, num) = ntuple(g, div(num, 2))
```
but this will:
```
h_func(h::H, num) where {H} = ntuple(h, div(num, 2))
```
This will not specialize:
```
f_vararg(x::Int...) = tuple(x...)
```
but this will:
```
g_vararg(x::Vararg{Int, N}) where {N} = tuple(x...)
```
One only needs to introduce a single type parameter to force specialization, even if the other types are unconstrained. For example, this will also specialize, and is useful when the arguments are not all of the same type:
```
h_vararg(x::Vararg{Any, N}) where {N} = tuple(x...)
```
Note that [`@code_typed`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_typed) and friends will always show you specialized code, even if Julia would not normally specialize that method call. You need to check the [method internals](https://docs.julialang.org/en/v1.8/devdocs/ast/#ast-lowered-method) if you want to see whether specializations are generated when argument types are changed, i.e., if `(@which f(...)).specializations` contains specializations for the argument in question.
[Break functions into multiple definitions](#Break-functions-into-multiple-definitions)
----------------------------------------------------------------------------------------
Writing a function as many small definitions allows the compiler to directly call the most applicable code, or even inline it.
Here is an example of a "compound function" that should really be written as multiple definitions:
```
using LinearAlgebra
function mynorm(A)
if isa(A, Vector)
return sqrt(real(dot(A,A)))
elseif isa(A, Matrix)
return maximum(svdvals(A))
else
error("mynorm: invalid argument")
end
end
```
This can be written more concisely and efficiently as:
```
norm(x::Vector) = sqrt(real(dot(x, x)))
norm(A::Matrix) = maximum(svdvals(A))
```
It should however be noted that the compiler is quite efficient at optimizing away the dead branches in code written as the `mynorm` example.
[Write "type-stable" functions](#Write-%22type-stable%22-functions)
--------------------------------------------------------------------
When possible, it helps to ensure that a function always returns a value of the same type. Consider the following definition:
```
pos(x) = x < 0 ? 0 : x
```
Although this seems innocent enough, the problem is that `0` is an integer (of type `Int`) and `x` might be of any type. Thus, depending on the value of `x`, this function might return a value of either of two types. This behavior is allowed, and may be desirable in some cases. But it can easily be fixed as follows:
```
pos(x) = x < 0 ? zero(x) : x
```
There is also a [`oneunit`](../../base/numbers/index#Base.oneunit) function, and a more general [`oftype(x, y)`](../../base/base/index#Base.oftype) function, which returns `y` converted to the type of `x`.
[Avoid changing the type of a variable](#Avoid-changing-the-type-of-a-variable)
--------------------------------------------------------------------------------
An analogous "type-stability" problem exists for variables used repeatedly within a function:
```
function foo()
x = 1
for i = 1:10
x /= rand()
end
return x
end
```
Local variable `x` starts as an integer, and after one loop iteration becomes a floating-point number (the result of [`/`](../../base/math/index#Base.:/) operator). This makes it more difficult for the compiler to optimize the body of the loop. There are several possible fixes:
* Initialize `x` with `x = 1.0`
* Declare the type of `x` explicitly as `x::Float64 = 1`
* Use an explicit conversion by `x = oneunit(Float64)`
* Initialize with the first loop iteration, to `x = 1 / rand()`, then loop `for i = 2:10`
[Separate kernel functions (aka, function barriers)](#kernel-functions)
------------------------------------------------------------------------
Many functions follow a pattern of performing some set-up work, and then running many iterations to perform a core computation. Where possible, it is a good idea to put these core computations in separate functions. For example, the following contrived function returns an array of a randomly-chosen type:
```
julia> function strange_twos(n)
a = Vector{rand(Bool) ? Int64 : Float64}(undef, n)
for i = 1:n
a[i] = 2
end
return a
end;
julia> strange_twos(3)
3-element Vector{Int64}:
2
2
2
```
This should be written as:
```
julia> function fill_twos!(a)
for i = eachindex(a)
a[i] = 2
end
end;
julia> function strange_twos(n)
a = Vector{rand(Bool) ? Int64 : Float64}(undef, n)
fill_twos!(a)
return a
end;
julia> strange_twos(3)
3-element Vector{Int64}:
2
2
2
```
Julia's compiler specializes code for argument types at function boundaries, so in the original implementation it does not know the type of `a` during the loop (since it is chosen randomly). Therefore the second version is generally faster since the inner loop can be recompiled as part of `fill_twos!` for different types of `a`.
The second form is also often better style and can lead to more code reuse.
This pattern is used in several places in Julia Base. For example, see `vcat` and `hcat` in [`abstractarray.jl`](https://github.com/JuliaLang/julia/blob/40fe264f4ffaa29b749bcf42239a89abdcbba846/base/abstractarray.jl#L1205-L1206), or the [`fill!`](../../base/arrays/index#Base.fill!) function, which we could have used instead of writing our own `fill_twos!`.
Functions like `strange_twos` occur when dealing with data of uncertain type, for example data loaded from an input file that might contain either integers, floats, strings, or something else.
[Types with values-as-parameters](#man-performance-value-type)
---------------------------------------------------------------
Let's say you want to create an `N`-dimensional array that has size 3 along each axis. Such arrays can be created like this:
```
julia> A = fill(5.0, (3, 3))
3×3 Matrix{Float64}:
5.0 5.0 5.0
5.0 5.0 5.0
5.0 5.0 5.0
```
This approach works very well: the compiler can figure out that `A` is an `Array{Float64,2}` because it knows the type of the fill value (`5.0::Float64`) and the dimensionality (`(3, 3)::NTuple{2,Int}`). This implies that the compiler can generate very efficient code for any future usage of `A` in the same function.
But now let's say you want to write a function that creates a 3×3×... array in arbitrary dimensions; you might be tempted to write a function
```
julia> function array3(fillval, N)
fill(fillval, ntuple(d->3, N))
end
array3 (generic function with 1 method)
julia> array3(5.0, 2)
3×3 Matrix{Float64}:
5.0 5.0 5.0
5.0 5.0 5.0
5.0 5.0 5.0
```
This works, but (as you can verify for yourself using `@code_warntype array3(5.0, 2)`) the problem is that the output type cannot be inferred: the argument `N` is a *value* of type `Int`, and type-inference does not (and cannot) predict its value in advance. This means that code using the output of this function has to be conservative, checking the type on each access of `A`; such code will be very slow.
Now, one very good way to solve such problems is by using the [function-barrier technique](#kernel-functions). However, in some cases you might want to eliminate the type-instability altogether. In such cases, one approach is to pass the dimensionality as a parameter, for example through `Val{T}()` (see ["Value types"](#)):
```
julia> function array3(fillval, ::Val{N}) where N
fill(fillval, ntuple(d->3, Val(N)))
end
array3 (generic function with 1 method)
julia> array3(5.0, Val(2))
3×3 Matrix{Float64}:
5.0 5.0 5.0
5.0 5.0 5.0
5.0 5.0 5.0
```
Julia has a specialized version of `ntuple` that accepts a `Val{::Int}` instance as the second parameter; by passing `N` as a type-parameter, you make its "value" known to the compiler. Consequently, this version of `array3` allows the compiler to predict the return type.
However, making use of such techniques can be surprisingly subtle. For example, it would be of no help if you called `array3` from a function like this:
```
function call_array3(fillval, n)
A = array3(fillval, Val(n))
end
```
Here, you've created the same problem all over again: the compiler can't guess what `n` is, so it doesn't know the *type* of `Val(n)`. Attempting to use `Val`, but doing so incorrectly, can easily make performance *worse* in many situations. (Only in situations where you're effectively combining `Val` with the function-barrier trick, to make the kernel function more efficient, should code like the above be used.)
An example of correct usage of `Val` would be:
```
function filter3(A::AbstractArray{T,N}) where {T,N}
kernel = array3(1, Val(N))
filter(A, kernel)
end
```
In this example, `N` is passed as a parameter, so its "value" is known to the compiler. Essentially, `Val(T)` works only when `T` is either hard-coded/literal (`Val(3)`) or already specified in the type-domain.
[The dangers of abusing multiple dispatch (aka, more on types with values-as-parameters)](#The-dangers-of-abusing-multiple-dispatch-(aka,-more-on-types-with-values-as-parameters))
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Once one learns to appreciate multiple dispatch, there's an understandable tendency to go overboard and try to use it for everything. For example, you might imagine using it to store information, e.g.
```
struct Car{Make, Model}
year::Int
...more fields...
end
```
and then dispatch on objects like `Car{:Honda,:Accord}(year, args...)`.
This might be worthwhile when either of the following are true:
* You require CPU-intensive processing on each `Car`, and it becomes vastly more efficient if you know the `Make` and `Model` at compile time and the total number of different `Make` or `Model` that will be used is not too large.
* You have homogenous lists of the same type of `Car` to process, so that you can store them all in an `Array{Car{:Honda,:Accord},N}`.
When the latter holds, a function processing such a homogenous array can be productively specialized: Julia knows the type of each element in advance (all objects in the container have the same concrete type), so Julia can "look up" the correct method calls when the function is being compiled (obviating the need to check at run-time) and thereby emit efficient code for processing the whole list.
When these do not hold, then it's likely that you'll get no benefit; worse, the resulting "combinatorial explosion of types" will be counterproductive. If `items[i+1]` has a different type than `item[i]`, Julia has to look up the type at run-time, search for the appropriate method in method tables, decide (via type intersection) which one matches, determine whether it has been JIT-compiled yet (and do so if not), and then make the call. In essence, you're asking the full type- system and JIT-compilation machinery to basically execute the equivalent of a switch statement or dictionary lookup in your own code.
Some run-time benchmarks comparing (1) type dispatch, (2) dictionary lookup, and (3) a "switch" statement can be found [on the mailing list](https://groups.google.com/forum/#!msg/julia-users/jUMu9A3QKQQ/qjgVWr7vAwAJ).
Perhaps even worse than the run-time impact is the compile-time impact: Julia will compile specialized functions for each different `Car{Make, Model}`; if you have hundreds or thousands of such types, then every function that accepts such an object as a parameter (from a custom `get_year` function you might write yourself, to the generic `push!` function in Julia Base) will have hundreds or thousands of variants compiled for it. Each of these increases the size of the cache of compiled code, the length of internal lists of methods, etc. Excess enthusiasm for values-as-parameters can easily waste enormous resources.
[Access arrays in memory order, along columns](#man-performance-column-major)
------------------------------------------------------------------------------
Multidimensional arrays in Julia are stored in column-major order. This means that arrays are stacked one column at a time. This can be verified using the `vec` function or the syntax `[:]` as shown below (notice that the array is ordered `[1 3 2 4]`, not `[1 2 3 4]`):
```
julia> x = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> x[:]
4-element Vector{Int64}:
1
3
2
4
```
This convention for ordering arrays is common in many languages like Fortran, Matlab, and R (to name a few). The alternative to column-major ordering is row-major ordering, which is the convention adopted by C and Python (`numpy`) among other languages. Remembering the ordering of arrays can have significant performance effects when looping over arrays. A rule of thumb to keep in mind is that with column-major arrays, the first index changes most rapidly. Essentially this means that looping will be faster if the inner-most loop index is the first to appear in a slice expression. Keep in mind that indexing an array with `:` is an implicit loop that iteratively accesses all elements within a particular dimension; it can be faster to extract columns than rows, for example.
Consider the following contrived example. Imagine we wanted to write a function that accepts a [`Vector`](../../base/arrays/index#Base.Vector) and returns a square [`Matrix`](../../base/arrays/index#Base.Matrix) with either the rows or the columns filled with copies of the input vector. Assume that it is not important whether rows or columns are filled with these copies (perhaps the rest of the code can be easily adapted accordingly). We could conceivably do this in at least four ways (in addition to the recommended call to the built-in [`repeat`](../../base/arrays/index#Base.repeat)):
```
function copy_cols(x::Vector{T}) where T
inds = axes(x, 1)
out = similar(Array{T}, inds, inds)
for i = inds
out[:, i] = x
end
return out
end
function copy_rows(x::Vector{T}) where T
inds = axes(x, 1)
out = similar(Array{T}, inds, inds)
for i = inds
out[i, :] = x
end
return out
end
function copy_col_row(x::Vector{T}) where T
inds = axes(x, 1)
out = similar(Array{T}, inds, inds)
for col = inds, row = inds
out[row, col] = x[row]
end
return out
end
function copy_row_col(x::Vector{T}) where T
inds = axes(x, 1)
out = similar(Array{T}, inds, inds)
for row = inds, col = inds
out[row, col] = x[col]
end
return out
end
```
Now we will time each of these functions using the same random `10000` by `1` input vector:
```
julia> x = randn(10000);
julia> fmt(f) = println(rpad(string(f)*": ", 14, ' '), @elapsed f(x))
julia> map(fmt, [copy_cols, copy_rows, copy_col_row, copy_row_col]);
copy_cols: 0.331706323
copy_rows: 1.799009911
copy_col_row: 0.415630047
copy_row_col: 1.721531501
```
Notice that `copy_cols` is much faster than `copy_rows`. This is expected because `copy_cols` respects the column-based memory layout of the `Matrix` and fills it one column at a time. Additionally, `copy_col_row` is much faster than `copy_row_col` because it follows our rule of thumb that the first element to appear in a slice expression should be coupled with the inner-most loop.
[Pre-allocating outputs](#Pre-allocating-outputs)
--------------------------------------------------
If your function returns an `Array` or some other complex type, it may have to allocate memory. Unfortunately, oftentimes allocation and its converse, garbage collection, are substantial bottlenecks.
Sometimes you can circumvent the need to allocate memory on each function call by preallocating the output. As a trivial example, compare
```
julia> function xinc(x)
return [x, x+1, x+2]
end;
julia> function loopinc()
y = 0
for i = 1:10^7
ret = xinc(i)
y += ret[2]
end
return y
end;
```
with
```
julia> function xinc!(ret::AbstractVector{T}, x::T) where T
ret[1] = x
ret[2] = x+1
ret[3] = x+2
nothing
end;
julia> function loopinc_prealloc()
ret = Vector{Int}(undef, 3)
y = 0
for i = 1:10^7
xinc!(ret, i)
y += ret[2]
end
return y
end;
```
Timing results:
```
julia> @time loopinc()
0.529894 seconds (40.00 M allocations: 1.490 GiB, 12.14% gc time)
50000015000000
julia> @time loopinc_prealloc()
0.030850 seconds (6 allocations: 288 bytes)
50000015000000
```
Preallocation has other advantages, for example by allowing the caller to control the "output" type from an algorithm. In the example above, we could have passed a `SubArray` rather than an [`Array`](../../base/arrays/index#Core.Array), had we so desired.
Taken to its extreme, pre-allocation can make your code uglier, so performance measurements and some judgment may be required. However, for "vectorized" (element-wise) functions, the convenient syntax `x .= f.(y)` can be used for in-place operations with fused loops and no temporary arrays (see the [dot syntax for vectorizing functions](../functions/index#man-vectorized)).
[More dots: Fuse vectorized operations](#More-dots:-Fuse-vectorized-operations)
--------------------------------------------------------------------------------
Julia has a special [dot syntax](../functions/index#man-vectorized) that converts any scalar function into a "vectorized" function call, and any operator into a "vectorized" operator, with the special property that nested "dot calls" are *fusing*: they are combined at the syntax level into a single loop, without allocating temporary arrays. If you use `.=` and similar assignment operators, the result can also be stored in-place in a pre-allocated array (see above).
In a linear-algebra context, this means that even though operations like `vector + vector` and `vector * scalar` are defined, it can be advantageous to instead use `vector .+ vector` and `vector .* scalar` because the resulting loops can be fused with surrounding computations. For example, consider the two functions:
```
julia> f(x) = 3x.^2 + 4x + 7x.^3;
julia> fdot(x) = @. 3x^2 + 4x + 7x^3; # equivalent to 3 .* x.^2 .+ 4 .* x .+ 7 .* x.^3
```
Both `f` and `fdot` compute the same thing. However, `fdot` (defined with the help of the [`@.`](../../base/arrays/index#Base.Broadcast.@__dot__) macro) is significantly faster when applied to an array:
```
julia> x = rand(10^6);
julia> @time f(x);
0.019049 seconds (16 allocations: 45.777 MiB, 18.59% gc time)
julia> @time fdot(x);
0.002790 seconds (6 allocations: 7.630 MiB)
julia> @time f.(x);
0.002626 seconds (8 allocations: 7.630 MiB)
```
That is, `fdot(x)` is ten times faster and allocates 1/6 the memory of `f(x)`, because each `*` and `+` operation in `f(x)` allocates a new temporary array and executes in a separate loop. (Of course, if you just do `f.(x)` then it is as fast as `fdot(x)` in this example, but in many contexts it is more convenient to just sprinkle some dots in your expressions rather than defining a separate function for each vectorized operation.)
[Consider using views for slices](#man-performance-views)
----------------------------------------------------------
In Julia, an array "slice" expression like `array[1:5, :]` creates a copy of that data (except on the left-hand side of an assignment, where `array[1:5, :] = ...` assigns in-place to that portion of `array`). If you are doing many operations on the slice, this can be good for performance because it is more efficient to work with a smaller contiguous copy than it would be to index into the original array. On the other hand, if you are just doing a few simple operations on the slice, the cost of the allocation and copy operations can be substantial.
An alternative is to create a "view" of the array, which is an array object (a `SubArray`) that actually references the data of the original array in-place, without making a copy. (If you write to a view, it modifies the original array's data as well.) This can be done for individual slices by calling [`view`](../../base/arrays/index#Base.view), or more simply for a whole expression or block of code by putting [`@views`](../../base/arrays/index#Base.@views) in front of that expression. For example:
```
julia> fcopy(x) = sum(x[2:end-1]);
julia> @views fview(x) = sum(x[2:end-1]);
julia> x = rand(10^6);
julia> @time fcopy(x);
0.003051 seconds (3 allocations: 7.629 MB)
julia> @time fview(x);
0.001020 seconds (1 allocation: 16 bytes)
```
Notice both the 3× speedup and the decreased memory allocation of the `fview` version of the function.
[Copying data is not always bad](#Copying-data-is-not-always-bad)
------------------------------------------------------------------
Arrays are stored contiguously in memory, lending themselves to CPU vectorization and fewer memory accesses due to caching. These are the same reasons that it is recommended to access arrays in column-major order (see above). Irregular access patterns and non-contiguous views can drastically slow down computations on arrays because of non-sequential memory access.
Copying irregularly-accessed data into a contiguous array before operating on it can result in a large speedup, such as in the example below. Here, a matrix and a vector are being accessed at 800,000 of their randomly-shuffled indices before being multiplied. Copying the views into plain arrays speeds up the multiplication even with the cost of the copying operation.
```
julia> using Random
julia> x = randn(1_000_000);
julia> inds = shuffle(1:1_000_000)[1:800000];
julia> A = randn(50, 1_000_000);
julia> xtmp = zeros(800_000);
julia> Atmp = zeros(50, 800_000);
julia> @time sum(view(A, :, inds) * view(x, inds))
0.412156 seconds (14 allocations: 960 bytes)
-4256.759568345458
julia> @time begin
copyto!(xtmp, view(x, inds))
copyto!(Atmp, view(A, :, inds))
sum(Atmp * xtmp)
end
0.285923 seconds (14 allocations: 960 bytes)
-4256.759568345134
```
Provided there is enough memory for the copies, the cost of copying the view to an array is far outweighed by the speed boost from doing the matrix multiplication on a contiguous array.
[Consider StaticArrays.jl for small fixed-size vector/matrix operations](#Consider-StaticArrays.jl-for-small-fixed-size-vector/matrix-operations)
--------------------------------------------------------------------------------------------------------------------------------------------------
If your application involves many small (`< 100` element) arrays of fixed sizes (i.e. the size is known prior to execution), then you might want to consider using the [StaticArrays.jl package](https://github.com/JuliaArrays/StaticArrays.jl). This package allows you to represent such arrays in a way that avoids unnecessary heap allocations and allows the compiler to specialize code for the *size* of the array, e.g. by completely unrolling vector operations (eliminating the loops) and storing elements in CPU registers.
For example, if you are doing computations with 2d geometries, you might have many computations with 2-component vectors. By using the `SVector` type from StaticArrays.jl, you can use convenient vector notation and operations like `norm(3v - w)` on vectors `v` and `w`, while allowing the compiler to unroll the code to a minimal computation equivalent to `@inbounds hypot(3v[1]-w[1], 3v[2]-w[2])`.
[Avoid string interpolation for I/O](#Avoid-string-interpolation-for-I/O)
--------------------------------------------------------------------------
When writing data to a file (or other I/O device), forming extra intermediate strings is a source of overhead. Instead of:
```
println(file, "$a $b")
```
use:
```
println(file, a, " ", b)
```
The first version of the code forms a string, then writes it to the file, while the second version writes values directly to the file. Also notice that in some cases string interpolation can be harder to read. Consider:
```
println(file, "$(f(a))$(f(b))")
```
versus:
```
println(file, f(a), f(b))
```
[Optimize network I/O during parallel execution](#Optimize-network-I/O-during-parallel-execution)
--------------------------------------------------------------------------------------------------
When executing a remote function in parallel:
```
using Distributed
responses = Vector{Any}(undef, nworkers())
@sync begin
for (idx, pid) in enumerate(workers())
@async responses[idx] = remotecall_fetch(foo, pid, args...)
end
end
```
is faster than:
```
using Distributed
refs = Vector{Any}(undef, nworkers())
for (idx, pid) in enumerate(workers())
refs[idx] = @spawnat pid foo(args...)
end
responses = [fetch(r) for r in refs]
```
The former results in a single network round-trip to every worker, while the latter results in two network calls - first by the [`@spawnat`](../../stdlib/distributed/index#Distributed.@spawnat) and the second due to the [`fetch`](#) (or even a [`wait`](../../base/parallel/index#Base.wait)). The [`fetch`](#)/[`wait`](../../base/parallel/index#Base.wait) is also being executed serially resulting in an overall poorer performance.
[Fix deprecation warnings](#Fix-deprecation-warnings)
------------------------------------------------------
A deprecated function internally performs a lookup in order to print a relevant warning only once. This extra lookup can cause a significant slowdown, so all uses of deprecated functions should be modified as suggested by the warnings.
[Tweaks](#Tweaks)
------------------
These are some minor points that might help in tight inner loops.
* Avoid unnecessary arrays. For example, instead of [`sum([x,y,z])`](../../base/collections/index#Base.sum) use `x+y+z`.
* Use [`abs2(z)`](../../base/math/index#Base.abs2) instead of [`abs(z)^2`](#) for complex `z`. In general, try to rewrite code to use [`abs2`](../../base/math/index#Base.abs2) instead of [`abs`](../../base/math/index#Base.abs) for complex arguments.
* Use [`div(x,y)`](../../base/math/index#Base.div) for truncating division of integers instead of [`trunc(x/y)`](../../base/math/index#Base.trunc), [`fld(x,y)`](../../base/math/index#Base.fld) instead of [`floor(x/y)`](../../base/math/index#Base.floor), and [`cld(x,y)`](../../base/math/index#Base.cld) instead of [`ceil(x/y)`](../../base/math/index#Base.ceil).
[Performance Annotations](#man-performance-annotations)
--------------------------------------------------------
Sometimes you can enable better optimization by promising certain program properties.
* Use [`@inbounds`](../../base/base/index#Base.@inbounds) to eliminate array bounds checking within expressions. Be certain before doing this. If the subscripts are ever out of bounds, you may suffer crashes or silent corruption.
* Use [`@fastmath`](../../base/math/index#Base.FastMath.@fastmath) to allow floating point optimizations that are correct for real numbers, but lead to differences for IEEE numbers. Be careful when doing this, as this may change numerical results. This corresponds to the `-ffast-math` option of clang.
* Write [`@simd`](../../base/base/index#Base.SimdLoop.@simd) in front of `for` loops to promise that the iterations are independent and may be reordered. Note that in many cases, Julia can automatically vectorize code without the `@simd` macro; it is only beneficial in cases where such a transformation would otherwise be illegal, including cases like allowing floating-point re-associativity and ignoring dependent memory accesses (`@simd ivdep`). Again, be very careful when asserting `@simd` as erroneously annotating a loop with dependent iterations may result in unexpected results. In particular, note that `setindex!` on some `AbstractArray` subtypes is inherently dependent upon iteration order. **This feature is experimental** and could change or disappear in future versions of Julia.
The common idiom of using 1:n to index into an AbstractArray is not safe if the Array uses unconventional indexing, and may cause a segmentation fault if bounds checking is turned off. Use `LinearIndices(x)` or `eachindex(x)` instead (see also [Arrays with custom indices](https://docs.julialang.org/en/v1.8/devdocs/offset-arrays/#man-custom-indices)).
While `@simd` needs to be placed directly in front of an innermost `for` loop, both `@inbounds` and `@fastmath` can be applied to either single expressions or all the expressions that appear within nested blocks of code, e.g., using `@inbounds begin` or `@inbounds for ...`.
Here is an example with both `@inbounds` and `@simd` markup (we here use `@noinline` to prevent the optimizer from trying to be too clever and defeat our benchmark):
```
@noinline function inner(x, y)
s = zero(eltype(x))
for i=eachindex(x)
@inbounds s += x[i]*y[i]
end
return s
end
@noinline function innersimd(x, y)
s = zero(eltype(x))
@simd for i = eachindex(x)
@inbounds s += x[i] * y[i]
end
return s
end
function timeit(n, reps)
x = rand(Float32, n)
y = rand(Float32, n)
s = zero(Float64)
time = @elapsed for j in 1:reps
s += inner(x, y)
end
println("GFlop/sec = ", 2n*reps / time*1E-9)
time = @elapsed for j in 1:reps
s += innersimd(x, y)
end
println("GFlop/sec (SIMD) = ", 2n*reps / time*1E-9)
end
timeit(1000, 1000)
```
On a computer with a 2.4GHz Intel Core i5 processor, this produces:
```
GFlop/sec = 1.9467069505224963
GFlop/sec (SIMD) = 17.578554163920018
```
(`GFlop/sec` measures the performance, and larger numbers are better.)
Here is an example with all three kinds of markup. This program first calculates the finite difference of a one-dimensional array, and then evaluates the L2-norm of the result:
```
function init!(u::Vector)
n = length(u)
dx = 1.0 / (n-1)
@fastmath @inbounds @simd for i in 1:n #by asserting that `u` is a `Vector` we can assume it has 1-based indexing
u[i] = sin(2pi*dx*i)
end
end
function deriv!(u::Vector, du)
n = length(u)
dx = 1.0 / (n-1)
@fastmath @inbounds du[1] = (u[2] - u[1]) / dx
@fastmath @inbounds @simd for i in 2:n-1
du[i] = (u[i+1] - u[i-1]) / (2*dx)
end
@fastmath @inbounds du[n] = (u[n] - u[n-1]) / dx
end
function mynorm(u::Vector)
n = length(u)
T = eltype(u)
s = zero(T)
@fastmath @inbounds @simd for i in 1:n
s += u[i]^2
end
@fastmath @inbounds return sqrt(s)
end
function main()
n = 2000
u = Vector{Float64}(undef, n)
init!(u)
du = similar(u)
deriv!(u, du)
nu = mynorm(du)
@time for i in 1:10^6
deriv!(u, du)
nu = mynorm(du)
end
println(nu)
end
main()
```
On a computer with a 2.7 GHz Intel Core i7 processor, this produces:
```
$ julia wave.jl;
1.207814709 seconds
4.443986180758249
$ julia --math-mode=ieee wave.jl;
4.487083643 seconds
4.443986180758249
```
Here, the option `--math-mode=ieee` disables the `@fastmath` macro, so that we can compare results.
In this case, the speedup due to `@fastmath` is a factor of about 3.7. This is unusually large – in general, the speedup will be smaller. (In this particular example, the working set of the benchmark is small enough to fit into the L1 cache of the processor, so that memory access latency does not play a role, and computing time is dominated by CPU usage. In many real world programs this is not the case.) Also, in this case this optimization does not change the result – in general, the result will be slightly different. In some cases, especially for numerically unstable algorithms, the result can be very different.
The annotation `@fastmath` re-arranges floating point expressions, e.g. changing the order of evaluation, or assuming that certain special cases (inf, nan) cannot occur. In this case (and on this particular computer), the main difference is that the expression `1 / (2*dx)` in the function `deriv` is hoisted out of the loop (i.e. calculated outside the loop), as if one had written `idx = 1 / (2*dx)`. In the loop, the expression `... / (2*dx)` then becomes `... * idx`, which is much faster to evaluate. Of course, both the actual optimization that is applied by the compiler as well as the resulting speedup depend very much on the hardware. You can examine the change in generated code by using Julia's [`code_native`](../../stdlib/interactiveutils/index#InteractiveUtils.code_native) function.
Note that `@fastmath` also assumes that `NaN`s will not occur during the computation, which can lead to surprising behavior:
```
julia> f(x) = isnan(x);
julia> f(NaN)
true
julia> f_fast(x) = @fastmath isnan(x);
julia> f_fast(NaN)
false
```
[Treat Subnormal Numbers as Zeros](#Treat-Subnormal-Numbers-as-Zeros)
----------------------------------------------------------------------
Subnormal numbers, formerly called [denormal numbers](https://en.wikipedia.org/wiki/Denormal_number), are useful in many contexts, but incur a performance penalty on some hardware. A call [`set_zero_subnormals(true)`](../../base/numbers/index#Base.Rounding.set_zero_subnormals) grants permission for floating-point operations to treat subnormal inputs or outputs as zeros, which may improve performance on some hardware. A call [`set_zero_subnormals(false)`](../../base/numbers/index#Base.Rounding.set_zero_subnormals) enforces strict IEEE behavior for subnormal numbers.
Below is an example where subnormals noticeably impact performance on some hardware:
```
function timestep(b::Vector{T}, a::Vector{T}, Δt::T) where T
@assert length(a)==length(b)
n = length(b)
b[1] = 1 # Boundary condition
for i=2:n-1
b[i] = a[i] + (a[i-1] - T(2)*a[i] + a[i+1]) * Δt
end
b[n] = 0 # Boundary condition
end
function heatflow(a::Vector{T}, nstep::Integer) where T
b = similar(a)
for t=1:div(nstep,2) # Assume nstep is even
timestep(b,a,T(0.1))
timestep(a,b,T(0.1))
end
end
heatflow(zeros(Float32,10),2) # Force compilation
for trial=1:6
a = zeros(Float32,1000)
set_zero_subnormals(iseven(trial)) # Odd trials use strict IEEE arithmetic
@time heatflow(a,1000)
end
```
This gives an output similar to
```
0.002202 seconds (1 allocation: 4.063 KiB)
0.001502 seconds (1 allocation: 4.063 KiB)
0.002139 seconds (1 allocation: 4.063 KiB)
0.001454 seconds (1 allocation: 4.063 KiB)
0.002115 seconds (1 allocation: 4.063 KiB)
0.001455 seconds (1 allocation: 4.063 KiB)
```
Note how each even iteration is significantly faster.
This example generates many subnormal numbers because the values in `a` become an exponentially decreasing curve, which slowly flattens out over time.
Treating subnormals as zeros should be used with caution, because doing so breaks some identities, such as `x-y == 0` implies `x == y`:
```
julia> x = 3f-38; y = 2f-38;
julia> set_zero_subnormals(true); (x - y, x == y)
(0.0f0, false)
julia> set_zero_subnormals(false); (x - y, x == y)
(1.0000001f-38, false)
```
In some applications, an alternative to zeroing subnormal numbers is to inject a tiny bit of noise. For example, instead of initializing `a` with zeros, initialize it with:
```
a = rand(Float32,1000) * 1.f-9
```
[`@code_warntype`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_warntype)
----------------------------------------------------------------------------------------
The macro [`@code_warntype`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_warntype) (or its function variant [`code_warntype`](../../stdlib/interactiveutils/index#InteractiveUtils.code_warntype)) can sometimes be helpful in diagnosing type-related problems. Here's an example:
```
julia> @noinline pos(x) = x < 0 ? 0 : x;
julia> function f(x)
y = pos(x)
return sin(y*x + 1)
end;
julia> @code_warntype f(3.2)
Variables
#self#::Core.Const(f)
x::Float64
y::UNION{FLOAT64, INT64}
Body::Float64
1 ─ (y = Main.pos(x))
│ %2 = (y * x)::Float64
│ %3 = (%2 + 1)::Float64
│ %4 = Main.sin(%3)::Float64
└── return %4
```
Interpreting the output of [`@code_warntype`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_warntype), like that of its cousins [`@code_lowered`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_lowered), [`@code_typed`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_typed), [`@code_llvm`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_llvm), and [`@code_native`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_native), takes a little practice. Your code is being presented in form that has been heavily digested on its way to generating compiled machine code. Most of the expressions are annotated by a type, indicated by the `::T` (where `T` might be [`Float64`](../../base/numbers/index#Core.Float64), for example). The most important characteristic of [`@code_warntype`](../../stdlib/interactiveutils/index#InteractiveUtils.@code_warntype) is that non-concrete types are displayed in red; since this document is written in Markdown, which has no color, in this document, red text is denoted by uppercase.
At the top, the inferred return type of the function is shown as `Body::Float64`. The next lines represent the body of `f` in Julia's SSA IR form. The numbered boxes are labels and represent targets for jumps (via `goto`) in your code. Looking at the body, you can see that the first thing that happens is that `pos` is called and the return value has been inferred as the `Union` type `UNION{FLOAT64, INT64}` shown in uppercase since it is a non-concrete type. This means that we cannot know the exact return type of `pos` based on the input types. However, the result of `y*x`is a `Float64` no matter if `y` is a `Float64` or `Int64` The net result is that `f(x::Float64)` will not be type-unstable in its output, even if some of the intermediate computations are type-unstable.
How you use this information is up to you. Obviously, it would be far and away best to fix `pos` to be type-stable: if you did so, all of the variables in `f` would be concrete, and its performance would be optimal. However, there are circumstances where this kind of *ephemeral* type instability might not matter too much: for example, if `pos` is never used in isolation, the fact that `f`'s output is type-stable (for [`Float64`](../../base/numbers/index#Core.Float64) inputs) will shield later code from the propagating effects of type instability. This is particularly relevant in cases where fixing the type instability is difficult or impossible. In such cases, the tips above (e.g., adding type annotations and/or breaking up functions) are your best tools to contain the "damage" from type instability. Also, note that even Julia Base has functions that are type unstable. For example, the function [`findfirst`](#) returns the index into an array where a key is found, or `nothing` if it is not found, a clear type instability. In order to make it easier to find the type instabilities that are likely to be important, `Union`s containing either `missing` or `nothing` are color highlighted in yellow, instead of red.
The following examples may help you interpret expressions marked as containing non-leaf types:
* Function body starting with `Body::UNION{T1,T2})`
+ Interpretation: function with unstable return type
+ Suggestion: make the return value type-stable, even if you have to annotate it
* `invoke Main.g(%%x::Int64)::UNION{FLOAT64, INT64}`
+ Interpretation: call to a type-unstable function `g`.
+ Suggestion: fix the function, or if necessary annotate the return value
* `invoke Base.getindex(%%x::Array{Any,1}, 1::Int64)::ANY`
+ Interpretation: accessing elements of poorly-typed arrays
+ Suggestion: use arrays with better-defined types, or if necessary annotate the type of individual element accesses
* `Base.getfield(%%x, :(:data))::ARRAY{FLOAT64,N} WHERE N`
+ Interpretation: getting a field that is of non-leaf type. In this case, the type of `x`, say `ArrayContainer`, had a field `data::Array{T}`. But `Array` needs the dimension `N`, too, to be a concrete type.
+ Suggestion: use concrete types like `Array{T,3}` or `Array{T,N}`, where `N` is now a parameter of `ArrayContainer`
[Performance of captured variable](#man-performance-captured)
--------------------------------------------------------------
Consider the following example that defines an inner function:
```
function abmult(r::Int)
if r < 0
r = -r
end
f = x -> x * r
return f
end
```
Function `abmult` returns a function `f` that multiplies its argument by the absolute value of `r`. The inner function assigned to `f` is called a "closure". Inner functions are also used by the language for `do`-blocks and for generator expressions.
This style of code presents performance challenges for the language. The parser, when translating it into lower-level instructions, substantially reorganizes the above code by extracting the inner function to a separate code block. "Captured" variables such as `r` that are shared by inner functions and their enclosing scope are also extracted into a heap-allocated "box" accessible to both inner and outer functions because the language specifies that `r` in the inner scope must be identical to `r` in the outer scope even after the outer scope (or another inner function) modifies `r`.
The discussion in the preceding paragraph referred to the "parser", that is, the phase of compilation that takes place when the module containing `abmult` is first loaded, as opposed to the later phase when it is first invoked. The parser does not "know" that `Int` is a fixed type, or that the statement `r = -r` transforms an `Int` to another `Int`. The magic of type inference takes place in the later phase of compilation.
Thus, the parser does not know that `r` has a fixed type (`Int`). nor that `r` does not change value once the inner function is created (so that the box is unneeded). Therefore, the parser emits code for box that holds an object with an abstract type such as `Any`, which requires run-time type dispatch for each occurrence of `r`. This can be verified by applying `@code_warntype` to the above function. Both the boxing and the run-time type dispatch can cause loss of performance.
If captured variables are used in a performance-critical section of the code, then the following tips help ensure that their use is performant. First, if it is known that a captured variable does not change its type, then this can be declared explicitly with a type annotation (on the variable, not the right-hand side):
```
function abmult2(r0::Int)
r::Int = r0
if r < 0
r = -r
end
f = x -> x * r
return f
end
```
The type annotation partially recovers lost performance due to capturing because the parser can associate a concrete type to the object in the box. Going further, if the captured variable does not need to be boxed at all (because it will not be reassigned after the closure is created), this can be indicated with `let` blocks as follows.
```
function abmult3(r::Int)
if r < 0
r = -r
end
f = let r = r
x -> x * r
end
return f
end
```
The `let` block creates a new variable `r` whose scope is only the inner function. The second technique recovers full language performance in the presence of captured variables. Note that this is a rapidly evolving aspect of the compiler, and it is likely that future releases will not require this degree of programmer annotation to attain performance. In the mean time, some user-contributed packages like [FastClosures](https://github.com/c42f/FastClosures.jl) automate the insertion of `let` statements as in `abmult3`.
| programming_docs |
julia Variables Variables
=========
A variable, in Julia, is a name associated (or bound) to a value. It's useful when you want to store a value (that you obtained after some math, for example) for later use. For example:
```
# Assign the value 10 to the variable x
julia> x = 10
10
# Doing math with x's value
julia> x + 1
11
# Reassign x's value
julia> x = 1 + 1
2
# You can assign values of other types, like strings of text
julia> x = "Hello World!"
"Hello World!"
```
Julia provides an extremely flexible system for naming variables. Variable names are case-sensitive, and have no semantic meaning (that is, the language will not treat variables differently based on their names).
```
julia> x = 1.0
1.0
julia> y = -3
-3
julia> Z = "My string"
"My string"
julia> customary_phrase = "Hello world!"
"Hello world!"
julia> UniversalDeclarationOfHumanRightsStart = "人人生而自由,在尊严和权利上一律平等。"
"人人生而自由,在尊严和权利上一律平等。"
```
Unicode names (in UTF-8 encoding) are allowed:
```
julia> δ = 0.00001
1.0e-5
julia> 안녕하세요 = "Hello"
"Hello"
```
In the Julia REPL and several other Julia editing environments, you can type many Unicode math symbols by typing the backslashed LaTeX symbol name followed by tab. For example, the variable name `δ` can be entered by typing `\delta`-*tab*, or even `α̂⁽²⁾` by `\alpha`-*tab*-`\hat`- *tab*-`\^(2)`-*tab*. (If you find a symbol somewhere, e.g. in someone else's code, that you don't know how to type, the REPL help will tell you: just type `?` and then paste the symbol.)
Julia will even let you redefine built-in constants and functions if needed (although this is not recommended to avoid potential confusions):
```
julia> pi = 3
3
julia> pi
3
julia> sqrt = 4
4
```
However, if you try to redefine a built-in constant or function already in use, Julia will give you an error:
```
julia> pi
π = 3.1415926535897...
julia> pi = 3
ERROR: cannot assign a value to variable MathConstants.pi from module Main
julia> sqrt(100)
10.0
julia> sqrt = 4
ERROR: cannot assign a value to variable Base.sqrt from module Main
```
[Allowed Variable Names](#man-allowed-variable-names)
------------------------------------------------------
Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than 00A0; in particular, [Unicode character categories](https://www.fileformat.info/info/unicode/category/index.htm) Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols), and a few other letter-like characters (e.g. a subset of the Sm math symbols) are allowed. Subsequent characters may also include ! and digits (0-9 and other characters in categories Nd/No), as well as other Unicode code points: diacritics and other modifying marks (categories Mn/Mc/Me/Sk), some punctuation connectors (category Pc), primes, and a few other characters.
Operators like `+` are also valid identifiers, but are parsed specially. In some contexts, operators can be used just like variables; for example `(+)` refers to the addition function, and `(+) = f` will reassign it. Most of the Unicode infix operators (in category Sm), such as `⊕`, are parsed as infix operators and are available for user-defined methods (e.g. you can use `const ⊗ = kron` to define `⊗` as an infix Kronecker product). Operators can also be suffixed with modifying marks, primes, and sub/superscripts, e.g. `+̂ₐ″` is parsed as an infix operator with the same precedence as `+`. A space is required between an operator that ends with a subscript/superscript letter and a subsequent variable name. For example, if `+ᵃ` is an operator, then `+ᵃx` must be written as `+ᵃ x` to distinguish it from `+ ᵃx` where `ᵃx` is the variable name.
A particular class of variable names is one that contains only underscores. These identifiers can only be assigned values but cannot be used to assign values to other variables. More technically, they can only be used as an [L-value](https://en.wikipedia.org/wiki/Value_(computer_science)#lrvalue), but not as an [R-value](https://en.wikipedia.org/wiki/R-value):
```
julia> x, ___ = size([2 2; 1 1])
(2, 2)
julia> y = ___
ERROR: syntax: all-underscore identifier used as rvalue
```
The only explicitly disallowed names for variables are the names of the built-in [Keywords](../../base/base/index#Keywords):
```
julia> else = false
ERROR: syntax: unexpected "else"
julia> try = "No"
ERROR: syntax: unexpected "="
```
Some Unicode characters are considered to be equivalent in identifiers. Different ways of entering Unicode combining characters (e.g., accents) are treated as equivalent (specifically, Julia identifiers are [NFC](http://www.macchiato.com/unicode/nfc-faq)-normalized). Julia also includes a few non-standard equivalences for characters that are visually similar and are easily entered by some input methods. The Unicode characters `ɛ` (U+025B: Latin small letter open e) and `µ` (U+00B5: micro sign) are treated as equivalent to the corresponding Greek letters. The middle dot `·` (U+00B7) and the Greek [interpunct](https://en.wikipedia.org/wiki/Interpunct) `·` (U+0387) are both treated as the mathematical dot operator `⋅` (U+22C5). The minus sign `−` (U+2212) is treated as equivalent to the hyphen-minus sign `-` (U+002D).
[Stylistic Conventions](#Stylistic-Conventions)
------------------------------------------------
While Julia imposes few restrictions on valid names, it has become useful to adopt the following conventions:
* Names of variables are in lower case.
* Word separation can be indicated by underscores (`'_'`), but use of underscores is discouraged unless the name would be hard to read otherwise.
* Names of `Type`s and `Module`s begin with a capital letter and word separation is shown with upper camel case instead of underscores.
* Names of `function`s and `macro`s are in lower case, without underscores.
* Functions that write to their arguments have names that end in `!`. These are sometimes called "mutating" or "in-place" functions because they are intended to produce changes in their arguments after the function is called, not just return a value.
For more information about stylistic conventions, see the [Style Guide](../style-guide/index#Style-Guide).
julia Handling Operating System Variation Handling Operating System Variation
===================================
When writing cross-platform applications or libraries, it is often necessary to allow for differences between operating systems. The variable `Sys.KERNEL` can be used to handle such cases. There are several functions in the `Sys` module intended to make this easier, such as `isunix`, `islinux`, `isapple`, `isbsd`, `isfreebsd`, and `iswindows`. These may be used as follows:
```
if Sys.iswindows()
windows_specific_thing(a)
end
```
Note that `islinux`, `isapple`, and `isfreebsd` are mutually exclusive subsets of `isunix`. Additionally, there is a macro `@static` which makes it possible to use these functions to conditionally hide invalid code, as demonstrated in the following examples.
Simple blocks:
```
ccall((@static Sys.iswindows() ? :_fopen : :fopen), ...)
```
Complex blocks:
```
@static if Sys.islinux()
linux_specific_thing(a)
elseif Sys.isapple()
apple_specific_thing(a)
else
generic_thing(a)
end
```
When nesting conditionals, the `@static` must be repeated for each level (parentheses optional, but recommended for readability):
```
@static Sys.iswindows() ? :a : (@static Sys.isapple() ? :b : :c)
```
julia Noteworthy Differences from other Languages Noteworthy Differences from other Languages
===========================================
[Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
--------------------------------------------------------------------------
Although MATLAB users may find Julia's syntax familiar, Julia is not a MATLAB clone. There are major syntactic and functional differences. The following are some noteworthy differences that may trip up Julia users accustomed to MATLAB:
* Julia arrays are indexed with square brackets, `A[i,j]`.
* Julia arrays are not copied when assigned to another variable. After `A = B`, changing elements of `B` will modify `A` as well.
* Julia values are not copied when passed to a function. If a function modifies an array, the changes will be visible in the caller.
* Julia does not automatically grow arrays in an assignment statement. Whereas in MATLAB `a(4) = 3.2` can create the array `a = [0 0 0 3.2]` and `a(5) = 7` can grow it into `a = [0 0 0 3.2 7]`, the corresponding Julia statement `a[5] = 7` throws an error if the length of `a` is less than 5 or if this statement is the first use of the identifier `a`. Julia has [`push!`](../../base/collections/index#Base.push!) and [`append!`](../../base/collections/index#Base.append!), which grow `Vector`s much more efficiently than MATLAB's `a(end+1) = val`.
* The imaginary unit `sqrt(-1)` is represented in Julia as [`im`](../../base/numbers/index#Base.im), not `i` or `j` as in MATLAB.
* In Julia, literal numbers without a decimal point (such as `42`) create integers instead of floating point numbers. As a result, some operations can throw a domain error if they expect a float; for example, `julia> a = -1; 2^a` throws a domain error, as the result is not an integer (see [the FAQ entry on domain errors](../faq/index#faq-domain-errors) for details).
* In Julia, multiple values are returned and assigned as tuples, e.g. `(a, b) = (1, 2)` or `a, b = 1, 2`. MATLAB's `nargout`, which is often used in MATLAB to do optional work based on the number of returned values, does not exist in Julia. Instead, users can use optional and keyword arguments to achieve similar capabilities.
* Julia has true one-dimensional arrays. Column vectors are of size `N`, not `Nx1`. For example, [`rand(N)`](../../stdlib/random/index#Base.rand) makes a 1-dimensional array.
* In Julia, `[x,y,z]` will always construct a 3-element array containing `x`, `y` and `z`.
+ To concatenate in the first ("vertical") dimension use either [`vcat(x,y,z)`](../../base/arrays/index#Base.vcat) or separate with semicolons (`[x; y; z]`).
+ To concatenate in the second ("horizontal") dimension use either [`hcat(x,y,z)`](../../base/arrays/index#Base.hcat) or separate with spaces (`[x y z]`).
+ To construct block matrices (concatenating in the first two dimensions), use either [`hvcat`](../../base/arrays/index#Base.hvcat) or combine spaces and semicolons (`[a b; c d]`).
* In Julia, `a:b` and `a:b:c` construct `AbstractRange` objects. To construct a full vector like in MATLAB, use [`collect(a:b)`](#). Generally, there is no need to call `collect` though. An `AbstractRange` object will act like a normal array in most cases but is more efficient because it lazily computes its values. This pattern of creating specialized objects instead of full arrays is used frequently, and is also seen in functions such as [`range`](../../base/math/index#Base.range), or with iterators such as `enumerate`, and `zip`. The special objects can mostly be used as if they were normal arrays.
* Functions in Julia return values from their last expression or the `return` keyword instead of listing the names of variables to return in the function definition (see [The return Keyword](../functions/index#The-return-Keyword) for details).
* A Julia script may contain any number of functions, and all definitions will be externally visible when the file is loaded. Function definitions can be loaded from files outside the current working directory.
* In Julia, reductions such as [`sum`](../../base/collections/index#Base.sum), [`prod`](../../base/collections/index#Base.prod), and [`max`](../../base/math/index#Base.max) are performed over every element of an array when called with a single argument, as in `sum(A)`, even if `A` has more than one dimension.
* In Julia, parentheses must be used to call a function with zero arguments, like in [`rand()`](../../stdlib/random/index#Base.rand).
* Julia discourages the use of semicolons to end statements. The results of statements are not automatically printed (except at the interactive prompt), and lines of code do not need to end with semicolons. [`println`](../../base/io-network/index#Base.println) or [`@printf`](../../stdlib/printf/index#Printf.@printf) can be used to print specific output.
* In Julia, if `A` and `B` are arrays, logical comparison operations like `A == B` do not return an array of booleans. Instead, use `A .== B`, and similarly for the other boolean operators like [`<`](#), [`>`](#).
* In Julia, the operators [`&`](../../base/math/index#Base.:&), [`|`](#), and [`⊻`](../../base/math/index#Base.xor) ([`xor`](../../base/math/index#Base.xor)) perform the bitwise operations equivalent to `and`, `or`, and `xor` respectively in MATLAB, and have precedence similar to Python's bitwise operators (unlike C). They can operate on scalars or element-wise across arrays and can be used to combine logical arrays, but note the difference in order of operations: parentheses may be required (e.g., to select elements of `A` equal to 1 or 2 use `(A .== 1) .| (A .== 2)`).
* In Julia, the elements of a collection can be passed as arguments to a function using the splat operator `...`, as in `xs=[1,2]; f(xs...)`.
* Julia's [`svd`](../../stdlib/linearalgebra/index#LinearAlgebra.svd) returns singular values as a vector instead of as a dense diagonal matrix.
* In Julia, `...` is not used to continue lines of code. Instead, incomplete expressions automatically continue onto the next line.
* In both Julia and MATLAB, the variable `ans` is set to the value of the last expression issued in an interactive session. In Julia, unlike MATLAB, `ans` is not set when Julia code is run in non-interactive mode.
* Julia's `struct`s do not support dynamically adding fields at runtime, unlike MATLAB's `class`es. Instead, use a [`Dict`](../../base/collections/index#Base.Dict). Dict in Julia isn't ordered.
* In Julia each module has its own global scope/namespace, whereas in MATLAB there is just one global scope.
* In MATLAB, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression `x(x>3)` or in the statement `x(x>3) = []` to modify `x` in-place. In contrast, Julia provides the higher order functions [`filter`](../../base/collections/index#Base.filter) and [`filter!`](../../base/collections/index#Base.filter!), allowing users to write `filter(z->z>3, x)` and `filter!(z->z>3, x)` as alternatives to the corresponding transliterations `x[x.>3]` and `x = x[x.>3]`. Using [`filter!`](../../base/collections/index#Base.filter!) reduces the use of temporary arrays.
* The analogue of extracting (or "dereferencing") all elements of a cell array, e.g. in `vertcat(A{:})` in MATLAB, is written using the splat operator in Julia, e.g. as `vcat(A...)`.
* In Julia, the `adjoint` function performs conjugate transposition; in MATLAB, `adjoint` provides the "adjugate" or classical adjoint, which is the transpose of the matrix of cofactors.
* In Julia, a^b^c is evaluated a^(b^c) while in MATLAB it's (a^b)^c.
[Noteworthy differences from R](#Noteworthy-differences-from-R)
----------------------------------------------------------------
One of Julia's goals is to provide an effective language for data analysis and statistical programming. For users coming to Julia from R, these are some noteworthy differences:
* Julia's single quotes enclose characters, not strings.
* Julia can create substrings by indexing into strings. In R, strings must be converted into character vectors before creating substrings.
* In Julia, like Python but unlike R, strings can be created with triple quotes `""" ... """`. This syntax is convenient for constructing strings that contain line breaks.
* In Julia, varargs are specified using the splat operator `...`, which always follows the name of a specific variable, unlike R, for which `...` can occur in isolation.
* In Julia, modulus is `mod(a, b)`, not `a %% b`. `%` in Julia is the remainder operator.
* Julia constructs vectors using brackets. Julia's `[1, 2, 3]` is the equivalent of R's `c(1, 2, 3)`.
* In Julia, not all data structures support logical indexing. Furthermore, logical indexing in Julia is supported only with vectors of length equal to the object being indexed. For example:
+ In R, `c(1, 2, 3, 4)[c(TRUE, FALSE)]` is equivalent to `c(1, 3)`.
+ In R, `c(1, 2, 3, 4)[c(TRUE, FALSE, TRUE, FALSE)]` is equivalent to `c(1, 3)`.
+ In Julia, `[1, 2, 3, 4][[true, false]]` throws a [`BoundsError`](../../base/base/index#Core.BoundsError).
+ In Julia, `[1, 2, 3, 4][[true, false, true, false]]` produces `[1, 3]`.
* Like many languages, Julia does not always allow operations on vectors of different lengths, unlike R where the vectors only need to share a common index range. For example, `c(1, 2, 3, 4) + c(1, 2)` is valid R but the equivalent `[1, 2, 3, 4] + [1, 2]` will throw an error in Julia.
* Julia allows an optional trailing comma when that comma does not change the meaning of code. This can cause confusion among R users when indexing into arrays. For example, `x[1,]` in R would return the first row of a matrix; in Julia, however, the comma is ignored, so `x[1,] == x[1]`, and will return the first element. To extract a row, be sure to use `:`, as in `x[1,:]`.
* Julia's [`map`](../../base/collections/index#Base.map) takes the function first, then its arguments, unlike `lapply(<structure>, function, ...)` in R. Similarly Julia's equivalent of `apply(X, MARGIN, FUN, ...)` in R is [`mapslices`](../../base/arrays/index#Base.mapslices) where the function is the first argument.
* Multivariate apply in R, e.g. `mapply(choose, 11:13, 1:3)`, can be written as `broadcast(binomial, 11:13, 1:3)` in Julia. Equivalently Julia offers a shorter dot syntax for vectorizing functions `binomial.(11:13, 1:3)`.
* Julia uses `end` to denote the end of conditional blocks, like `if`, loop blocks, like `while`/ `for`, and functions. In lieu of the one-line `if ( cond ) statement`, Julia allows statements of the form `if cond; statement; end`, `cond && statement` and `!cond || statement`. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. `cond && (x = value)`.
* In Julia, `<-`, `<<-` and `->` are not assignment operators.
* Julia's `->` creates an anonymous function.
* Julia's [`*`](#) operator can perform matrix multiplication, unlike in R. If `A` and `B` are matrices, then `A * B` denotes a matrix multiplication in Julia, equivalent to R's `A %*% B`. In R, this same notation would perform an element-wise (Hadamard) product. To get the element-wise multiplication operation, you need to write `A .* B` in Julia.
* Julia performs matrix transposition using the `transpose` function and conjugated transposition using the `'` operator or the `adjoint` function. Julia's `transpose(A)` is therefore equivalent to R's `t(A)`. Additionally a non-recursive transpose in Julia is provided by the `permutedims` function.
* Julia does not require parentheses when writing `if` statements or `for`/`while` loops: use `for i in [1, 2, 3]` instead of `for (i in c(1, 2, 3))` and `if i == 1` instead of `if (i == 1)`.
* Julia does not treat the numbers `0` and `1` as Booleans. You cannot write `if (1)` in Julia, because `if` statements accept only booleans. Instead, you can write `if true`, `if Bool(1)`, or `if 1==1`.
* Julia does not provide `nrow` and `ncol`. Instead, use `size(M, 1)` for `nrow(M)` and `size(M, 2)` for `ncol(M)`.
* Julia is careful to distinguish scalars, vectors and matrices. In R, `1` and `c(1)` are the same. In Julia, they cannot be used interchangeably.
* Julia's [`diag`](../../stdlib/linearalgebra/index#LinearAlgebra.diag) and [`diagm`](../../stdlib/linearalgebra/index#LinearAlgebra.diagm) are not like R's.
* Julia cannot assign to the results of function calls on the left hand side of an assignment operation: you cannot write `diag(M) = fill(1, n)`.
* Julia discourages populating the main namespace with functions. Most statistical functionality for Julia is found in [packages](https://pkg.julialang.org/) under the [JuliaStats organization](https://github.com/JuliaStats). For example:
+ Functions pertaining to probability distributions are provided by the [Distributions package](https://github.com/JuliaStats/Distributions.jl).
+ The [DataFrames package](https://github.com/JuliaData/DataFrames.jl) provides data frames.
+ Generalized linear models are provided by the [GLM package](https://github.com/JuliaStats/GLM.jl).
* Julia provides tuples and real hash tables, but not R-style lists. When returning multiple items, you should typically use a tuple or a named tuple: instead of `list(a = 1, b = 2)`, use `(1, 2)` or `(a=1, b=2)`.
* Julia encourages users to write their own types, which are easier to use than S3 or S4 objects in R. Julia's multiple dispatch system means that `table(x::TypeA)` and `table(x::TypeB)` act like R's `table.TypeA(x)` and `table.TypeB(x)`.
* In Julia, values are not copied when assigned or passed to a function. If a function modifies an array, the changes will be visible in the caller. This is very different from R and allows new functions to operate on large data structures much more efficiently.
* In Julia, vectors and matrices are concatenated using [`hcat`](../../base/arrays/index#Base.hcat), [`vcat`](../../base/arrays/index#Base.vcat) and [`hvcat`](../../base/arrays/index#Base.hvcat), not `c`, `rbind` and `cbind` like in R.
* In Julia, a range like `a:b` is not shorthand for a vector like in R, but is a specialized `AbstractRange` object that is used for iteration. To convert a range into a vector, use [`collect(a:b)`](#).
* The `:` operator has a different precedence in R and Julia. In particular, in Julia arithmetic operators have higher precedence than the `:` operator, whereas the reverse is true in R. For example, `1:n-1` in Julia is equivalent to `1:(n-1)` in R.
* Julia's [`max`](../../base/math/index#Base.max) and [`min`](../../base/math/index#Base.min) are the equivalent of `pmax` and `pmin` respectively in R, but both arguments need to have the same dimensions. While [`maximum`](../../base/collections/index#Base.maximum) and [`minimum`](../../base/collections/index#Base.minimum) replace `max` and `min` in R, there are important differences.
* Julia's [`sum`](../../base/collections/index#Base.sum), [`prod`](../../base/collections/index#Base.prod), [`maximum`](../../base/collections/index#Base.maximum), and [`minimum`](../../base/collections/index#Base.minimum) are different from their counterparts in R. They all accept an optional keyword argument `dims`, which indicates the dimensions, over which the operation is carried out. For instance, let `A = [1 2; 3 4]` in Julia and `B <- rbind(c(1,2),c(3,4))` be the same matrix in R. Then `sum(A)` gives the same result as `sum(B)`, but `sum(A, dims=1)` is a row vector containing the sum over each column and `sum(A, dims=2)` is a column vector containing the sum over each row. This contrasts to the behavior of R, where separate `colSums(B)` and `rowSums(B)` functions provide these functionalities. If the `dims` keyword argument is a vector, then it specifies all the dimensions over which the sum is performed, while retaining the dimensions of the summed array, e.g. `sum(A, dims=(1,2)) == hcat(10)`. It should be noted that there is no error checking regarding the second argument.
* Julia has several functions that can mutate their arguments. For example, it has both [`sort`](../../base/sort/index#Base.sort) and [`sort!`](../../base/sort/index#Base.sort!).
* In R, performance requires vectorization. In Julia, almost the opposite is true: the best performing code is often achieved by using devectorized loops.
* Julia is eagerly evaluated and does not support R-style lazy evaluation. For most users, this means that there are very few unquoted expressions or column names.
* Julia does not support the `NULL` type. The closest equivalent is [`nothing`](../../base/constants/index#Core.nothing), but it behaves like a scalar value rather than like a list. Use `x === nothing` instead of `is.null(x)`.
* In Julia, missing values are represented by the [`missing`](../../base/base/index#Base.missing) object rather than by `NA`. Use [`ismissing(x)`](../../base/base/index#Base.ismissing) (or `ismissing.(x)` for element-wise operation on vectors) instead of `is.na(x)`. The [`skipmissing`](../../base/base/index#Base.skipmissing) function is generally used instead of `na.rm=TRUE` (though in some particular cases functions take a `skipmissing` argument).
* Julia lacks the equivalent of R's `assign` or `get`.
* In Julia, `return` does not require parentheses.
* In R, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression `x[x>3]` or in the statement `x = x[x>3]` to modify `x` in-place. In contrast, Julia provides the higher order functions [`filter`](../../base/collections/index#Base.filter) and [`filter!`](../../base/collections/index#Base.filter!), allowing users to write `filter(z->z>3, x)` and `filter!(z->z>3, x)` as alternatives to the corresponding transliterations `x[x.>3]` and `x = x[x.>3]`. Using [`filter!`](../../base/collections/index#Base.filter!) reduces the use of temporary arrays.
[Noteworthy differences from Python](#Noteworthy-differences-from-Python)
--------------------------------------------------------------------------
* Julia's `for`, `if`, `while`, etc. blocks are terminated by the `end` keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has no `pass` keyword.
* Strings are denoted by double quotation marks (`"text"`) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single (`'text'`) or double quotation marks (`"text"`). Single quotation marks are used for characters in Julia (`'c'`).
* String concatenation is done with `*` in Julia, not `+` like in Python. Analogously, string repetition is done with `^`, not `*`. Implicit string concatenation of string literals like in Python (e.g. `'ab' 'cd' == 'abcd'`) is not done in Julia.
* Python Lists—flexible but slow—correspond to the Julia `Vector{Any}` type or more generally `Vector{T}` where `T` is some non-concrete element type. "Fast" arrays like NumPy arrays that store elements in-place (i.e., `dtype` is `np.float64`, `[('f1', np.uint64), ('f2', np.int32)]`, etc.) can be represented by `Array{T}` where `T` is a concrete, immutable element type. This includes built-in types like `Float64`, `Int32`, `Int64` but also more complex types like `Tuple{UInt64,Float64}` and many user-defined types as well.
* In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
* Julia's slice indexing includes the last element, unlike in Python. `a[2:3]` in Julia is `a[1:3]` in Python.
* Unlike Python, Julia allows [AbstractArrays with arbitrary indexes](https://julialang.org/blog/2017/04/offset-arrays/). Python's special interpretation of negative indexing, `a[-1]` and `a[-2]`, should be written `a[end]` and `a[end-1]` in Julia.
* Julia requires `end` for indexing until the last element. `x[1:]` in Python is equivalent to `x[2:end]` in Julia.
* Julia's range indexing has the format of `x[start:step:stop]`, whereas Python's format is `x[start:(stop+1):step]`. Hence, `x[0:10:2]` in Python is equivalent to `x[1:2:10]` in Julia. Similarly, `x[::-1]` in Python, which refers to the reversed array, is equivalent to `x[end:-1:1]` in Julia.
* In Julia, ranges can be constructed independently as `start:step:stop`, the same syntax it uses in array-indexing. The `range` function is also supported.
* In Julia, indexing a matrix with arrays like `X[[1,2], [1,3]]` refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python, `X[[1,2], [1,3]]` refers to a vector that contains the values of cell `[1,1]` and `[2,3]` in the matrix. `X[[1,2], [1,3]]` in Julia is equivalent with `X[np.ix_([0,1],[0,2])]` in Python. `X[[0,1], [0,2]]` in Python is equivalent with `X[[CartesianIndex(1,1), CartesianIndex(2,3)]]` in Julia.
* Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
* Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (see [relevant section of Performance Tips](../performance-tips/index#man-performance-column-major)).
* Julia's updating operators (e.g. `+=`, `-=`, ...) are *not in-place* whereas NumPy's are. This means `A = [1, 1]; B = A; B += [3, 3]` doesn't change values in `A`, it rather rebinds the name `B` to the result of the right-hand side `B = B + 3`, which is a new array. For in-place operation, use `B .+= 3` (see also [dot operators](../mathematical-operations/index#man-dot-operators)), explicit loops, or `InplaceOps.jl`.
* Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function `f(x=rand()) = x` returns a new random number every time it is invoked without argument. On the other hand, the function `g(x=[1,2]) = push!(x,3)` returns `[1,2,3]` every time it is called as `g()`.
* In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a `MethodError` or calling of the wrong method.
* In Julia `%` is the remainder operator, whereas in Python it is the modulus.
* In Julia, the commonly used `Int` type corresponds to the machine integer type (`Int32` or `Int64`), unlike in Python, where `int` is an arbitrary length integer. This means in Julia the `Int` type will overflow, such that `2^64 == 0`. If you need larger values use another appropriate type, such as `Int128`, [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) or a floating point type like `Float64`.
* The imaginary unit `sqrt(-1)` is represented in Julia as `im`, not `j` as in Python.
* In Julia, the exponentiation operator is `^`, not `**` as in Python.
* Julia uses `nothing` of type `Nothing` to represent a null value, whereas Python uses `None` of type `NoneType`.
* In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both `A` and `B` are matrices, `A * B` in Julia performs matrix multiplication, not element-wise multiplication as in Python. `A * B` in Julia is equivalent with `A @ B` in Python, whereas `A * B` in Python is equivalent with `A .* B` in Julia.
* The adjoint operator `'` in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator `.T` over a vector in Python returns the original vector (non-op).
* In Julia, a function may contain multiple concrete implementations (called *methods*), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
* There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
* Calling a method of a class instance in Python (`x = MyClass(*args); x.f(y)`) corresponds to a function call in Julia, e.g. `x = MyType(args...); f(x, y)`. In general, multiple dispatch is more flexible and powerful than the Python class system.
* Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
* The logical Julia program structure (Packages and Modules) is independent of the file structure (`include` for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules).
* The ternary operator `x > 0 ? 1 : -1` in Julia corresponds to a conditional expression in Python `1 if x > 0 else -1`.
* In Julia the `@` symbol refers to a macro, whereas in Python it refers to a decorator.
* Exception handling in Julia is done using `try` — `catch` — `finally`, instead of `try` — `except` — `finally`. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching).
* In Julia loops are fast, there is no need to write "vectorized" code for performance reasons.
* Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (see [Performance Tips](../performance-tips/index#man-performance-tips)).
* In Julia, rounding and truncation are explicit. Python's `int(3.7)` should be `floor(Int, 3.7)` or `Int(floor(3.7))` and is distinguished from `round(Int, 3.7)`. `floor(x)` and `round(x)` on their own return an integer value of the same type as `x` rather than always returning `Int`.
* In Julia, parsing is explicit. Python's `float("3.7")` would be `parse(Float64, "3.7")` in Julia.
* In Python, the majority of values can be used in logical contexts (e.g. `if "a":` means the following block is executed, and `if "":` means it is not). In Julia, you need explicit conversion to `Bool` (e.g. `if "a"` throws an exception). If you want to test for a non-empty string in Julia, you would explicitly write `if !isempty("")`. Perhaps surprisingly, in Python `if "False"` and `bool("False")` both evaluate to `True` (because `"False"` is a non-empty string); in Julia, `parse(Bool, "false")` returns `false`.
* In Julia, a new local scope is introduced by most code blocks, including loops and `try` — `catch` — `finally`. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereas `if` blocks do not introduce a new local scope in both languages.
[Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
----------------------------------------------------------------------
* Julia arrays are indexed with square brackets, and can have more than one dimension `A[i,j]`. This syntax is not just syntactic sugar for a reference to a pointer or address as in C/C++. See [the manual entry about array construction](../arrays/index#man-multi-dim-arrays).
* In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
* Julia arrays are not copied when assigned to another variable. After `A = B`, changing elements of `B` will modify `A` as well. Updating operators like `+=` do not operate in-place, they are equivalent to `A = A + B` which rebinds the left-hand side to the result of the right-hand side expression.
* Julia arrays are column major (Fortran ordered) whereas C/C++ arrays are row major ordered by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to C/C++ (see [relevant section of Performance Tips](../performance-tips/index#man-performance-column-major)).
* Julia values are not copied when assigned or passed to a function. If a function modifies an array, the changes will be visible in the caller.
* In Julia, whitespace is significant, unlike C/C++, so care must be taken when adding/removing whitespace from a Julia program.
* In Julia, literal numbers without a decimal point (such as `42`) create signed integers, of type `Int`, but literals too large to fit in the machine word size will automatically be promoted to a larger size type, such as `Int64` (if `Int` is `Int32`), `Int128`, or the arbitrarily large `BigInt` type. There are no numeric literal suffixes, such as `L`, `LL`, `U`, `UL`, `ULL` to indicate unsigned and/or signed vs. unsigned. Decimal literals are always signed, and hexadecimal literals (which start with `0x` like C/C++), are unsigned, unless when they encode more than 128 bits, in which case they are of type `BigInt`. Hexadecimal literals also, unlike C/C++/Java and unlike decimal literals in Julia, have a type based on the *length* of the literal, including leading 0s. For example, `0x0` and `0x00` have type [`UInt8`](../../base/numbers/index#Core.UInt8), `0x000` and `0x0000` have type [`UInt16`](../../base/numbers/index#Core.UInt16), then literals with 5 to 8 hex digits have type `UInt32`, 9 to 16 hex digits type `UInt64`, 17 to 32 hex digits type `UInt128`, and more that 32 hex digits type `BigInt`. This needs to be taken into account when defining hexadecimal masks, for example `~0xf == 0xf0` is very different from `~0x000f == 0xfff0`. 64 bit `Float64` and 32 bit [`Float32`](../../base/numbers/index#Core.Float32) bit literals are expressed as `1.0` and `1.0f0` respectively. Floating point literals are rounded (and not promoted to the `BigFloat` type) if they can not be exactly represented. Floating point literals are closer in behavior to C/C++. Octal (prefixed with `0o`) and binary (prefixed with `0b`) literals are also treated as unsigned (or `BigInt` for more than 128 bits).
* In Julia, the division operator [`/`](../../base/math/index#Base.:/) returns a floating point number when both operands are of integer type. To perform integer division, use [`div`](../../base/math/index#Base.div) or [`÷`](../../base/math/index#Base.div).
* Indexing an `Array` with floating point types is generally an error in Julia. The Julia equivalent of the C expression `a[i / 2]` is `a[i ÷ 2 + 1]`, where `i` is of integer type.
* String literals can be delimited with either `"` or `"""`, `"""` delimited literals can contain `"` characters without quoting it like `"\""`. String literals can have values of other variables or expressions interpolated into them, indicated by `$variablename` or `$(expression)`, which evaluates the variable name or the expression in the context of the function.
* `//` indicates a [`Rational`](../../base/numbers/index#Base.Rational) number, and not a single-line comment (which is `#` in Julia)
* `#=` indicates the start of a multiline comment, and `=#` ends it.
* Functions in Julia return values from their last expression(s) or the `return` keyword. Multiple values can be returned from functions and assigned as tuples, e.g. `(a, b) = myfunction()` or `a, b = myfunction()`, instead of having to pass pointers to values as one would have to do in C/C++ (i.e. `a = myfunction(&b)`.
* Julia does not require the use of semicolons to end statements. The results of expressions are not automatically printed (except at the interactive prompt, i.e. the REPL), and lines of code do not need to end with semicolons. [`println`](../../base/io-network/index#Base.println) or [`@printf`](../../stdlib/printf/index#Printf.@printf) can be used to print specific output. In the REPL, `;` can be used to suppress output. `;` also has a different meaning within `[ ]`, something to watch out for. `;` can be used to separate expressions on a single line, but are not strictly necessary in many cases, and are more an aid to readability.
* In Julia, the operator [`⊻`](../../base/math/index#Base.xor) ([`xor`](../../base/math/index#Base.xor)) performs the bitwise XOR operation, i.e. [`^`](#) in C/C++. Also, the bitwise operators do not have the same precedence as C/C++, so parenthesis may be required.
* Julia's [`^`](#) is exponentiation (pow), not bitwise XOR as in C/C++ (use [`⊻`](../../base/math/index#Base.xor), or [`xor`](../../base/math/index#Base.xor), in Julia)
* Julia has two right-shift operators, `>>` and `>>>`. `>>` performs an arithmetic shift, `>>>` always performs a logical shift, unlike C/C++, where the meaning of `>>` depends on the type of the value being shifted.
* Julia's `->` creates an anonymous function, it does not access a member via a pointer.
* Julia does not require parentheses when writing `if` statements or `for`/`while` loops: use `for i in [1, 2, 3]` instead of `for (int i=1; i <= 3; i++)` and `if i == 1` instead of `if (i == 1)`.
* Julia does not treat the numbers `0` and `1` as Booleans. You cannot write `if (1)` in Julia, because `if` statements accept only booleans. Instead, you can write `if true`, `if Bool(1)`, or `if 1==1`.
* Julia uses `end` to denote the end of conditional blocks, like `if`, loop blocks, like `while`/ `for`, and functions. In lieu of the one-line `if ( cond ) statement`, Julia allows statements of the form `if cond; statement; end`, `cond && statement` and `!cond || statement`. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. `cond && (x = value)`, because of the operator precedence.
* Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
* Julia macros operate on parsed expressions, rather than the text of the program, which allows them to perform sophisticated transformations of Julia code. Macro names start with the `@` character, and have both a function-like syntax, `@mymacro(arg1, arg2, arg3)`, and a statement-like syntax, `@mymacro arg1 arg2 arg3`. The forms are interchangeable; the function-like form is particularly useful if the macro appears within another expression, and is often clearest. The statement-like form is often used to annotate blocks, as in the distributed `for` construct: `@distributed for i in 1:n; #= body =#; end`. Where the end of the macro construct may be unclear, use the function-like form.
* Julia has an enumeration type, expressed using the macro `@enum(name, value1, value2, ...)` For example: `@enum(Fruit, banana=1, apple, pear)`
* By convention, functions that modify their arguments have a `!` at the end of the name, for example `push!`.
* In C++, by default, you have static dispatch, i.e. you need to annotate a function as virtual, in order to have dynamic dispatch. On the other hand, in Julia every method is "virtual" (although it's more general than that since methods are dispatched on every argument type, not only `this`, using the most-specific-declaration rule).
[Noteworthy differences from Common Lisp](#Noteworthy-differences-from-Common-Lisp)
------------------------------------------------------------------------------------
* Julia uses 1-based indexing for arrays by default, and it can also handle arbitrary [index offsets](https://docs.julialang.org/en/v1.8/devdocs/offset-arrays/#man-custom-indices).
* Functions and variables share the same namespace (“Lisp-1”).
* There is a [`Pair`](../../base/collections/index#Core.Pair) type, but it is not meant to be used as a `COMMON-LISP:CONS`. Various iterable collections can be used interchangeably in most parts of the language (eg splatting, tuples, etc). `Tuple`s are the closest to Common Lisp lists for *short* collections of heterogeneous elements. Use `NamedTuple`s in place of alists. For larger collections of homogeneous types, `Array`s and `Dict`s should be used.
* The typical Julia workflow for prototyping also uses continuous manipulation of the image, implemented with the [Revise.jl](https://github.com/timholy/Revise.jl) package.
* For performance, Julia prefers that operations have [type stability](../faq/index#man-type-stability). Where Common Lisp abstracts away from the underlying machine operations, Julia cleaves closer to them. For example:
+ Integer division using `/` always returns a floating-point result, even if the computation is exact.
- `//` always returns a rational result
- `÷` always returns a (truncated) integer result
+ Bignums are supported, but conversion is not automatic; ordinary integers [overflow](../faq/index#faq-integer-arithmetic).
+ Complex numbers are supported, but to get complex results, [you need complex inputs](../faq/index#faq-domain-errors).
+ There are multiple Complex and Rational types, with different component types.
* Modules (namespaces) can be hierarchical. [`import`](../../base/base/index#import) and [`using`](../../base/base/index#using) have a dual role: they load the code and make it available in the namespace. `import` for only the module name is possible (roughly equivalent to `ASDF:LOAD-OP`). Slot names don't need to be exported separately. Global variables can't be assigned to from outside the module (except with `eval(mod, :(var = val))` as an escape hatch).
* Macros start with `@`, and are not as seamlessly integrated into the language as Common Lisp; consequently, macro usage is not as widespread as in the latter. A form of hygiene for [macros](../metaprogramming/index#Metaprogramming) is supported by the language. Because of the different surface syntax, there is no equivalent to `COMMON-LISP:&BODY`.
* *All* functions are generic and use multiple dispatch. Argument lists don't have to follow the same template, which leads to a powerful idiom (see [`do`](../../base/base/index#do)). Optional and keyword arguments are handled differently. Method ambiguities are not resolved like in the Common Lisp Object System, necessitating the definition of a more specific method for the intersection.
* Symbols do not belong to any package, and do not contain any values *per se*. `M.var` evaluates the symbol `var` in the module `M`.
* A functional programming style is fully supported by the language, including closures, but isn't always the idiomatic solution for Julia. Some [workarounds](../performance-tips/index#man-performance-captured) may be necessary for performance when modifying captured variables.
| programming_docs |
julia Multi-dimensional Arrays Multi-dimensional Arrays
========================
Julia, like most technical computing languages, provides a first-class array implementation. Most technical computing languages pay a lot of attention to their array implementation at the expense of other containers. Julia does not treat arrays in any special way. The array library is implemented almost completely in Julia itself, and derives its performance from the compiler, just like any other code written in Julia. As such, it's also possible to define custom array types by inheriting from [`AbstractArray`](../../base/arrays/index#Core.AbstractArray). See the [manual section on the AbstractArray interface](../interfaces/index#man-interface-array) for more details on implementing a custom array type.
An array is a collection of objects stored in a multi-dimensional grid. Zero-dimensional arrays are allowed, see [this FAQ entry](../faq/index#faq-array-0dim). In the most general case, an array may contain objects of type [`Any`](../../base/base/index#Core.Any). For most computational purposes, arrays should contain objects of a more specific type, such as [`Float64`](../../base/numbers/index#Core.Float64) or [`Int32`](../../base/numbers/index#Core.Int32).
In general, unlike many other technical computing languages, Julia does not expect programs to be written in a vectorized style for performance. Julia's compiler uses type inference and generates optimized code for scalar array indexing, allowing programs to be written in a style that is convenient and readable, without sacrificing performance, and using less memory at times.
In Julia, all arguments to functions are [passed by sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) (i.e. by pointers). Some technical computing languages pass arrays by value, and while this prevents accidental modification by callees of a value in the caller, it makes avoiding unwanted copying of arrays difficult. By convention, a function name ending with a `!` indicates that it will mutate or destroy the value of one or more of its arguments (compare, for example, [`sort`](../../base/sort/index#Base.sort) and [`sort!`](../../base/sort/index#Base.sort!)). Callees must make explicit copies to ensure that they don't modify inputs that they don't intend to change. Many non- mutating functions are implemented by calling a function of the same name with an added `!` at the end on an explicit copy of the input, and returning that copy.
[Basic Functions](#Basic-Functions)
------------------------------------
| Function | Description |
| --- | --- |
| [`eltype(A)`](../../base/collections/index#Base.eltype) | the type of the elements contained in `A` |
| [`length(A)`](#) | the number of elements in `A` |
| [`ndims(A)`](../../base/arrays/index#Base.ndims) | the number of dimensions of `A` |
| [`size(A)`](../../base/arrays/index#Base.size) | a tuple containing the dimensions of `A` |
| [`size(A,n)`](../../base/arrays/index#Base.size) | the size of `A` along dimension `n` |
| [`axes(A)`](#) | a tuple containing the valid indices of `A` |
| [`axes(A,n)`](#) | a range expressing the valid indices along dimension `n` |
| [`eachindex(A)`](../../base/arrays/index#Base.eachindex) | an efficient iterator for visiting each position in `A` |
| [`stride(A,k)`](../../base/arrays/index#Base.stride) | the stride (linear index distance between adjacent elements) along dimension `k` |
| [`strides(A)`](../../base/arrays/index#Base.strides) | a tuple of the strides in each dimension |
[Construction and Initialization](#Construction-and-Initialization)
--------------------------------------------------------------------
Many functions for constructing and initializing arrays are provided. In the following list of such functions, calls with a `dims...` argument can either take a single tuple of dimension sizes or a series of dimension sizes passed as a variable number of arguments. Most of these functions also accept a first input `T`, which is the element type of the array. If the type `T` is omitted it will default to [`Float64`](../../base/numbers/index#Core.Float64).
| Function | Description |
| --- | --- |
| [`Array{T}(undef, dims...)`](../../base/arrays/index#Core.Array) | an uninitialized dense [`Array`](../../base/arrays/index#Core.Array) |
| [`zeros(T, dims...)`](../../base/arrays/index#Base.zeros) | an `Array` of all zeros |
| [`ones(T, dims...)`](../../base/arrays/index#Base.ones) | an `Array` of all ones |
| [`trues(dims...)`](../../base/arrays/index#Base.trues) | a [`BitArray`](../../base/arrays/index#Base.BitArray) with all values `true` |
| [`falses(dims...)`](../../base/arrays/index#Base.falses) | a `BitArray` with all values `false` |
| [`reshape(A, dims...)`](../../base/arrays/index#Base.reshape) | an array containing the same data as `A`, but with different dimensions |
| [`copy(A)`](../../base/base/index#Base.copy) | copy `A` |
| [`deepcopy(A)`](../../base/base/index#Base.deepcopy) | copy `A`, recursively copying its elements |
| [`similar(A, T, dims...)`](../../base/arrays/index#Base.similar) | an uninitialized array of the same type as `A` (dense, sparse, etc.), but with the specified element type and dimensions. The second and third arguments are both optional, defaulting to the element type and dimensions of `A` if omitted. |
| [`reinterpret(T, A)`](../../base/arrays/index#Base.reinterpret) | an array with the same binary data as `A`, but with element type `T` |
| [`rand(T, dims...)`](../../stdlib/random/index#Base.rand) | an `Array` with random, iid [[1]](#footnote-1) and uniformly distributed values in the half-open interval $[0, 1)$ |
| [`randn(T, dims...)`](../../stdlib/random/index#Base.randn) | an `Array` with random, iid and standard normally distributed values |
| [`Matrix{T}(I, m, n)`](../../base/arrays/index#Base.Matrix) | `m`-by-`n` identity matrix. Requires `using LinearAlgebra` for [`I`](../../stdlib/linearalgebra/index#LinearAlgebra.I). |
| [`range(start, stop, n)`](../../base/math/index#Base.range) | a range of `n` linearly spaced elements from `start` to `stop` |
| [`fill!(A, x)`](../../base/arrays/index#Base.fill!) | fill the array `A` with the value `x` |
| [`fill(x, dims...)`](../../base/arrays/index#Base.fill) | an `Array` filled with the value `x`. In particular, `fill(x)` constructs a zero-dimensional `Array` containing `x`. |
To see the various ways we can pass dimensions to these functions, consider the following examples:
```
julia> zeros(Int8, 2, 3)
2×3 Matrix{Int8}:
0 0 0
0 0 0
julia> zeros(Int8, (2, 3))
2×3 Matrix{Int8}:
0 0 0
0 0 0
julia> zeros((2, 3))
2×3 Matrix{Float64}:
0.0 0.0 0.0
0.0 0.0 0.0
```
Here, `(2, 3)` is a [`Tuple`](../../base/base/index#Core.Tuple) and the first argument — the element type — is optional, defaulting to `Float64`.
[Array literals](#man-array-literals)
--------------------------------------
Arrays can also be directly constructed with square braces; the syntax `[A, B, C, ...]` creates a one-dimensional array (i.e., a vector) containing the comma-separated arguments as its elements. The element type ([`eltype`](../../base/collections/index#Base.eltype)) of the resulting array is automatically determined by the types of the arguments inside the braces. If all the arguments are the same type, then that is its `eltype`. If they all have a common [promotion type](../conversion-and-promotion/index#conversion-and-promotion) then they get converted to that type using [`convert`](../../base/base/index#Base.convert) and that type is the array's `eltype`. Otherwise, a heterogeneous array that can hold anything — a `Vector{Any}` — is constructed; this includes the literal `[]` where no arguments are given.
```
julia> [1,2,3] # An array of `Int`s
3-element Vector{Int64}:
1
2
3
julia> promote(1, 2.3, 4//5) # This combination of Int, Float64 and Rational promotes to Float64
(1.0, 2.3, 0.8)
julia> [1, 2.3, 4//5] # Thus that's the element type of this Array
3-element Vector{Float64}:
1.0
2.3
0.8
julia> []
Any[]
```
###
[Concatenation](#man-array-concatenation)
If the arguments inside the square brackets are separated by single semicolons (`;`) or newlines instead of commas, then their contents are *vertically concatenated* together instead of the arguments being used as elements themselves.
```
julia> [1:2, 4:5] # Has a comma, so no concatenation occurs. The ranges are themselves the elements
2-element Vector{UnitRange{Int64}}:
1:2
4:5
julia> [1:2; 4:5]
4-element Vector{Int64}:
1
2
4
5
julia> [1:2
4:5
6]
5-element Vector{Int64}:
1
2
4
5
6
```
Similarly, if the arguments are separated by tabs or spaces or double semicolons, then their contents are *horizontally concatenated* together.
```
julia> [1:2 4:5 7:8]
2×3 Matrix{Int64}:
1 4 7
2 5 8
julia> [[1,2] [4,5] [7,8]]
2×3 Matrix{Int64}:
1 4 7
2 5 8
julia> [1 2 3] # Numbers can also be horizontally concatenated
1×3 Matrix{Int64}:
1 2 3
julia> [1;; 2;; 3;; 4]
1×4 Matrix{Int64}:
1 2 3 4
```
Single semicolons (or newlines) and spaces (or tabs) can be combined to concatenate both horizontally and vertically at the same time.
```
julia> [1 2
3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> [zeros(Int, 2, 2) [1; 2]
[3 4] 5]
3×3 Matrix{Int64}:
0 0 1
0 0 2
3 4 5
julia> [[1 1]; 2 3; [4 4]]
3×2 Matrix{Int64}:
1 1
2 3
4 4
```
Spaces (and tabs) have a higher precedence than semicolons, performing any horizontal concatenations first and then concatenating the result. Using double semicolons for the horizontal concatenation, on the other hand, performs any vertical concatenations before horizontally concatenating the result.
```
julia> [zeros(Int, 2, 2) ; [3 4] ;; [1; 2] ; 5]
3×3 Matrix{Int64}:
0 0 1
0 0 2
3 4 5
julia> [1:2; 4;; 1; 3:4]
3×2 Matrix{Int64}:
1 1
2 3
4 4
```
Just as `;` and `;;` concatenate in the first and second dimension, using more semicolons extends this same general scheme. The number of semicolons in the separator specifies the particular dimension, so `;;;` concatenates in the third dimension, `;;;;` in the 4th, and so on. Fewer semicolons take precedence, so the lower dimensions are generally concatenated first.
```
julia> [1; 2;; 3; 4;; 5; 6;;;
7; 8;; 9; 10;; 11; 12]
2×3×2 Array{Int64, 3}:
[:, :, 1] =
1 3 5
2 4 6
[:, :, 2] =
7 9 11
8 10 12
```
Like before, spaces (and tabs) for horizontal concatenation have a higher precedence than any number of semicolons. Thus, higher-dimensional arrays can also be written by specifying their rows first, with their elements textually arranged in a manner similar to their layout:
```
julia> [1 3 5
2 4 6;;;
7 9 11
8 10 12]
2×3×2 Array{Int64, 3}:
[:, :, 1] =
1 3 5
2 4 6
[:, :, 2] =
7 9 11
8 10 12
julia> [1 2;;; 3 4;;;; 5 6;;; 7 8]
1×2×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
1 2
[:, :, 2, 1] =
3 4
[:, :, 1, 2] =
5 6
[:, :, 2, 2] =
7 8
julia> [[1 2;;; 3 4];;;; [5 6];;; [7 8]]
1×2×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
1 2
[:, :, 2, 1] =
3 4
[:, :, 1, 2] =
5 6
[:, :, 2, 2] =
7 8
```
Although they both mean concatenation in the second dimension, spaces (or tabs) and `;;` cannot appear in the same array expression unless the double semicolon is simply serving as a "line continuation" character. This allows a single horizontal concatenation to span multiple lines (without the line break being interpreted as a vertical concatenation).
```
julia> [1 2 ;;
3 4]
1×4 Matrix{Int64}:
1 2 3 4
```
Terminating semicolons may also be used to add trailing length 1 dimensions.
```
julia> [1;;]
1×1 Matrix{Int64}:
1
julia> [2; 3;;;]
2×1×1 Array{Int64, 3}:
[:, :, 1] =
2
3
```
More generally, concatenation can be accomplished through the [`cat`](../../base/arrays/index#Base.cat) function. These syntaxes are shorthands for function calls that themselves are convenience functions:
| Syntax | Function | Description |
| --- | --- | --- |
| | [`cat`](../../base/arrays/index#Base.cat) | concatenate input arrays along dimension(s) `k` |
| `[A; B; C; ...]` | [`vcat`](../../base/arrays/index#Base.vcat) | shorthand for `cat(A...; dims=1) |
| `[A B C ...]` | [`hcat`](../../base/arrays/index#Base.hcat) | shorthand for `cat(A...; dims=2) |
| `[A B; C D; ...]` | [`hvcat`](../../base/arrays/index#Base.hvcat) | simultaneous vertical and horizontal concatenation |
| `[A; C;; B; D;;; ...]` | [`hvncat`](../../base/arrays/index#Base.hvncat) | simultaneous n-dimensional concatenation, where number of semicolons indicate the dimension to concatenate |
###
[Typed array literals](#Typed-array-literals)
An array with a specific element type can be constructed using the syntax `T[A, B, C, ...]`. This will construct a 1-d array with element type `T`, initialized to contain elements `A`, `B`, `C`, etc. For example, `Any[x, y, z]` constructs a heterogeneous array that can contain any values.
Concatenation syntax can similarly be prefixed with a type to specify the element type of the result.
```
julia> [[1 2] [3 4]]
1×4 Matrix{Int64}:
1 2 3 4
julia> Int8[[1 2] [3 4]]
1×4 Matrix{Int8}:
1 2 3 4
```
[Comprehensions](#man-comprehensions)
--------------------------------------
Comprehensions provide a general and powerful way to construct arrays. Comprehension syntax is similar to set construction notation in mathematics:
```
A = [ F(x,y,...) for x=rx, y=ry, ... ]
```
The meaning of this form is that `F(x,y,...)` is evaluated with the variables `x`, `y`, etc. taking on each value in their given list of values. Values can be specified as any iterable object, but will commonly be ranges like `1:n` or `2:(n-1)`, or explicit arrays of values like `[1.2, 3.4, 5.7]`. The result is an N-d dense array with dimensions that are the concatenation of the dimensions of the variable ranges `rx`, `ry`, etc. and each `F(x,y,...)` evaluation returns a scalar.
The following example computes a weighted average of the current element and its left and right neighbor along a 1-d grid. :
```
julia> x = rand(8)
8-element Array{Float64,1}:
0.843025
0.869052
0.365105
0.699456
0.977653
0.994953
0.41084
0.809411
julia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]
6-element Array{Float64,1}:
0.736559
0.57468
0.685417
0.912429
0.8446
0.656511
```
The resulting array type depends on the types of the computed elements just like [array literals](#man-array-literals) do. In order to control the type explicitly, a type can be prepended to the comprehension. For example, we could have requested the result in single precision by writing:
```
Float32[ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]
```
[Generator Expressions](#Generator-Expressions)
------------------------------------------------
Comprehensions can also be written without the enclosing square brackets, producing an object known as a generator. This object can be iterated to produce values on demand, instead of allocating an array and storing them in advance (see [Iteration](#Iteration)). For example, the following expression sums a series without allocating memory:
```
julia> sum(1/n^2 for n=1:1000)
1.6439345666815615
```
When writing a generator expression with multiple dimensions inside an argument list, parentheses are needed to separate the generator from subsequent arguments:
```
julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;])
ERROR: syntax: invalid iteration specification
```
All comma-separated expressions after `for` are interpreted as ranges. Adding parentheses lets us add a third argument to [`map`](../../base/collections/index#Base.map):
```
julia> map(tuple, (1/(i+j) for i=1:2, j=1:2), [1 3; 2 4])
2×2 Matrix{Tuple{Float64, Int64}}:
(0.5, 1) (0.333333, 3)
(0.333333, 2) (0.25, 4)
```
Generators are implemented via inner functions. Just like inner functions used elsewhere in the language, variables from the enclosing scope can be "captured" in the inner function. For example, `sum(p[i] - q[i] for i=1:n)` captures the three variables `p`, `q` and `n` from the enclosing scope. Captured variables can present performance challenges; see [performance tips](../performance-tips/index#man-performance-captured).
Ranges in generators and comprehensions can depend on previous ranges by writing multiple `for` keywords:
```
julia> [(i,j) for i=1:3 for j=1:i]
6-element Vector{Tuple{Int64, Int64}}:
(1, 1)
(2, 1)
(2, 2)
(3, 1)
(3, 2)
(3, 3)
```
In such cases, the result is always 1-d.
Generated values can be filtered using the `if` keyword:
```
julia> [(i,j) for i=1:3 for j=1:i if i+j == 4]
2-element Vector{Tuple{Int64, Int64}}:
(2, 2)
(3, 1)
```
[Indexing](#man-array-indexing)
--------------------------------
The general syntax for indexing into an n-dimensional array `A` is:
```
X = A[I_1, I_2, ..., I_n]
```
where each `I_k` may be a scalar integer, an array of integers, or any other [supported index](#man-supported-index-types). This includes [`Colon`](../../base/arrays/index#Base.Colon) (`:`) to select all indices within the entire dimension, ranges of the form `a:c` or `a:b:c` to select contiguous or strided subsections, and arrays of booleans to select elements at their `true` indices.
If all the indices are scalars, then the result `X` is a single element from the array `A`. Otherwise, `X` is an array with the same number of dimensions as the sum of the dimensionalities of all the indices.
If all indices `I_k` are vectors, for example, then the shape of `X` would be `(length(I_1), length(I_2), ..., length(I_n))`, with location `i_1, i_2, ..., i_n` of `X` containing the value `A[I_1[i_1], I_2[i_2], ..., I_n[i_n]]`.
Example:
```
julia> A = reshape(collect(1:16), (2, 2, 2, 2))
2×2×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
1 3
2 4
[:, :, 2, 1] =
5 7
6 8
[:, :, 1, 2] =
9 11
10 12
[:, :, 2, 2] =
13 15
14 16
julia> A[1, 2, 1, 1] # all scalar indices
3
julia> A[[1, 2], [1], [1, 2], [1]] # all vector indices
2×1×2×1 Array{Int64, 4}:
[:, :, 1, 1] =
1
2
[:, :, 2, 1] =
5
6
julia> A[[1, 2], [1], [1, 2], 1] # a mix of index types
2×1×2 Array{Int64, 3}:
[:, :, 1] =
1
2
[:, :, 2] =
5
6
```
Note how the size of the resulting array is different in the last two cases.
If `I_1` is changed to a two-dimensional matrix, then `X` becomes an `n+1`-dimensional array of shape `(size(I_1, 1), size(I_1, 2), length(I_2), ..., length(I_n))`. The matrix adds a dimension.
Example:
```
julia> A = reshape(collect(1:16), (2, 2, 2, 2));
julia> A[[1 2; 1 2]]
2×2 Matrix{Int64}:
1 2
1 2
julia> A[[1 2; 1 2], 1, 2, 1]
2×2 Matrix{Int64}:
5 6
5 6
```
The location `i_1, i_2, i_3, ..., i_{n+1}` contains the value at `A[I_1[i_1, i_2], I_2[i_3], ..., I_n[i_{n+1}]]`. All dimensions indexed with scalars are dropped. For example, if `J` is an array of indices, then the result of `A[2, J, 3]` is an array with size `size(J)`. Its `j`th element is populated by `A[2, J[j], 3]`.
As a special part of this syntax, the `end` keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the innermost array being indexed. Indexing syntax without the `end` keyword is equivalent to a call to [`getindex`](../../base/collections/index#Base.getindex):
```
X = getindex(A, I_1, I_2, ..., I_n)
```
Example:
```
julia> x = reshape(1:16, 4, 4)
4×4 reshape(::UnitRange{Int64}, 4, 4) with eltype Int64:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> x[2:3, 2:end-1]
2×2 Matrix{Int64}:
6 10
7 11
julia> x[1, [2 3; 4 1]]
2×2 Matrix{Int64}:
5 9
13 1
```
[Indexed Assignment](#man-indexed-assignment)
----------------------------------------------
The general syntax for assigning values in an n-dimensional array `A` is:
```
A[I_1, I_2, ..., I_n] = X
```
where each `I_k` may be a scalar integer, an array of integers, or any other [supported index](#man-supported-index-types). This includes [`Colon`](../../base/arrays/index#Base.Colon) (`:`) to select all indices within the entire dimension, ranges of the form `a:c` or `a:b:c` to select contiguous or strided subsections, and arrays of booleans to select elements at their `true` indices.
If all indices `I_k` are integers, then the value in location `I_1, I_2, ..., I_n` of `A` is overwritten with the value of `X`, [`convert`](../../base/base/index#Base.convert)ing to the [`eltype`](../../base/collections/index#Base.eltype) of `A` if necessary.
If any index `I_k` is itself an array, then the right hand side `X` must also be an array with the same shape as the result of indexing `A[I_1, I_2, ..., I_n]` or a vector with the same number of elements. The value in location `I_1[i_1], I_2[i_2], ..., I_n[i_n]` of `A` is overwritten with the value `X[I_1, I_2, ..., I_n]`, converting if necessary. The element-wise assignment operator `.=` may be used to [broadcast](#Broadcasting) `X` across the selected locations:
```
A[I_1, I_2, ..., I_n] .= X
```
Just as in [Indexing](#man-array-indexing), the `end` keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the array being assigned into. Indexed assignment syntax without the `end` keyword is equivalent to a call to [`setindex!`](../../base/collections/index#Base.setindex!):
```
setindex!(A, X, I_1, I_2, ..., I_n)
```
Example:
```
julia> x = collect(reshape(1:9, 3, 3))
3×3 Matrix{Int64}:
1 4 7
2 5 8
3 6 9
julia> x[3, 3] = -9;
julia> x[1:2, 1:2] = [-1 -4; -2 -5];
julia> x
3×3 Matrix{Int64}:
-1 -4 7
-2 -5 8
3 6 -9
```
[Supported index types](#man-supported-index-types)
----------------------------------------------------
In the expression `A[I_1, I_2, ..., I_n]`, each `I_k` may be a scalar index, an array of scalar indices, or an object that represents an array of scalar indices and can be converted to such by [`to_indices`](../../base/arrays/index#Base.to_indices):
1. A scalar index. By default this includes:
* Non-boolean integers
* [`CartesianIndex{N}`](../../base/arrays/index#Base.IteratorsMD.CartesianIndex)s, which behave like an `N`-tuple of integers spanning multiple dimensions (see below for more details)
2. An array of scalar indices. This includes:
* Vectors and multidimensional arrays of integers
* Empty arrays like `[]`, which select no elements
* Ranges like `a:c` or `a:b:c`, which select contiguous or strided subsections from `a` to `c` (inclusive)
* Any custom array of scalar indices that is a subtype of `AbstractArray`
* Arrays of `CartesianIndex{N}` (see below for more details)
3. An object that represents an array of scalar indices and can be converted to such by [`to_indices`](../../base/arrays/index#Base.to_indices). By default this includes:
* [`Colon()`](../../base/arrays/index#Base.Colon) (`:`), which represents all indices within an entire dimension or across the entire array
* Arrays of booleans, which select elements at their `true` indices (see below for more details)
Some examples:
```
julia> A = reshape(collect(1:2:18), (3, 3))
3×3 Matrix{Int64}:
1 7 13
3 9 15
5 11 17
julia> A[4]
7
julia> A[[2, 5, 8]]
3-element Vector{Int64}:
3
9
15
julia> A[[1 4; 3 8]]
2×2 Matrix{Int64}:
1 7
5 15
julia> A[[]]
Int64[]
julia> A[1:2:5]
3-element Vector{Int64}:
1
5
9
julia> A[2, :]
3-element Vector{Int64}:
3
9
15
julia> A[:, 3]
3-element Vector{Int64}:
13
15
17
julia> A[:, 3:3]
3×1 Matrix{Int64}:
13
15
17
```
###
[Cartesian indices](#Cartesian-indices)
The special `CartesianIndex{N}` object represents a scalar index that behaves like an `N`-tuple of integers spanning multiple dimensions. For example:
```
julia> A = reshape(1:32, 4, 4, 2);
julia> A[3, 2, 1]
7
julia> A[CartesianIndex(3, 2, 1)] == A[3, 2, 1] == 7
true
```
Considered alone, this may seem relatively trivial; `CartesianIndex` simply gathers multiple integers together into one object that represents a single multidimensional index. When combined with other indexing forms and iterators that yield `CartesianIndex`es, however, this can produce very elegant and efficient code. See [Iteration](#Iteration) below, and for some more advanced examples, see [this blog post on multidimensional algorithms and iteration](https://julialang.org/blog/2016/02/iteration).
Arrays of `CartesianIndex{N}` are also supported. They represent a collection of scalar indices that each span `N` dimensions, enabling a form of indexing that is sometimes referred to as pointwise indexing. For example, it enables accessing the diagonal elements from the first "page" of `A` from above:
```
julia> page = A[:,:,1]
4×4 Matrix{Int64}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> page[[CartesianIndex(1,1),
CartesianIndex(2,2),
CartesianIndex(3,3),
CartesianIndex(4,4)]]
4-element Vector{Int64}:
1
6
11
16
```
This can be expressed much more simply with [dot broadcasting](../functions/index#man-vectorized) and by combining it with a normal integer index (instead of extracting the first `page` from `A` as a separate step). It can even be combined with a `:` to extract both diagonals from the two pages at the same time:
```
julia> A[CartesianIndex.(axes(A, 1), axes(A, 2)), 1]
4-element Vector{Int64}:
1
6
11
16
julia> A[CartesianIndex.(axes(A, 1), axes(A, 2)), :]
4×2 Matrix{Int64}:
1 17
6 22
11 27
16 32
```
`CartesianIndex` and arrays of `CartesianIndex` are not compatible with the `end` keyword to represent the last index of a dimension. Do not use `end` in indexing expressions that may contain either `CartesianIndex` or arrays thereof.
###
[Logical indexing](#Logical-indexing)
Often referred to as logical indexing or indexing with a logical mask, indexing by a boolean array selects elements at the indices where its values are `true`. Indexing by a boolean vector `B` is effectively the same as indexing by the vector of integers that is returned by [`findall(B)`](#). Similarly, indexing by a `N`-dimensional boolean array is effectively the same as indexing by the vector of `CartesianIndex{N}`s where its values are `true`. A logical index must be a vector of the same length as the dimension it indexes into, or it must be the only index provided and match the size and dimensionality of the array it indexes into. It is generally more efficient to use boolean arrays as indices directly instead of first calling [`findall`](#).
```
julia> x = reshape(1:16, 4, 4)
4×4 reshape(::UnitRange{Int64}, 4, 4) with eltype Int64:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> x[[false, true, true, false], :]
2×4 Matrix{Int64}:
2 6 10 14
3 7 11 15
julia> mask = map(ispow2, x)
4×4 Matrix{Bool}:
1 0 0 0
1 0 0 0
0 0 0 0
1 1 0 1
julia> x[mask]
5-element Vector{Int64}:
1
2
4
8
16
```
###
[Number of indices](#Number-of-indices)
####
[Cartesian indexing](#Cartesian-indexing)
The ordinary way to index into an `N`-dimensional array is to use exactly `N` indices; each index selects the position(s) in its particular dimension. For example, in the three-dimensional array `A = rand(4, 3, 2)`, `A[2, 3, 1]` will select the number in the second row of the third column in the first "page" of the array. This is often referred to as *cartesian indexing*.
####
[Linear indexing](#Linear-indexing)
When exactly one index `i` is provided, that index no longer represents a location in a particular dimension of the array. Instead, it selects the `i`th element using the column-major iteration order that linearly spans the entire array. This is known as *linear indexing*. It essentially treats the array as though it had been reshaped into a one-dimensional vector with [`vec`](../../base/arrays/index#Base.vec).
```
julia> A = [2 6; 4 7; 3 1]
3×2 Matrix{Int64}:
2 6
4 7
3 1
julia> A[5]
7
julia> vec(A)[5]
7
```
A linear index into the array `A` can be converted to a `CartesianIndex` for cartesian indexing with `CartesianIndices(A)[i]` (see [`CartesianIndices`](../../base/arrays/index#Base.IteratorsMD.CartesianIndices)), and a set of `N` cartesian indices can be converted to a linear index with `LinearIndices(A)[i_1, i_2, ..., i_N]` (see [`LinearIndices`](../../base/arrays/index#Base.LinearIndices)).
```
julia> CartesianIndices(A)[5]
CartesianIndex(2, 2)
julia> LinearIndices(A)[2, 2]
5
```
It's important to note that there's a very large asymmetry in the performance of these conversions. Converting a linear index to a set of cartesian indices requires dividing and taking the remainder, whereas going the other way is just multiplies and adds. In modern processors, integer division can be 10-50 times slower than multiplication. While some arrays — like [`Array`](../../base/arrays/index#Core.Array) itself — are implemented using a linear chunk of memory and directly use a linear index in their implementations, other arrays — like [`Diagonal`](../../stdlib/linearalgebra/index#LinearAlgebra.Diagonal) — need the full set of cartesian indices to do their lookup (see [`IndexStyle`](../../base/arrays/index#Base.IndexStyle) to introspect which is which). As such, when iterating over an entire array, it's much better to iterate over [`eachindex(A)`](../../base/arrays/index#Base.eachindex) instead of `1:length(A)`. Not only will the former be much faster in cases where `A` is `IndexCartesian`, but it will also support [OffsetArrays](https://github.com/JuliaArrays/OffsetArrays.jl), too.
####
[Omitted and extra indices](#Omitted-and-extra-indices)
In addition to linear indexing, an `N`-dimensional array may be indexed with fewer or more than `N` indices in certain situations.
Indices may be omitted if the trailing dimensions that are not indexed into are all length one. In other words, trailing indices can be omitted only if there is only one possible value that those omitted indices could be for an in-bounds indexing expression. For example, a four-dimensional array with size `(3, 4, 2, 1)` may be indexed with only three indices as the dimension that gets skipped (the fourth dimension) has length one. Note that linear indexing takes precedence over this rule.
```
julia> A = reshape(1:24, 3, 4, 2, 1)
3×4×2×1 reshape(::UnitRange{Int64}, 3, 4, 2, 1) with eltype Int64:
[:, :, 1, 1] =
1 4 7 10
2 5 8 11
3 6 9 12
[:, :, 2, 1] =
13 16 19 22
14 17 20 23
15 18 21 24
julia> A[1, 3, 2] # Omits the fourth dimension (length 1)
19
julia> A[1, 3] # Attempts to omit dimensions 3 & 4 (lengths 2 and 1)
ERROR: BoundsError: attempt to access 3×4×2×1 reshape(::UnitRange{Int64}, 3, 4, 2, 1) with eltype Int64 at index [1, 3]
julia> A[19] # Linear indexing
19
```
When omitting *all* indices with `A[]`, this semantic provides a simple idiom to retrieve the only element in an array and simultaneously ensure that there was only one element.
Similarly, more than `N` indices may be provided if all the indices beyond the dimensionality of the array are `1` (or more generally are the first and only element of `axes(A, d)` where `d` is that particular dimension number). This allows vectors to be indexed like one-column matrices, for example:
```
julia> A = [8,6,7]
3-element Vector{Int64}:
8
6
7
julia> A[2,1]
6
```
[Iteration](#Iteration)
------------------------
The recommended ways to iterate over a whole array are
```
for a in A
# Do something with the element a
end
for i in eachindex(A)
# Do something with i and/or A[i]
end
```
The first construct is used when you need the value, but not index, of each element. In the second construct, `i` will be an `Int` if `A` is an array type with fast linear indexing; otherwise, it will be a `CartesianIndex`:
```
julia> A = rand(4,3);
julia> B = view(A, 1:3, 2:3);
julia> for i in eachindex(B)
@show i
end
i = CartesianIndex(1, 1)
i = CartesianIndex(2, 1)
i = CartesianIndex(3, 1)
i = CartesianIndex(1, 2)
i = CartesianIndex(2, 2)
i = CartesianIndex(3, 2)
```
In contrast with `for i = 1:length(A)`, iterating with [`eachindex`](../../base/arrays/index#Base.eachindex) provides an efficient way to iterate over any array type.
[Array traits](#Array-traits)
------------------------------
If you write a custom [`AbstractArray`](../../base/arrays/index#Core.AbstractArray) type, you can specify that it has fast linear indexing using
```
Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()
```
This setting will cause `eachindex` iteration over a `MyArray` to use integers. If you don't specify this trait, the default value `IndexCartesian()` is used.
[Array and Vectorized Operators and Functions](#man-array-and-vectorized-operators-and-functions)
--------------------------------------------------------------------------------------------------
The following operators are supported for arrays:
1. Unary arithmetic – `-`, `+`
2. Binary arithmetic – `-`, `+`, `*`, `/`, `\`, `^`
3. Comparison – `==`, `!=`, `≈` ([`isapprox`](../../base/math/index#Base.isapprox)), `≉`
To enable convenient vectorization of mathematical and other operations, Julia [provides the dot syntax](../functions/index#man-vectorized) `f.(args...)`, e.g. `sin.(x)` or `min.(x,y)`, for elementwise operations over arrays or mixtures of arrays and scalars (a [Broadcasting](#Broadcasting) operation); these have the additional advantage of "fusing" into a single loop when combined with other dot calls, e.g. `sin.(cos.(x))`.
Also, *every* binary operator supports a [dot version](../mathematical-operations/index#man-dot-operators) that can be applied to arrays (and combinations of arrays and scalars) in such [fused broadcasting operations](../functions/index#man-vectorized), e.g. `z .== sin.(x .* y)`.
Note that comparisons such as `==` operate on whole arrays, giving a single boolean answer. Use dot operators like `.==` for elementwise comparisons. (For comparison operations like `<`, *only* the elementwise `.<` version is applicable to arrays.)
Also notice the difference between `max.(a,b)`, which [`broadcast`](../../base/arrays/index#Base.Broadcast.broadcast)s [`max`](../../base/math/index#Base.max) elementwise over `a` and `b`, and [`maximum(a)`](../../base/collections/index#Base.maximum), which finds the largest value within `a`. The same relationship holds for `min.(a,b)` and `minimum(a)`.
[Broadcasting](#Broadcasting)
------------------------------
It is sometimes useful to perform element-by-element binary operations on arrays of different sizes, such as adding a vector to each column of a matrix. An inefficient way to do this would be to replicate the vector to the size of the matrix:
```
julia> a = rand(2,1); A = rand(2,3);
julia> repeat(a,1,3)+A
2×3 Array{Float64,2}:
1.20813 1.82068 1.25387
1.56851 1.86401 1.67846
```
This is wasteful when dimensions get large, so Julia provides [`broadcast`](../../base/arrays/index#Base.Broadcast.broadcast), which expands singleton dimensions in array arguments to match the corresponding dimension in the other array without using extra memory, and applies the given function elementwise:
```
julia> broadcast(+, a, A)
2×3 Array{Float64,2}:
1.20813 1.82068 1.25387
1.56851 1.86401 1.67846
julia> b = rand(1,2)
1×2 Array{Float64,2}:
0.867535 0.00457906
julia> broadcast(+, a, b)
2×2 Array{Float64,2}:
1.71056 0.847604
1.73659 0.873631
```
[Dotted operators](../mathematical-operations/index#man-dot-operators) such as `.+` and `.*` are equivalent to `broadcast` calls (except that they fuse, as [described above](#man-array-and-vectorized-operators-and-functions)). There is also a [`broadcast!`](../../base/arrays/index#Base.Broadcast.broadcast!) function to specify an explicit destination (which can also be accessed in a fusing fashion by `.=` assignment). In fact, `f.(args...)` is equivalent to `broadcast(f, args...)`, providing a convenient syntax to broadcast any function ([dot syntax](../functions/index#man-vectorized)). Nested "dot calls" `f.(...)` (including calls to `.+` etcetera) [automatically fuse](../mathematical-operations/index#man-dot-operators) into a single `broadcast` call.
Additionally, [`broadcast`](../../base/arrays/index#Base.Broadcast.broadcast) is not limited to arrays (see the function documentation); it also handles scalars, tuples and other collections. By default, only some argument types are considered scalars, including (but not limited to) `Number`s, `String`s, `Symbol`s, `Type`s, `Function`s and some common singletons like `missing` and `nothing`. All other arguments are iterated over or indexed into elementwise.
```
julia> convert.(Float32, [1, 2])
2-element Vector{Float32}:
1.0
2.0
julia> ceil.(UInt8, [1.2 3.4; 5.6 6.7])
2×2 Matrix{UInt8}:
0x02 0x04
0x06 0x07
julia> string.(1:3, ". ", ["First", "Second", "Third"])
3-element Vector{String}:
"1. First"
"2. Second"
"3. Third"
```
Sometimes, you want a container (like an array) that would normally participate in broadcast to be "protected" from broadcast's behavior of iterating over all of its elements. By placing it inside another container (like a single element [`Tuple`](../../base/base/index#Core.Tuple)) broadcast will treat it as a single value.
```
julia> ([1, 2, 3], [4, 5, 6]) .+ ([1, 2, 3],)
([2, 4, 6], [5, 7, 9])
julia> ([1, 2, 3], [4, 5, 6]) .+ tuple([1, 2, 3])
([2, 4, 6], [5, 7, 9])
```
[Implementation](#Implementation)
----------------------------------
The base array type in Julia is the abstract type [`AbstractArray{T,N}`](../../base/arrays/index#Core.AbstractArray). It is parameterized by the number of dimensions `N` and the element type `T`. [`AbstractVector`](../../base/arrays/index#Base.AbstractVector) and [`AbstractMatrix`](../../base/arrays/index#Base.AbstractMatrix) are aliases for the 1-d and 2-d cases. Operations on `AbstractArray` objects are defined using higher level operators and functions, in a way that is independent of the underlying storage. These operations generally work correctly as a fallback for any specific array implementation.
The `AbstractArray` type includes anything vaguely array-like, and implementations of it might be quite different from conventional arrays. For example, elements might be computed on request rather than stored. However, any concrete `AbstractArray{T,N}` type should generally implement at least [`size(A)`](../../base/arrays/index#Base.size) (returning an `Int` tuple), [`getindex(A,i)`](#) and [`getindex(A,i1,...,iN)`](../../base/collections/index#Base.getindex); mutable arrays should also implement [`setindex!`](../../base/collections/index#Base.setindex!). It is recommended that these operations have nearly constant time complexity, as otherwise some array functions may be unexpectedly slow. Concrete types should also typically provide a [`similar(A,T=eltype(A),dims=size(A))`](../../base/arrays/index#Base.similar) method, which is used to allocate a similar array for [`copy`](../../base/base/index#Base.copy) and other out-of-place operations. No matter how an `AbstractArray{T,N}` is represented internally, `T` is the type of object returned by *integer* indexing (`A[1, ..., 1]`, when `A` is not empty) and `N` should be the length of the tuple returned by [`size`](../../base/arrays/index#Base.size). For more details on defining custom `AbstractArray` implementations, see the [array interface guide in the interfaces chapter](../interfaces/index#man-interface-array).
`DenseArray` is an abstract subtype of `AbstractArray` intended to include all arrays where elements are stored contiguously in column-major order (see [additional notes in Performance Tips](../performance-tips/index#man-performance-column-major)). The [`Array`](../../base/arrays/index#Core.Array) type is a specific instance of `DenseArray`; [`Vector`](../../base/arrays/index#Base.Vector) and [`Matrix`](../../base/arrays/index#Base.Matrix) are aliases for the 1-d and 2-d cases. Very few operations are implemented specifically for `Array` beyond those that are required for all `AbstractArray`s; much of the array library is implemented in a generic manner that allows all custom arrays to behave similarly.
`SubArray` is a specialization of `AbstractArray` that performs indexing by sharing memory with the original array rather than by copying it. A `SubArray` is created with the [`view`](../../base/arrays/index#Base.view) function, which is called the same way as [`getindex`](../../base/collections/index#Base.getindex) (with an array and a series of index arguments). The result of [`view`](../../base/arrays/index#Base.view) looks the same as the result of [`getindex`](../../base/collections/index#Base.getindex), except the data is left in place. [`view`](../../base/arrays/index#Base.view) stores the input index vectors in a `SubArray` object, which can later be used to index the original array indirectly. By putting the [`@views`](../../base/arrays/index#Base.@views) macro in front of an expression or block of code, any `array[...]` slice in that expression will be converted to create a `SubArray` view instead.
[`BitArray`](../../base/arrays/index#Base.BitArray)s are space-efficient "packed" boolean arrays, which store one bit per boolean value. They can be used similarly to `Array{Bool}` arrays (which store one byte per boolean value), and can be converted to/from the latter via `Array(bitarray)` and `BitArray(array)`, respectively.
An array is "strided" if it is stored in memory with well-defined spacings (strides) between its elements. A strided array with a supported element type may be passed to an external (non-Julia) library like BLAS or LAPACK by simply passing its [`pointer`](../../base/c/index#Base.pointer) and the stride for each dimension. The [`stride(A, d)`](../../base/arrays/index#Base.stride) is the distance between elements along dimension `d`. For example, the builtin `Array` returned by `rand(5,7,2)` has its elements arranged contiguously in column major order. This means that the stride of the first dimension — the spacing between elements in the same column — is `1`:
```
julia> A = rand(5,7,2);
julia> stride(A,1)
1
```
The stride of the second dimension is the spacing between elements in the same row, skipping as many elements as there are in a single column (`5`). Similarly, jumping between the two "pages" (in the third dimension) requires skipping `5*7 == 35` elements. The [`strides`](../../base/arrays/index#Base.strides) of this array is the tuple of these three numbers together:
```
julia> strides(A)
(1, 5, 35)
```
In this particular case, the number of elements skipped *in memory* matches the number of *linear indices* skipped. This is only the case for contiguous arrays like `Array` (and other `DenseArray` subtypes) and is not true in general. Views with range indices are a good example of *non-contiguous* strided arrays; consider `V = @view A[1:3:4, 2:2:6, 2:-1:1]`. This view `V` refers to the same memory as `A` but is skipping and re-arranging some of its elements. The stride of the first dimension of `V` is `3` because we're only selecting every third row from our original array:
```
julia> V = @view A[1:3:4, 2:2:6, 2:-1:1];
julia> stride(V, 1)
3
```
This view is similarly selecting every other column from our original `A` — and thus it needs to skip the equivalent of two five-element columns when moving between indices in the second dimension:
```
julia> stride(V, 2)
10
```
The third dimension is interesting because its order is reversed! Thus to get from the first "page" to the second one it must go *backwards* in memory, and so its stride in this dimension is negative!
```
julia> stride(V, 3)
-35
```
This means that the `pointer` for `V` is actually pointing into the middle of `A`'s memory block, and it refers to elements both backwards and forwards in memory. See the [interface guide for strided arrays](../interfaces/index#man-interface-strided-arrays) for more details on defining your own strided arrays. [`StridedVector`](../../base/arrays/index#Base.StridedVector) and [`StridedMatrix`](../../base/arrays/index#Base.StridedMatrix) are convenient aliases for many of the builtin array types that are considered strided arrays, allowing them to dispatch to select specialized implementations that call highly tuned and optimized BLAS and LAPACK functions using just the pointer and strides.
It is worth emphasizing that strides are about offsets in memory rather than indexing. If you are looking to convert between linear (single-index) indexing and cartesian (multi-index) indexing, see [`LinearIndices`](../../base/arrays/index#Base.LinearIndices) and [`CartesianIndices`](../../base/arrays/index#Base.IteratorsMD.CartesianIndices).
* [1](#citeref-1)*iid*, independently and identically distributed.
| programming_docs |
julia Control Flow Control Flow
============
Julia provides a variety of control flow constructs:
* [Compound Expressions](#man-compound-expressions): `begin` and `;`.
* [Conditional Evaluation](#man-conditional-evaluation): `if`-`elseif`-`else` and `?:` (ternary operator).
* [Short-Circuit Evaluation](#Short-Circuit-Evaluation): logical operators `&&` (“and”) and `||` (“or”), and also chained comparisons.
* [Repeated Evaluation: Loops](#man-loops): `while` and `for`.
* [Exception Handling](#Exception-Handling): `try`-`catch`, [`error`](../../base/base/index#Base.error) and [`throw`](../../base/base/index#Core.throw).
* [Tasks (aka Coroutines)](#man-tasks): [`yieldto`](../../base/parallel/index#Base.yieldto).
The first five control flow mechanisms are standard to high-level programming languages. [`Task`](../../base/parallel/index#Core.Task)s are not so standard: they provide non-local control flow, making it possible to switch between temporarily-suspended computations. This is a powerful construct: both exception handling and cooperative multitasking are implemented in Julia using tasks. Everyday programming requires no direct usage of tasks, but certain problems can be solved much more easily by using tasks.
[Compound Expressions](#man-compound-expressions)
--------------------------------------------------
Sometimes it is convenient to have a single expression which evaluates several subexpressions in order, returning the value of the last subexpression as its value. There are two Julia constructs that accomplish this: `begin` blocks and `;` chains. The value of both compound expression constructs is that of the last subexpression. Here's an example of a `begin` block:
```
julia> z = begin
x = 1
y = 2
x + y
end
3
```
Since these are fairly small, simple expressions, they could easily be placed onto a single line, which is where the `;` chain syntax comes in handy:
```
julia> z = (x = 1; y = 2; x + y)
3
```
This syntax is particularly useful with the terse single-line function definition form introduced in [Functions](../functions/index#man-functions). Although it is typical, there is no requirement that `begin` blocks be multiline or that `;` chains be single-line:
```
julia> begin x = 1; y = 2; x + y end
3
julia> (x = 1;
y = 2;
x + y)
3
```
[Conditional Evaluation](#man-conditional-evaluation)
------------------------------------------------------
Conditional evaluation allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the `if`-`elseif`-`else` conditional syntax:
```
if x < y
println("x is less than y")
elseif x > y
println("x is greater than y")
else
println("x is equal to y")
end
```
If the condition expression `x < y` is `true`, then the corresponding block is evaluated; otherwise the condition expression `x > y` is evaluated, and if it is `true`, the corresponding block is evaluated; if neither expression is true, the `else` block is evaluated. Here it is in action:
```
julia> function test(x, y)
if x < y
println("x is less than y")
elseif x > y
println("x is greater than y")
else
println("x is equal to y")
end
end
test (generic function with 1 method)
julia> test(1, 2)
x is less than y
julia> test(2, 1)
x is greater than y
julia> test(1, 1)
x is equal to y
```
The `elseif` and `else` blocks are optional, and as many `elseif` blocks as desired can be used. The condition expressions in the `if`-`elseif`-`else` construct are evaluated until the first one evaluates to `true`, after which the associated block is evaluated, and no further condition expressions or blocks are evaluated.
`if` blocks are "leaky", i.e. they do not introduce a local scope. This means that new variables defined inside the `if` clauses can be used after the `if` block, even if they weren't defined before. So, we could have defined the `test` function above as
```
julia> function test(x,y)
if x < y
relation = "less than"
elseif x == y
relation = "equal to"
else
relation = "greater than"
end
println("x is ", relation, " y.")
end
test (generic function with 1 method)
julia> test(2, 1)
x is greater than y.
```
The variable `relation` is declared inside the `if` block, but used outside. However, when depending on this behavior, make sure all possible code paths define a value for the variable. The following change to the above function results in a runtime error
```
julia> function test(x,y)
if x < y
relation = "less than"
elseif x == y
relation = "equal to"
end
println("x is ", relation, " y.")
end
test (generic function with 1 method)
julia> test(1,2)
x is less than y.
julia> test(2,1)
ERROR: UndefVarError: relation not defined
Stacktrace:
[1] test(::Int64, ::Int64) at ./none:7
```
`if` blocks also return a value, which may seem unintuitive to users coming from many other languages. This value is simply the return value of the last executed statement in the branch that was chosen, so
```
julia> x = 3
3
julia> if x > 0
"positive!"
else
"negative..."
end
"positive!"
```
Note that very short conditional statements (one-liners) are frequently expressed using Short-Circuit Evaluation in Julia, as outlined in the next section.
Unlike C, MATLAB, Perl, Python, and Ruby – but like Java, and a few other stricter, typed languages – it is an error if the value of a conditional expression is anything but `true` or `false`:
```
julia> if 1
println("true")
end
ERROR: TypeError: non-boolean (Int64) used in boolean context
```
This error indicates that the conditional was of the wrong type: [`Int64`](../../base/numbers/index#Core.Int64) rather than the required [`Bool`](../../base/numbers/index#Core.Bool).
The so-called "ternary operator", `?:`, is closely related to the `if`-`elseif`-`else` syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:
```
a ? b : c
```
The expression `a`, before the `?`, is a condition expression, and the ternary operation evaluates the expression `b`, before the `:`, if the condition `a` is `true` or the expression `c`, after the `:`, if it is `false`. Note that the spaces around `?` and `:` are mandatory: an expression like `a?b:c` is not a valid ternary expression (but a newline is acceptable after both the `?` and the `:`).
The easiest way to understand this behavior is to see an example. In the previous example, the `println` call is shared by all three branches: the only real choice is which literal string to print. This could be written more concisely using the ternary operator. For the sake of clarity, let's try a two-way version first:
```
julia> x = 1; y = 2;
julia> println(x < y ? "less than" : "not less than")
less than
julia> x = 1; y = 0;
julia> println(x < y ? "less than" : "not less than")
not less than
```
If the expression `x < y` is true, the entire ternary operator expression evaluates to the string `"less than"` and otherwise it evaluates to the string `"not less than"`. The original three-way example requires chaining multiple uses of the ternary operator together:
```
julia> test(x, y) = println(x < y ? "x is less than y" :
x > y ? "x is greater than y" : "x is equal to y")
test (generic function with 1 method)
julia> test(1, 2)
x is less than y
julia> test(2, 1)
x is greater than y
julia> test(1, 1)
x is equal to y
```
To facilitate chaining, the operator associates from right to left.
It is significant that like `if`-`elseif`-`else`, the expressions before and after the `:` are only evaluated if the condition expression evaluates to `true` or `false`, respectively:
```
julia> v(x) = (println(x); x)
v (generic function with 1 method)
julia> 1 < 2 ? v("yes") : v("no")
yes
"yes"
julia> 1 > 2 ? v("yes") : v("no")
no
"no"
```
[Short-Circuit Evaluation](#Short-Circuit-Evaluation)
------------------------------------------------------
The `&&` and `||` operators in Julia correspond to logical “and” and “or” operations, respectively, and are typically used for this purpose. However, they have an additional property of *short-circuit* evaluation: they don't necessarily evaluate their second argument, as explained below. (There are also bitwise `&` and `|` operators that can be used as logical “and” and “or” *without* short-circuit behavior, but beware that `&` and `|` have higher precedence than `&&` and `||` for evaluation order.)
Short-circuit evaluation is quite similar to conditional evaluation. The behavior is found in most imperative programming languages having the `&&` and `||` boolean operators: in a series of boolean expressions connected by these operators, only the minimum number of expressions are evaluated as are necessary to determine the final boolean value of the entire chain. Some languages (like Python) refer to them as `and` (`&&`) and `or` (`||`). Explicitly, this means that:
* In the expression `a && b`, the subexpression `b` is only evaluated if `a` evaluates to `true`.
* In the expression `a || b`, the subexpression `b` is only evaluated if `a` evaluates to `false`.
The reasoning is that `a && b` must be `false` if `a` is `false`, regardless of the value of `b`, and likewise, the value of `a || b` must be true if `a` is `true`, regardless of the value of `b`. Both `&&` and `||` associate to the right, but `&&` has higher precedence than `||` does. It's easy to experiment with this behavior:
```
julia> t(x) = (println(x); true)
t (generic function with 1 method)
julia> f(x) = (println(x); false)
f (generic function with 1 method)
julia> t(1) && t(2)
1
2
true
julia> t(1) && f(2)
1
2
false
julia> f(1) && t(2)
1
false
julia> f(1) && f(2)
1
false
julia> t(1) || t(2)
1
true
julia> t(1) || f(2)
1
true
julia> f(1) || t(2)
1
2
true
julia> f(1) || f(2)
1
2
false
```
You can easily experiment in the same way with the associativity and precedence of various combinations of `&&` and `||` operators.
This behavior is frequently used in Julia to form an alternative to very short `if` statements. Instead of `if <cond> <statement> end`, one can write `<cond> && <statement>` (which could be read as: <cond> *and then* <statement>). Similarly, instead of `if ! <cond> <statement> end`, one can write `<cond> || <statement>` (which could be read as: <cond> *or else* <statement>).
For example, a recursive factorial routine could be defined like this:
```
julia> function fact(n::Int)
n >= 0 || error("n must be non-negative")
n == 0 && return 1
n * fact(n-1)
end
fact (generic function with 1 method)
julia> fact(5)
120
julia> fact(0)
1
julia> fact(-1)
ERROR: n must be non-negative
Stacktrace:
[1] error at ./error.jl:33 [inlined]
[2] fact(::Int64) at ./none:2
[3] top-level scope
```
Boolean operations *without* short-circuit evaluation can be done with the bitwise boolean operators introduced in [Mathematical Operations and Elementary Functions](../mathematical-operations/index#Mathematical-Operations-and-Elementary-Functions): `&` and `|`. These are normal functions, which happen to support infix operator syntax, but always evaluate their arguments:
```
julia> f(1) & t(2)
1
2
false
julia> t(1) | t(2)
1
2
true
```
Just like condition expressions used in `if`, `elseif` or the ternary operator, the operands of `&&` or `||` must be boolean values (`true` or `false`). Using a non-boolean value anywhere except for the last entry in a conditional chain is an error:
```
julia> 1 && true
ERROR: TypeError: non-boolean (Int64) used in boolean context
```
On the other hand, any type of expression can be used at the end of a conditional chain. It will be evaluated and returned depending on the preceding conditionals:
```
julia> true && (x = (1, 2, 3))
(1, 2, 3)
julia> false && (x = (1, 2, 3))
false
```
[Repeated Evaluation: Loops](#man-loops)
-----------------------------------------
There are two constructs for repeated evaluation of expressions: the `while` loop and the `for` loop. Here is an example of a `while` loop:
```
julia> i = 1;
julia> while i <= 5
println(i)
global i += 1
end
1
2
3
4
5
```
The `while` loop evaluates the condition expression (`i <= 5` in this case), and as long it remains `true`, keeps also evaluating the body of the `while` loop. If the condition expression is `false` when the `while` loop is first reached, the body is never evaluated.
The `for` loop makes common repeated evaluation idioms easier to write. Since counting up and down like the above `while` loop does is so common, it can be expressed more concisely with a `for` loop:
```
julia> for i = 1:5
println(i)
end
1
2
3
4
5
```
Here the `1:5` is a range object, representing the sequence of numbers 1, 2, 3, 4, 5. The `for` loop iterates through these values, assigning each one in turn to the variable `i`. One rather important distinction between the previous `while` loop form and the `for` loop form is the scope during which the variable is visible. If the variable `i` has not been introduced in another scope, in the `for` loop form, it is visible only inside of the `for` loop, and not outside/afterwards. You'll either need a new interactive session instance or a different variable name to test this:
```
julia> for j = 1:5
println(j)
end
1
2
3
4
5
julia> j
ERROR: UndefVarError: j not defined
```
See [Scope of Variables](../variables-and-scoping/index#scope-of-variables) for a detailed explanation of variable scope and how it works in Julia.
In general, the `for` loop construct can iterate over any container. In these cases, the alternative (but fully equivalent) keyword `in` or `∈` is typically used instead of `=`, since it makes the code read more clearly:
```
julia> for i in [1,4,0]
println(i)
end
1
4
0
julia> for s ∈ ["foo","bar","baz"]
println(s)
end
foo
bar
baz
```
Various types of iterable containers will be introduced and discussed in later sections of the manual (see, e.g., [Multi-dimensional Arrays](../arrays/index#man-multi-dim-arrays)).
It is sometimes convenient to terminate the repetition of a `while` before the test condition is falsified or stop iterating in a `for` loop before the end of the iterable object is reached. This can be accomplished with the `break` keyword:
```
julia> i = 1;
julia> while true
println(i)
if i >= 5
break
end
global i += 1
end
1
2
3
4
5
julia> for j = 1:1000
println(j)
if j >= 5
break
end
end
1
2
3
4
5
```
Without the `break` keyword, the above `while` loop would never terminate on its own, and the `for` loop would iterate up to 1000. These loops are both exited early by using `break`.
In other circumstances, it is handy to be able to stop an iteration and move on to the next one immediately. The `continue` keyword accomplishes this:
```
julia> for i = 1:10
if i % 3 != 0
continue
end
println(i)
end
3
6
9
```
This is a somewhat contrived example since we could produce the same behavior more clearly by negating the condition and placing the `println` call inside the `if` block. In realistic usage there is more code to be evaluated after the `continue`, and often there are multiple points from which one calls `continue`.
Multiple nested `for` loops can be combined into a single outer loop, forming the cartesian product of its iterables:
```
julia> for i = 1:2, j = 3:4
println((i, j))
end
(1, 3)
(1, 4)
(2, 3)
(2, 4)
```
With this syntax, iterables may still refer to outer loop variables; e.g. `for i = 1:n, j = 1:i` is valid. However a `break` statement inside such a loop exits the entire nest of loops, not just the inner one. Both variables (`i` and `j`) are set to their current iteration values each time the inner loop runs. Therefore, assignments to `i` will not be visible to subsequent iterations:
```
julia> for i = 1:2, j = 3:4
println((i, j))
i = 0
end
(1, 3)
(1, 4)
(2, 3)
(2, 4)
```
If this example were rewritten to use a `for` keyword for each variable, then the output would be different: the second and fourth values would contain `0`.
Multiple containers can be iterated over at the same time in a single `for` loop using [`zip`](../../base/iterators/index#Base.Iterators.zip):
```
julia> for (j, k) in zip([1 2 3], [4 5 6 7])
println((j,k))
end
(1, 4)
(2, 5)
(3, 6)
```
Using [`zip`](../../base/iterators/index#Base.Iterators.zip) will create an iterator that is a tuple containing the subiterators for the containers passed to it. The `zip` iterator will iterate over all subiterators in order, choosing the $i$th element of each subiterator in the $i$th iteration of the `for` loop. Once any of the subiterators run out, the `for` loop will stop.
[Exception Handling](#Exception-Handling)
------------------------------------------
When an unexpected condition occurs, a function may be unable to return a reasonable value to its caller. In such cases, it may be best for the exceptional condition to either terminate the program while printing a diagnostic error message, or if the programmer has provided code to handle such exceptional circumstances then allow that code to take the appropriate action.
###
[Built-in `Exception`s](#Built-in-Exceptions)
`Exception`s are thrown when an unexpected condition has occurred. The built-in `Exception`s listed below all interrupt the normal flow of control.
| `Exception` |
| --- |
| [`ArgumentError`](../../base/base/index#Core.ArgumentError) |
| [`BoundsError`](../../base/base/index#Core.BoundsError) |
| [`CompositeException`](../../base/base/index#Base.CompositeException) |
| [`DimensionMismatch`](../../base/base/index#Base.DimensionMismatch) |
| [`DivideError`](../../base/base/index#Core.DivideError) |
| [`DomainError`](../../base/base/index#Core.DomainError) |
| [`EOFError`](../../base/base/index#Base.EOFError) |
| [`ErrorException`](../../base/base/index#Core.ErrorException) |
| [`InexactError`](../../base/base/index#Core.InexactError) |
| [`InitError`](../../base/base/index#Core.InitError) |
| [`InterruptException`](../../base/base/index#Core.InterruptException) |
| `InvalidStateException` |
| [`KeyError`](../../base/base/index#Base.KeyError) |
| [`LoadError`](../../base/base/index#Core.LoadError) |
| [`OutOfMemoryError`](../../base/base/index#Core.OutOfMemoryError) |
| [`ReadOnlyMemoryError`](../../base/base/index#Core.ReadOnlyMemoryError) |
| [`RemoteException`](../../stdlib/distributed/index#Distributed.RemoteException) |
| [`MethodError`](../../base/base/index#Core.MethodError) |
| [`OverflowError`](../../base/base/index#Core.OverflowError) |
| [`Meta.ParseError`](../../base/base/index#Base.Meta.ParseError) |
| [`SystemError`](../../base/base/index#Base.SystemError) |
| [`TypeError`](../../base/base/index#Core.TypeError) |
| [`UndefRefError`](../../base/base/index#Core.UndefRefError) |
| [`UndefVarError`](../../base/base/index#Core.UndefVarError) |
| [`StringIndexError`](../../base/base/index#Base.StringIndexError) |
For example, the [`sqrt`](#) function throws a [`DomainError`](../../base/base/index#Core.DomainError) if applied to a negative real value:
```
julia> sqrt(-1)
ERROR: DomainError with -1.0:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
```
You may define your own exceptions in the following way:
```
julia> struct MyCustomException <: Exception end
```
###
[The](#The-%5Bthrow%5D(@ref)-function) [`throw`](../../base/base/index#Core.throw) function
Exceptions can be created explicitly with [`throw`](../../base/base/index#Core.throw). For example, a function defined only for nonnegative numbers could be written to [`throw`](../../base/base/index#Core.throw) a [`DomainError`](../../base/base/index#Core.DomainError) if the argument is negative:
```
julia> f(x) = x>=0 ? exp(-x) : throw(DomainError(x, "argument must be nonnegative"))
f (generic function with 1 method)
julia> f(1)
0.36787944117144233
julia> f(-1)
ERROR: DomainError with -1:
argument must be nonnegative
Stacktrace:
[1] f(::Int64) at ./none:1
```
Note that [`DomainError`](../../base/base/index#Core.DomainError) without parentheses is not an exception, but a type of exception. It needs to be called to obtain an `Exception` object:
```
julia> typeof(DomainError(nothing)) <: Exception
true
julia> typeof(DomainError) <: Exception
false
```
Additionally, some exception types take one or more arguments that are used for error reporting:
```
julia> throw(UndefVarError(:x))
ERROR: UndefVarError: x not defined
```
This mechanism can be implemented easily by custom exception types following the way [`UndefVarError`](../../base/base/index#Core.UndefVarError) is written:
```
julia> struct MyUndefVarError <: Exception
var::Symbol
end
julia> Base.showerror(io::IO, e::MyUndefVarError) = print(io, e.var, " not defined")
```
When writing an error message, it is preferred to make the first word lowercase. For example,
`size(A) == size(B) || throw(DimensionMismatch("size of A not equal to size of B"))`
is preferred over
`size(A) == size(B) || throw(DimensionMismatch("Size of A not equal to size of B"))`.
However, sometimes it makes sense to keep the uppercase first letter, for instance if an argument to a function is a capital letter:
`size(A,1) == size(B,2) || throw(DimensionMismatch("A has first dimension..."))`.
###
[Errors](#Errors)
The [`error`](../../base/base/index#Base.error) function is used to produce an [`ErrorException`](../../base/base/index#Core.ErrorException) that interrupts the normal flow of control.
Suppose we want to stop execution immediately if the square root of a negative number is taken. To do this, we can define a fussy version of the [`sqrt`](#) function that raises an error if its argument is negative:
```
julia> fussy_sqrt(x) = x >= 0 ? sqrt(x) : error("negative x not allowed")
fussy_sqrt (generic function with 1 method)
julia> fussy_sqrt(2)
1.4142135623730951
julia> fussy_sqrt(-1)
ERROR: negative x not allowed
Stacktrace:
[1] error at ./error.jl:33 [inlined]
[2] fussy_sqrt(::Int64) at ./none:1
[3] top-level scope
```
If `fussy_sqrt` is called with a negative value from another function, instead of trying to continue execution of the calling function, it returns immediately, displaying the error message in the interactive session:
```
julia> function verbose_fussy_sqrt(x)
println("before fussy_sqrt")
r = fussy_sqrt(x)
println("after fussy_sqrt")
return r
end
verbose_fussy_sqrt (generic function with 1 method)
julia> verbose_fussy_sqrt(2)
before fussy_sqrt
after fussy_sqrt
1.4142135623730951
julia> verbose_fussy_sqrt(-1)
before fussy_sqrt
ERROR: negative x not allowed
Stacktrace:
[1] error at ./error.jl:33 [inlined]
[2] fussy_sqrt at ./none:1 [inlined]
[3] verbose_fussy_sqrt(::Int64) at ./none:3
[4] top-level scope
```
###
[The `try/catch` statement](#The-try/catch-statement)
The `try/catch` statement allows for `Exception`s to be tested for, and for the graceful handling of things that may ordinarily break your application. For example, in the below code the function for square root would normally throw an exception. By placing a `try/catch` block around it we can mitigate that here. You may choose how you wish to handle this exception, whether logging it, return a placeholder value or as in the case below where we just printed out a statement. One thing to think about when deciding how to handle unexpected situations is that using a `try/catch` block is much slower than using conditional branching to handle those situations. Below there are more examples of handling exceptions with a `try/catch` block:
```
julia> try
sqrt("ten")
catch e
println("You should have entered a numeric value")
end
You should have entered a numeric value
```
`try/catch` statements also allow the `Exception` to be saved in a variable. The following contrived example calculates the square root of the second element of `x` if `x` is indexable, otherwise assumes `x` is a real number and returns its square root:
```
julia> sqrt_second(x) = try
sqrt(x[2])
catch y
if isa(y, DomainError)
sqrt(complex(x[2], 0))
elseif isa(y, BoundsError)
sqrt(x)
end
end
sqrt_second (generic function with 1 method)
julia> sqrt_second([1 4])
2.0
julia> sqrt_second([1 -4])
0.0 + 2.0im
julia> sqrt_second(9)
3.0
julia> sqrt_second(-9)
ERROR: DomainError with -9.0:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
```
Note that the symbol following `catch` will always be interpreted as a name for the exception, so care is needed when writing `try/catch` expressions on a single line. The following code will *not* work to return the value of `x` in case of an error:
```
try bad() catch x end
```
Instead, use a semicolon or insert a line break after `catch`:
```
try bad() catch; x end
try bad()
catch
x
end
```
The power of the `try/catch` construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions. There are situations where no error has occurred, but the ability to unwind the stack and pass a value to a higher level is desirable. Julia provides the [`rethrow`](../../base/base/index#Base.rethrow), [`backtrace`](../../base/base/index#Base.backtrace), [`catch_backtrace`](../../base/base/index#Base.catch_backtrace) and [`current_exceptions`](../../base/base/index#Base.current_exceptions) functions for more advanced error handling.
###
[`finally` Clauses](#finally-Clauses)
In code that performs state changes or uses resources like files, there is typically clean-up work (such as closing files) that needs to be done when the code is finished. Exceptions potentially complicate this task, since they can cause a block of code to exit before reaching its normal end. The `finally` keyword provides a way to run some code when a given block of code exits, regardless of how it exits.
For example, here is how we can guarantee that an opened file is closed:
```
f = open("file")
try
# operate on file f
finally
close(f)
end
```
When control leaves the `try` block (for example due to a `return`, or just finishing normally), `close(f)` will be executed. If the `try` block exits due to an exception, the exception will continue propagating. A `catch` block may be combined with `try` and `finally` as well. In this case the `finally` block will run after `catch` has handled the error.
[Tasks (aka Coroutines)](#man-tasks)
-------------------------------------
Tasks are a control flow feature that allows computations to be suspended and resumed in a flexible manner. We mention them here only for completeness; for a full discussion see [Asynchronous Programming](../asynchronous-programming/index#man-asynchronous).
| programming_docs |
julia Running External Programs Running External Programs
=========================
Julia borrows backtick notation for commands from the shell, Perl, and Ruby. However, in Julia, writing
```
julia> `echo hello`
`echo hello`
```
differs in several aspects from the behavior in various shells, Perl, or Ruby:
* Instead of immediately running the command, backticks create a [`Cmd`](../../base/base/index#Base.Cmd) object to represent the command. You can use this object to connect the command to others via pipes, [`run`](../../base/base/index#Base.run) it, and [`read`](../../base/io-network/index#Base.read) or [`write`](../../base/io-network/index#Base.write) to it.
* When the command is run, Julia does not capture its output unless you specifically arrange for it to. Instead, the output of the command by default goes to [`stdout`](../../base/io-network/index#Base.stdout) as it would using `libc`'s `system` call.
* The command is never run with a shell. Instead, Julia parses the command syntax directly, appropriately interpolating variables and splitting on words as the shell would, respecting shell quoting syntax. The command is run as `julia`'s immediate child process, using `fork` and `exec` calls.
The following assumes a Posix environment as on Linux or MacOS. On Windows, many similar commands, such as `echo` and `dir`, are not external programs and instead are built into the shell `cmd.exe` itself. One option to run these commands is to invoke `cmd.exe`, for example `cmd /C echo hello`. Alternatively Julia can be run inside a Posix environment such as Cygwin.
Here's a simple example of running an external program:
```
julia> mycommand = `echo hello`
`echo hello`
julia> typeof(mycommand)
Cmd
julia> run(mycommand);
hello
```
The `hello` is the output of the `echo` command, sent to [`stdout`](../../base/io-network/index#Base.stdout). If the external command fails to run successfully, the run method throws an [`ErrorException`](../../base/base/index#Core.ErrorException).
If you want to read the output of the external command, [`read`](../../base/io-network/index#Base.read) or [`readchomp`](../../base/io-network/index#Base.readchomp) can be used instead:
```
julia> read(`echo hello`, String)
"hello\n"
julia> readchomp(`echo hello`)
"hello"
```
More generally, you can use [`open`](../../base/io-network/index#Base.open) to read from or write to an external command.
```
julia> open(`less`, "w", stdout) do io
for i = 1:3
println(io, i)
end
end
1
2
3
```
The program name and the individual arguments in a command can be accessed and iterated over as if the command were an array of strings:
```
julia> collect(`echo "foo bar"`)
2-element Vector{String}:
"echo"
"foo bar"
julia> `echo "foo bar"`[2]
"foo bar"
```
[Interpolation](#command-interpolation)
----------------------------------------
Suppose you want to do something a bit more complicated and use the name of a file in the variable `file` as an argument to a command. You can use `$` for interpolation much as you would in a string literal (see [Strings](https://docs.julialang.org/en/v1.8/devdocs/ast/#Strings)):
```
julia> file = "/etc/passwd"
"/etc/passwd"
julia> `sort $file`
`sort /etc/passwd`
```
A common pitfall when running external programs via a shell is that if a file name contains characters that are special to the shell, they may cause undesirable behavior. Suppose, for example, rather than `/etc/passwd`, we wanted to sort the contents of the file `/Volumes/External HD/data.csv`. Let's try it:
```
julia> file = "/Volumes/External HD/data.csv"
"/Volumes/External HD/data.csv"
julia> `sort $file`
`sort '/Volumes/External HD/data.csv'`
```
How did the file name get quoted? Julia knows that `file` is meant to be interpolated as a single argument, so it quotes the word for you. Actually, that is not quite accurate: the value of `file` is never interpreted by a shell, so there's no need for actual quoting; the quotes are inserted only for presentation to the user. This will even work if you interpolate a value as part of a shell word:
```
julia> path = "/Volumes/External HD"
"/Volumes/External HD"
julia> name = "data"
"data"
julia> ext = "csv"
"csv"
julia> `sort $path/$name.$ext`
`sort '/Volumes/External HD/data.csv'`
```
As you can see, the space in the `path` variable is appropriately escaped. But what if you *want* to interpolate multiple words? In that case, just use an array (or any other iterable container):
```
julia> files = ["/etc/passwd","/Volumes/External HD/data.csv"]
2-element Vector{String}:
"/etc/passwd"
"/Volumes/External HD/data.csv"
julia> `grep foo $files`
`grep foo /etc/passwd '/Volumes/External HD/data.csv'`
```
If you interpolate an array as part of a shell word, Julia emulates the shell's `{a,b,c}` argument generation:
```
julia> names = ["foo","bar","baz"]
3-element Vector{String}:
"foo"
"bar"
"baz"
julia> `grep xylophone $names.txt`
`grep xylophone foo.txt bar.txt baz.txt`
```
Moreover, if you interpolate multiple arrays into the same word, the shell's Cartesian product generation behavior is emulated:
```
julia> names = ["foo","bar","baz"]
3-element Vector{String}:
"foo"
"bar"
"baz"
julia> exts = ["aux","log"]
2-element Vector{String}:
"aux"
"log"
julia> `rm -f $names.$exts`
`rm -f foo.aux foo.log bar.aux bar.log baz.aux baz.log`
```
Since you can interpolate literal arrays, you can use this generative functionality without needing to create temporary array objects first:
```
julia> `rm -rf $["foo","bar","baz","qux"].$["aux","log","pdf"]`
`rm -rf foo.aux foo.log foo.pdf bar.aux bar.log bar.pdf baz.aux baz.log baz.pdf qux.aux qux.log qux.pdf`
```
[Quoting](#Quoting)
--------------------
Inevitably, one wants to write commands that aren't quite so simple, and it becomes necessary to use quotes. Here's a simple example of a Perl one-liner at a shell prompt:
```
sh$ perl -le '$|=1; for (0..3) { print }'
0
1
2
3
```
The Perl expression needs to be in single quotes for two reasons: so that spaces don't break the expression into multiple shell words, and so that uses of Perl variables like `$|` (yes, that's the name of a variable in Perl), don't cause interpolation. In other instances, you may want to use double quotes so that interpolation *does* occur:
```
sh$ first="A"
sh$ second="B"
sh$ perl -le '$|=1; print for @ARGV' "1: $first" "2: $second"
1: A
2: B
```
In general, the Julia backtick syntax is carefully designed so that you can just cut-and-paste shell commands as is into backticks and they will work: the escaping, quoting, and interpolation behaviors are the same as the shell's. The only difference is that the interpolation is integrated and aware of Julia's notion of what is a single string value, and what is a container for multiple values. Let's try the above two examples in Julia:
```
julia> A = `perl -le '$|=1; for (0..3) { print }'`
`perl -le '$|=1; for (0..3) { print }'`
julia> run(A);
0
1
2
3
julia> first = "A"; second = "B";
julia> B = `perl -le 'print for @ARGV' "1: $first" "2: $second"`
`perl -le 'print for @ARGV' '1: A' '2: B'`
julia> run(B);
1: A
2: B
```
The results are identical, and Julia's interpolation behavior mimics the shell's with some improvements due to the fact that Julia supports first-class iterable objects while most shells use strings split on spaces for this, which introduces ambiguities. When trying to port shell commands to Julia, try cut and pasting first. Since Julia shows commands to you before running them, you can easily and safely just examine its interpretation without doing any damage.
[Pipelines](#Pipelines)
------------------------
Shell metacharacters, such as `|`, `&`, and `>`, need to be quoted (or escaped) inside of Julia's backticks:
```
julia> run(`echo hello '|' sort`);
hello | sort
julia> run(`echo hello \| sort`);
hello | sort
```
This expression invokes the `echo` command with three words as arguments: `hello`, `|`, and `sort`. The result is that a single line is printed: `hello | sort`. How, then, does one construct a pipeline? Instead of using `'|'` inside of backticks, one uses [`pipeline`](#):
```
julia> run(pipeline(`echo hello`, `sort`));
hello
```
This pipes the output of the `echo` command to the `sort` command. Of course, this isn't terribly interesting since there's only one line to sort, but we can certainly do much more interesting things:
```
julia> run(pipeline(`cut -d: -f3 /etc/passwd`, `sort -n`, `tail -n5`))
210
211
212
213
214
```
This prints the highest five user IDs on a UNIX system. The `cut`, `sort` and `tail` commands are all spawned as immediate children of the current `julia` process, with no intervening shell process. Julia itself does the work to setup pipes and connect file descriptors that is normally done by the shell. Since Julia does this itself, it retains better control and can do some things that shells cannot.
Julia can run multiple commands in parallel:
```
julia> run(`echo hello` & `echo world`);
world
hello
```
The order of the output here is non-deterministic because the two `echo` processes are started nearly simultaneously, and race to make the first write to the [`stdout`](../../base/io-network/index#Base.stdout) descriptor they share with each other and the `julia` parent process. Julia lets you pipe the output from both of these processes to another program:
```
julia> run(pipeline(`echo world` & `echo hello`, `sort`));
hello
world
```
In terms of UNIX plumbing, what's happening here is that a single UNIX pipe object is created and written to by both `echo` processes, and the other end of the pipe is read from by the `sort` command.
IO redirection can be accomplished by passing keyword arguments `stdin`, `stdout`, and `stderr` to the `pipeline` function:
```
pipeline(`do_work`, stdout=pipeline(`sort`, "out.txt"), stderr="errs.txt")
```
###
[Avoiding Deadlock in Pipelines](#Avoiding-Deadlock-in-Pipelines)
When reading and writing to both ends of a pipeline from a single process, it is important to avoid forcing the kernel to buffer all of the data.
For example, when reading all of the output from a command, call `read(out, String)`, not `wait(process)`, since the former will actively consume all of the data written by the process, whereas the latter will attempt to store the data in the kernel's buffers while waiting for a reader to be connected.
Another common solution is to separate the reader and writer of the pipeline into separate [`Task`](../../base/parallel/index#Core.Task)s:
```
writer = @async write(process, "data")
reader = @async do_compute(read(process, String))
wait(writer)
fetch(reader)
```
(commonly also, reader is not a separate task, since we immediately `fetch` it anyways).
###
[Complex Example](#Complex-Example)
The combination of a high-level programming language, a first-class command abstraction, and automatic setup of pipes between processes is a powerful one. To give some sense of the complex pipelines that can be created easily, here are some more sophisticated examples, with apologies for the excessive use of Perl one-liners:
```
julia> prefixer(prefix, sleep) = `perl -nle '$|=1; print "'$prefix' ", $_; sleep '$sleep';'`;
julia> run(pipeline(`perl -le '$|=1; for(0..5){ print; sleep 1 }'`, prefixer("A",2) & prefixer("B",2)));
B 0
A 1
B 2
A 3
B 4
A 5
```
This is a classic example of a single producer feeding two concurrent consumers: one `perl` process generates lines with the numbers 0 through 5 on them, while two parallel processes consume that output, one prefixing lines with the letter "A", the other with the letter "B". Which consumer gets the first line is non-deterministic, but once that race has been won, the lines are consumed alternately by one process and then the other. (Setting `$|=1` in Perl causes each print statement to flush the [`stdout`](../../base/io-network/index#Base.stdout) handle, which is necessary for this example to work. Otherwise all the output is buffered and printed to the pipe at once, to be read by just one consumer process.)
Here is an even more complex multi-stage producer-consumer example:
```
julia> run(pipeline(`perl -le '$|=1; for(0..5){ print; sleep 1 }'`,
prefixer("X",3) & prefixer("Y",3) & prefixer("Z",3),
prefixer("A",2) & prefixer("B",2)));
A X 0
B Y 1
A Z 2
B X 3
A Y 4
B Z 5
```
This example is similar to the previous one, except there are two stages of consumers, and the stages have different latency so they use a different number of parallel workers, to maintain saturated throughput.
We strongly encourage you to try all these examples to see how they work.
[`Cmd` Objects](#Cmd-Objects)
------------------------------
The backtick syntax create an object of type [`Cmd`](../../base/base/index#Base.Cmd). Such object may also be constructed directly from an existing `Cmd` or list of arguments:
```
run(Cmd(`pwd`, dir=".."))
run(Cmd(["pwd"], detach=true, ignorestatus=true))
```
This allows you to specify several aspects of the `Cmd`'s execution environment via keyword arguments. For example, the `dir` keyword provides control over the `Cmd`'s working directory:
```
julia> run(Cmd(`pwd`, dir="/"));
/
```
And the `env` keyword allows you to set execution environment variables:
```
julia> run(Cmd(`sh -c "echo foo \$HOWLONG"`, env=("HOWLONG" => "ever!",)));
foo ever!
```
See [`Cmd`](../../base/base/index#Base.Cmd) for additional keyword arguments. The [`setenv`](../../base/base/index#Base.setenv) and [`addenv`](../../base/base/index#Base.addenv) commands provide another means for replacing or adding to the `Cmd` execution environment variables, respectively:
```
julia> run(setenv(`sh -c "echo foo \$HOWLONG"`, ("HOWLONG" => "ever!",)));
foo ever!
julia> run(addenv(`sh -c "echo foo \$HOWLONG"`, "HOWLONG" => "ever!"));
foo ever!
```
julia Functions Functions
=========
In Julia, a function is an object that maps a tuple of argument values to a return value. Julia functions are not pure mathematical functions, because they can alter and be affected by the global state of the program. The basic syntax for defining functions in Julia is:
```
julia> function f(x,y)
x + y
end
f (generic function with 1 method)
```
This function accepts two arguments `x` and `y` and returns the value of the last expression evaluated, which is `x + y`.
There is a second, more terse syntax for defining a function in Julia. The traditional function declaration syntax demonstrated above is equivalent to the following compact "assignment form":
```
julia> f(x,y) = x + y
f (generic function with 1 method)
```
In the assignment form, the body of the function must be a single expression, although it can be a compound expression (see [Compound Expressions](../control-flow/index#man-compound-expressions)). Short, simple function definitions are common in Julia. The short function syntax is accordingly quite idiomatic, considerably reducing both typing and visual noise.
A function is called using the traditional parenthesis syntax:
```
julia> f(2,3)
5
```
Without parentheses, the expression `f` refers to the function object, and can be passed around like any other value:
```
julia> g = f;
julia> g(2,3)
5
```
As with variables, Unicode can also be used for function names:
```
julia> ∑(x,y) = x + y
∑ (generic function with 1 method)
julia> ∑(2, 3)
5
```
[Argument Passing Behavior](#Argument-Passing-Behavior)
--------------------------------------------------------
Julia function arguments follow a convention sometimes called "pass-by-sharing", which means that values are not copied when they are passed to functions. Function arguments themselves act as new variable *bindings* (new locations that can refer to values), but the values they refer to are identical to the passed values. Modifications to mutable values (such as `Array`s) made within a function will be visible to the caller. This is the same behavior found in Scheme, most Lisps, Python, Ruby and Perl, among other dynamic languages.
[Argument-type declarations](#Argument-type-declarations)
----------------------------------------------------------
You can declare the types of function arguments by appending `::TypeName` to the argument name, as usual for [Type Declarations](../types/index#Type-Declarations) in Julia. For example, the following function computes [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number) recursively:
```
fib(n::Integer) = n ≤ 2 ? one(n) : fib(n-1) + fib(n-2)
```
and the `::Integer` specification means that it will only be callable when `n` is a subtype of the [abstract](../types/index#man-abstract-types) `Integer` type.
Argument-type declarations **normally have no impact on performance**: regardless of what argument types (if any) are declared, Julia compiles a specialized version of the function for the actual argument types passed by the caller. For example, calling `fib(1)` will trigger the compilation of specialized version of `fib` optimized specifically for `Int` arguments, which is then re-used if `fib(7)` or `fib(15)` are called. (There are rare exceptions when an argument-type declaration can trigger additional compiler specializations; see: [Be aware of when Julia avoids specializing](../performance-tips/index#Be-aware-of-when-Julia-avoids-specializing).) The most common reasons to declare argument types in Julia are, instead:
* **Dispatch:** As explained in [Methods](../methods/index#Methods), you can have different versions ("methods") of a function for different argument types, in which case the argument types are used to determine which implementation is called for which arguments. For example, you might implement a completely different algorithm `fib(x::Number) = ...` that works for any `Number` type by using [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Binet%27s_formula) to extend it to non-integer values.
* **Correctness:** Type declarations can be useful if your function only returns correct results for certain argument types. For example, if we omitted argument types and wrote `fib(n) = n ≤ 2 ? one(n) : fib(n-1) + fib(n-2)`, then `fib(1.5)` would silently give us the nonsensical answer `1.0`.
* **Clarity:** Type declarations can serve as a form of documentation about the expected arguments.
However, it is a **common mistake to overly restrict the argument types**, which can unnecessarily limit the applicability of the function and prevent it from being re-used in circumstances you did not anticipate. For example, the `fib(n::Integer)` function above works equally well for `Int` arguments (machine integers) and `BigInt` arbitrary-precision integers (see [BigFloats and BigInts](../../base/numbers/index#BigFloats-and-BigInts)), which is especially useful because Fibonacci numbers grow exponentially rapidly and will quickly overflow any fixed-precision type like `Int` (see [Overflow behavior](../integers-and-floating-point-numbers/index#Overflow-behavior)). If we had declared our function as `fib(n::Int)`, however, the application to `BigInt` would have been prevented for no reason. In general, you should use the most general applicable abstract types for arguments, and **when in doubt, omit the argument types**. You can always add argument-type specifications later if they become necessary, and you don't sacrifice performance or functionality by omitting them.
[The `return` Keyword](#The-return-Keyword)
--------------------------------------------
The value returned by a function is the value of the last expression evaluated, which, by default, is the last expression in the body of the function definition. In the example function, `f`, from the previous section this is the value of the expression `x + y`. As an alternative, as in many other languages, the `return` keyword causes a function to return immediately, providing an expression whose value is returned:
```
function g(x,y)
return x * y
x + y
end
```
Since function definitions can be entered into interactive sessions, it is easy to compare these definitions:
```
julia> f(x,y) = x + y
f (generic function with 1 method)
julia> function g(x,y)
return x * y
x + y
end
g (generic function with 1 method)
julia> f(2,3)
5
julia> g(2,3)
6
```
Of course, in a purely linear function body like `g`, the usage of `return` is pointless since the expression `x + y` is never evaluated and we could simply make `x * y` the last expression in the function and omit the `return`. In conjunction with other control flow, however, `return` is of real use. Here, for example, is a function that computes the hypotenuse length of a right triangle with sides of length `x` and `y`, avoiding overflow:
```
julia> function hypot(x,y)
x = abs(x)
y = abs(y)
if x > y
r = y/x
return x*sqrt(1+r*r)
end
if y == 0
return zero(x)
end
r = x/y
return y*sqrt(1+r*r)
end
hypot (generic function with 1 method)
julia> hypot(3, 4)
5.0
```
There are three possible points of return from this function, returning the values of three different expressions, depending on the values of `x` and `y`. The `return` on the last line could be omitted since it is the last expression.
###
[Return type](#Return-type)
A return type can be specified in the function declaration using the `::` operator. This converts the return value to the specified type.
```
julia> function g(x, y)::Int8
return x * y
end;
julia> typeof(g(1, 2))
Int8
```
This function will always return an `Int8` regardless of the types of `x` and `y`. See [Type Declarations](../types/index#Type-Declarations) for more on return types.
Return type declarations are **rarely used** in Julia: in general, you should instead write "type-stable" functions in which Julia's compiler can automatically infer the return type. For more information, see the [Performance Tips](../performance-tips/index#man-performance-tips) chapter.
###
[Returning nothing](#Returning-nothing)
For functions that do not need to return a value (functions used only for some side effects), the Julia convention is to return the value [`nothing`](../../base/constants/index#Core.nothing):
```
function printx(x)
println("x = $x")
return nothing
end
```
This is a *convention* in the sense that `nothing` is not a Julia keyword but only a singleton object of type `Nothing`. Also, you may notice that the `printx` function example above is contrived, because `println` already returns `nothing`, so that the `return` line is redundant.
There are two possible shortened forms for the `return nothing` expression. On the one hand, the `return` keyword implicitly returns `nothing`, so it can be used alone. On the other hand, since functions implicitly return their last expression evaluated, `nothing` can be used alone when it's the last expression. The preference for the expression `return nothing` as opposed to `return` or `nothing` alone is a matter of coding style.
[Operators Are Functions](#Operators-Are-Functions)
----------------------------------------------------
In Julia, most operators are just functions with support for special syntax. (The exceptions are operators with special evaluation semantics like `&&` and `||`. These operators cannot be functions since [Short-Circuit Evaluation](../control-flow/index#Short-Circuit-Evaluation) requires that their operands are not evaluated before evaluation of the operator.) Accordingly, you can also apply them using parenthesized argument lists, just as you would any other function:
```
julia> 1 + 2 + 3
6
julia> +(1,2,3)
6
```
The infix form is exactly equivalent to the function application form – in fact the former is parsed to produce the function call internally. This also means that you can assign and pass around operators such as [`+`](../../base/math/index#Base.:+) and [`*`](#) just like you would with other function values:
```
julia> f = +;
julia> f(1,2,3)
6
```
Under the name `f`, the function does not support infix notation, however.
[Operators With Special Names](#Operators-With-Special-Names)
--------------------------------------------------------------
A few special expressions correspond to calls to functions with non-obvious names. These are:
| Expression | Calls |
| --- | --- |
| `[A B C ...]` | [`hcat`](../../base/arrays/index#Base.hcat) |
| `[A; B; C; ...]` | [`vcat`](../../base/arrays/index#Base.vcat) |
| `[A B; C D; ...]` | [`hvcat`](../../base/arrays/index#Base.hvcat) |
| `A'` | [`adjoint`](../../stdlib/linearalgebra/index#Base.adjoint) |
| `A[i]` | [`getindex`](../../base/collections/index#Base.getindex) |
| `A[i] = x` | [`setindex!`](../../base/collections/index#Base.setindex!) |
| `A.n` | [`getproperty`](../../base/base/index#Base.getproperty) |
| `A.n = x` | [`setproperty!`](../../base/base/index#Base.setproperty!) |
[Anonymous Functions](#man-anonymous-functions)
------------------------------------------------
Functions in Julia are [first-class objects](https://en.wikipedia.org/wiki/First-class_citizen): they can be assigned to variables, and called using the standard function call syntax from the variable they have been assigned to. They can be used as arguments, and they can be returned as values. They can also be created anonymously, without being given a name, using either of these syntaxes:
```
julia> x -> x^2 + 2x - 1
#1 (generic function with 1 method)
julia> function (x)
x^2 + 2x - 1
end
#3 (generic function with 1 method)
```
This creates a function taking one argument `x` and returning the value of the polynomial `x^2 + 2x - 1` at that value. Notice that the result is a generic function, but with a compiler-generated name based on consecutive numbering.
The primary use for anonymous functions is passing them to functions which take other functions as arguments. A classic example is [`map`](../../base/collections/index#Base.map), which applies a function to each value of an array and returns a new array containing the resulting values:
```
julia> map(round, [1.2, 3.5, 1.7])
3-element Vector{Float64}:
1.0
4.0
2.0
```
This is fine if a named function effecting the transform already exists to pass as the first argument to [`map`](../../base/collections/index#Base.map). Often, however, a ready-to-use, named function does not exist. In these situations, the anonymous function construct allows easy creation of a single-use function object without needing a name:
```
julia> map(x -> x^2 + 2x - 1, [1, 3, -1])
3-element Vector{Int64}:
2
14
-2
```
An anonymous function accepting multiple arguments can be written using the syntax `(x,y,z)->2x+y-z`. A zero-argument anonymous function is written as `()->3`. The idea of a function with no arguments may seem strange, but is useful for "delaying" a computation. In this usage, a block of code is wrapped in a zero-argument function, which is later invoked by calling it as `f`.
As an example, consider this call to [`get`](../../base/collections/index#Base.get):
```
get(dict, key) do
# default value calculated here
time()
end
```
The code above is equivalent to calling `get` with an anonymous function containing the code enclosed between `do` and `end`, like so:
```
get(()->time(), dict, key)
```
The call to [`time`](#) is delayed by wrapping it in a 0-argument anonymous function that is called only when the requested key is absent from `dict`.
[Tuples](#Tuples)
------------------
Julia has a built-in data structure called a *tuple* that is closely related to function arguments and return values. A tuple is a fixed-length container that can hold any values, but cannot be modified (it is *immutable*). Tuples are constructed with commas and parentheses, and can be accessed via indexing:
```
julia> (1, 1+1)
(1, 2)
julia> (1,)
(1,)
julia> x = (0.0, "hello", 6*7)
(0.0, "hello", 42)
julia> x[2]
"hello"
```
Notice that a length-1 tuple must be written with a comma, `(1,)`, since `(1)` would just be a parenthesized value. `()` represents the empty (length-0) tuple.
[Named Tuples](#Named-Tuples)
------------------------------
The components of tuples can optionally be named, in which case a *named tuple* is constructed:
```
julia> x = (a=2, b=1+2)
(a = 2, b = 3)
julia> x[1]
2
julia> x.a
2
```
Named tuples are very similar to tuples, except that fields can additionally be accessed by name using dot syntax (`x.a`) in addition to the regular indexing syntax (`x[1]`).
[Destructuring Assignment and Multiple Return Values](#destructuring-assignment)
---------------------------------------------------------------------------------
A comma-separated list of variables (optionally wrapped in parentheses) can appear on the left side of an assignment: the value on the right side is *destructured* by iterating over and assigning to each variable in turn:
```
julia> (a,b,c) = 1:3
1:3
julia> b
2
```
The value on the right should be an iterator (see [Iteration interface](../interfaces/index#man-interface-iteration)) at least as long as the number of variables on the left (any excess elements of the iterator are ignored).
This can be used to return multiple values from functions by returning a tuple or other iterable value. For example, the following function returns two values:
```
julia> function foo(a,b)
a+b, a*b
end
foo (generic function with 1 method)
```
If you call it in an interactive session without assigning the return value anywhere, you will see the tuple returned:
```
julia> foo(2,3)
(5, 6)
```
Destructuring assignment extracts each value into a variable:
```
julia> x, y = foo(2,3)
(5, 6)
julia> x
5
julia> y
6
```
Another common use is for swapping variables:
```
julia> y, x = x, y
(5, 6)
julia> x
6
julia> y
5
```
If only a subset of the elements of the iterator are required, a common convention is to assign ignored elements to a variable consisting of only underscores `_` (which is an otherwise invalid variable name, see [Allowed Variable Names](../variables/index#man-allowed-variable-names)):
```
julia> _, _, _, d = 1:10
1:10
julia> d
4
```
Other valid left-hand side expressions can be used as elements of the assignment list, which will call [`setindex!`](../../base/collections/index#Base.setindex!) or [`setproperty!`](../../base/base/index#Base.setproperty!), or recursively destructure individual elements of the iterator:
```
julia> X = zeros(3);
julia> X[1], (a,b) = (1, (2, 3))
(1, (2, 3))
julia> X
3-element Vector{Float64}:
1.0
0.0
0.0
julia> a
2
julia> b
3
```
`...` with assignment requires Julia 1.6
If the last symbol in the assignment list is suffixed by `...` (known as *slurping*), then it will be assigned a collection or lazy iterator of the remaining elements of the right-hand side iterator:
```
julia> a, b... = "hello"
"hello"
julia> a
'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
julia> b
"ello"
julia> a, b... = Iterators.map(abs2, 1:4)
Base.Generator{UnitRange{Int64}, typeof(abs2)}(abs2, 1:4)
julia> a
1
julia> b
Base.Iterators.Rest{Base.Generator{UnitRange{Int64}, typeof(abs2)}, Int64}(Base.Generator{UnitRange{Int64}, typeof(abs2)}(abs2, 1:4), 1)
```
See [`Base.rest`](../../base/collections/index#Base.rest) for details on the precise handling and customization for specific iterators.
[Property destructuring](#Property-destructuring)
--------------------------------------------------
Instead of destructuring based on iteration, the right side of assignments can also be destructured using property names. This follows the syntax for NamedTuples, and works by assigning to each variable on the left a property of the right side of the assignment with the same name using `getproperty`:
```
julia> (; b, a) = (a=1, b=2, c=3)
(a = 1, b = 2, c = 3)
julia> a
1
julia> b
2
```
[Argument destructuring](#Argument-destructuring)
--------------------------------------------------
The destructuring feature can also be used within a function argument. If a function argument name is written as a tuple (e.g. `(x, y)`) instead of just a symbol, then an assignment `(x, y) = argument` will be inserted for you:
```
julia> minmax(x, y) = (y < x) ? (y, x) : (x, y)
julia> gap((min, max)) = max - min
julia> gap(minmax(10, 2))
8
```
Notice the extra set of parentheses in the definition of `gap`. Without those, `gap` would be a two-argument function, and this example would not work.
Similarly, property destructuring can also be used for function arguments:
```
julia> foo((; x, y)) = x + y
foo (generic function with 1 method)
julia> foo((x=1, y=2))
3
julia> struct A
x
y
end
julia> foo(A(3, 4))
7
```
For anonymous functions, destructuring a single argument requires an extra comma:
```
julia> map(((x,y),) -> x + y, [(1,2), (3,4)])
2-element Array{Int64,1}:
3
7
```
[Varargs Functions](#Varargs-Functions)
----------------------------------------
It is often convenient to be able to write functions taking an arbitrary number of arguments. Such functions are traditionally known as "varargs" functions, which is short for "variable number of arguments". You can define a varargs function by following the last positional argument with an ellipsis:
```
julia> bar(a,b,x...) = (a,b,x)
bar (generic function with 1 method)
```
The variables `a` and `b` are bound to the first two argument values as usual, and the variable `x` is bound to an iterable collection of the zero or more values passed to `bar` after its first two arguments:
```
julia> bar(1,2)
(1, 2, ())
julia> bar(1,2,3)
(1, 2, (3,))
julia> bar(1, 2, 3, 4)
(1, 2, (3, 4))
julia> bar(1,2,3,4,5,6)
(1, 2, (3, 4, 5, 6))
```
In all these cases, `x` is bound to a tuple of the trailing values passed to `bar`.
It is possible to constrain the number of values passed as a variable argument; this will be discussed later in [Parametrically-constrained Varargs methods](../methods/index#Parametrically-constrained-Varargs-methods).
On the flip side, it is often handy to "splat" the values contained in an iterable collection into a function call as individual arguments. To do this, one also uses `...` but in the function call instead:
```
julia> x = (3, 4)
(3, 4)
julia> bar(1,2,x...)
(1, 2, (3, 4))
```
In this case a tuple of values is spliced into a varargs call precisely where the variable number of arguments go. This need not be the case, however:
```
julia> x = (2, 3, 4)
(2, 3, 4)
julia> bar(1,x...)
(1, 2, (3, 4))
julia> x = (1, 2, 3, 4)
(1, 2, 3, 4)
julia> bar(x...)
(1, 2, (3, 4))
```
Furthermore, the iterable object splatted into a function call need not be a tuple:
```
julia> x = [3,4]
2-element Vector{Int64}:
3
4
julia> bar(1,2,x...)
(1, 2, (3, 4))
julia> x = [1,2,3,4]
4-element Vector{Int64}:
1
2
3
4
julia> bar(x...)
(1, 2, (3, 4))
```
Also, the function that arguments are splatted into need not be a varargs function (although it often is):
```
julia> baz(a,b) = a + b;
julia> args = [1,2]
2-element Vector{Int64}:
1
2
julia> baz(args...)
3
julia> args = [1,2,3]
3-element Vector{Int64}:
1
2
3
julia> baz(args...)
ERROR: MethodError: no method matching baz(::Int64, ::Int64, ::Int64)
Closest candidates are:
baz(::Any, ::Any) at none:1
```
As you can see, if the wrong number of elements are in the splatted container, then the function call will fail, just as it would if too many arguments were given explicitly.
[Optional Arguments](#Optional-Arguments)
------------------------------------------
It is often possible to provide sensible default values for function arguments. This can save users from having to pass every argument on every call. For example, the function [`Date(y, [m, d])`](../../stdlib/dates/index#Dates.Date) from `Dates` module constructs a `Date` type for a given year `y`, month `m` and day `d`. However, `m` and `d` arguments are optional and their default value is `1`. This behavior can be expressed concisely as:
```
function Date(y::Int64, m::Int64=1, d::Int64=1)
err = validargs(Date, y, m, d)
err === nothing || throw(err)
return Date(UTD(totaldays(y, m, d)))
end
```
Observe, that this definition calls another method of the `Date` function that takes one argument of type `UTInstant{Day}`.
With this definition, the function can be called with either one, two or three arguments, and `1` is automatically passed when only one or two of the arguments are specified:
```
julia> using Dates
julia> Date(2000, 12, 12)
2000-12-12
julia> Date(2000, 12)
2000-12-01
julia> Date(2000)
2000-01-01
```
Optional arguments are actually just a convenient syntax for writing multiple method definitions with different numbers of arguments (see [Note on Optional and keyword Arguments](../methods/index#Note-on-Optional-and-keyword-Arguments)). This can be checked for our `Date` function example by calling `methods` function.
[Keyword Arguments](#Keyword-Arguments)
----------------------------------------
Some functions need a large number of arguments, or have a large number of behaviors. Remembering how to call such functions can be difficult. Keyword arguments can make these complex interfaces easier to use and extend by allowing arguments to be identified by name instead of only by position.
For example, consider a function `plot` that plots a line. This function might have many options, for controlling line style, width, color, and so on. If it accepts keyword arguments, a possible call might look like `plot(x, y, width=2)`, where we have chosen to specify only line width. Notice that this serves two purposes. The call is easier to read, since we can label an argument with its meaning. It also becomes possible to pass any subset of a large number of arguments, in any order.
Functions with keyword arguments are defined using a semicolon in the signature:
```
function plot(x, y; style="solid", width=1, color="black")
###
end
```
When the function is called, the semicolon is optional: one can either call `plot(x, y, width=2)` or `plot(x, y; width=2)`, but the former style is more common. An explicit semicolon is required only for passing varargs or computed keywords as described below.
Keyword argument default values are evaluated only when necessary (when a corresponding keyword argument is not passed), and in left-to-right order. Therefore default expressions may refer to prior keyword arguments.
The types of keyword arguments can be made explicit as follows:
```
function f(;x::Int=1)
###
end
```
Keyword arguments can also be used in varargs functions:
```
function plot(x...; style="solid")
###
end
```
Extra keyword arguments can be collected using `...`, as in varargs functions:
```
function f(x; y=0, kwargs...)
###
end
```
Inside `f`, `kwargs` will be an immutable key-value iterator over a named tuple. Named tuples (as well as dictionaries with keys of `Symbol`) can be passed as keyword arguments using a semicolon in a call, e.g. `f(x, z=1; kwargs...)`.
If a keyword argument is not assigned a default value in the method definition, then it is *required*: an [`UndefKeywordError`](../../base/base/index#Core.UndefKeywordError) exception will be thrown if the caller does not assign it a value:
```
function f(x; y)
###
end
f(3, y=5) # ok, y is assigned
f(3) # throws UndefKeywordError(:y)
```
One can also pass `key => value` expressions after a semicolon. For example, `plot(x, y; :width => 2)` is equivalent to `plot(x, y, width=2)`. This is useful in situations where the keyword name is computed at runtime.
When a bare identifier or dot expression occurs after a semicolon, the keyword argument name is implied by the identifier or field name. For example `plot(x, y; width)` is equivalent to `plot(x, y; width=width)` and `plot(x, y; options.width)` is equivalent to `plot(x, y; width=options.width)`.
The nature of keyword arguments makes it possible to specify the same argument more than once. For example, in the call `plot(x, y; options..., width=2)` it is possible that the `options` structure also contains a value for `width`. In such a case the rightmost occurrence takes precedence; in this example, `width` is certain to have the value `2`. However, explicitly specifying the same keyword argument multiple times, for example `plot(x, y, width=2, width=3)`, is not allowed and results in a syntax error.
[Evaluation Scope of Default Values](#Evaluation-Scope-of-Default-Values)
--------------------------------------------------------------------------
When optional and keyword argument default expressions are evaluated, only *previous* arguments are in scope. For example, given this definition:
```
function f(x, a=b, b=1)
###
end
```
the `b` in `a=b` refers to a `b` in an outer scope, not the subsequent argument `b`.
[Do-Block Syntax for Function Arguments](#Do-Block-Syntax-for-Function-Arguments)
----------------------------------------------------------------------------------
Passing functions as arguments to other functions is a powerful technique, but the syntax for it is not always convenient. Such calls are especially awkward to write when the function argument requires multiple lines. As an example, consider calling [`map`](../../base/collections/index#Base.map) on a function with several cases:
```
map(x->begin
if x < 0 && iseven(x)
return 0
elseif x == 0
return 1
else
return x
end
end,
[A, B, C])
```
Julia provides a reserved word `do` for rewriting this code more clearly:
```
map([A, B, C]) do x
if x < 0 && iseven(x)
return 0
elseif x == 0
return 1
else
return x
end
end
```
The `do x` syntax creates an anonymous function with argument `x` and passes it as the first argument to [`map`](../../base/collections/index#Base.map). Similarly, `do a,b` would create a two-argument anonymous function. Note that `do (a,b)` would create a one-argument anonymous function, whose argument is a tuple to be deconstructed. A plain `do` would declare that what follows is an anonymous function of the form `() -> ...`.
How these arguments are initialized depends on the "outer" function; here, [`map`](../../base/collections/index#Base.map) will sequentially set `x` to `A`, `B`, `C`, calling the anonymous function on each, just as would happen in the syntax `map(func, [A, B, C])`.
This syntax makes it easier to use functions to effectively extend the language, since calls look like normal code blocks. There are many possible uses quite different from [`map`](../../base/collections/index#Base.map), such as managing system state. For example, there is a version of [`open`](../../base/io-network/index#Base.open) that runs code ensuring that the opened file is eventually closed:
```
open("outfile", "w") do io
write(io, data)
end
```
This is accomplished by the following definition:
```
function open(f::Function, args...)
io = open(args...)
try
f(io)
finally
close(io)
end
end
```
Here, [`open`](../../base/io-network/index#Base.open) first opens the file for writing and then passes the resulting output stream to the anonymous function you defined in the `do ... end` block. After your function exits, [`open`](../../base/io-network/index#Base.open) will make sure that the stream is properly closed, regardless of whether your function exited normally or threw an exception. (The `try/finally` construct will be described in [Control Flow](../control-flow/index#Control-Flow).)
With the `do` block syntax, it helps to check the documentation or implementation to know how the arguments of the user function are initialized.
A `do` block, like any other inner function, can "capture" variables from its enclosing scope. For example, the variable `data` in the above example of `open...do` is captured from the outer scope. Captured variables can create performance challenges as discussed in [performance tips](../performance-tips/index#man-performance-captured).
[Function composition and piping](#Function-composition-and-piping)
--------------------------------------------------------------------
Functions in Julia can be combined by composing or piping (chaining) them together.
Function composition is when you combine functions together and apply the resulting composition to arguments. You use the function composition operator (`∘`) to compose the functions, so `(f ∘ g)(args...)` is the same as `f(g(args...))`.
You can type the composition operator at the REPL and suitably-configured editors using `\circ<tab>`.
For example, the `sqrt` and `+` functions can be composed like this:
```
julia> (sqrt ∘ +)(3, 6)
3.0
```
This adds the numbers first, then finds the square root of the result.
The next example composes three functions and maps the result over an array of strings:
```
julia> map(first ∘ reverse ∘ uppercase, split("you can compose functions like this"))
6-element Vector{Char}:
'U': ASCII/Unicode U+0055 (category Lu: Letter, uppercase)
'N': ASCII/Unicode U+004E (category Lu: Letter, uppercase)
'E': ASCII/Unicode U+0045 (category Lu: Letter, uppercase)
'S': ASCII/Unicode U+0053 (category Lu: Letter, uppercase)
'E': ASCII/Unicode U+0045 (category Lu: Letter, uppercase)
'S': ASCII/Unicode U+0053 (category Lu: Letter, uppercase)
```
Function chaining (sometimes called "piping" or "using a pipe" to send data to a subsequent function) is when you apply a function to the previous function's output:
```
julia> 1:10 |> sum |> sqrt
7.416198487095663
```
Here, the total produced by `sum` is passed to the `sqrt` function. The equivalent composition would be:
```
julia> (sqrt ∘ sum)(1:10)
7.416198487095663
```
The pipe operator can also be used with broadcasting, as `.|>`, to provide a useful combination of the chaining/piping and dot vectorization syntax (described below).
```
julia> ["a", "list", "of", "strings"] .|> [uppercase, reverse, titlecase, length]
4-element Vector{Any}:
"A"
"tsil"
"Of"
7
```
When combining pipes with anonymous functions, parentheses must be used if subsequent pipes are not to parsed as part of the anonymous function's body. Compare:
```
julia> 1:3 .|> (x -> x^2) |> sum |> sqrt
3.7416573867739413
julia> 1:3 .|> x -> x^2 |> sum |> sqrt
3-element Vector{Float64}:
1.0
2.0
3.0
```
[Dot Syntax for Vectorizing Functions](#man-vectorized)
--------------------------------------------------------
In technical-computing languages, it is common to have "vectorized" versions of functions, which simply apply a given function `f(x)` to each element of an array `A` to yield a new array via `f(A)`. This kind of syntax is convenient for data processing, but in other languages vectorization is also often required for performance: if loops are slow, the "vectorized" version of a function can call fast library code written in a low-level language. In Julia, vectorized functions are *not* required for performance, and indeed it is often beneficial to write your own loops (see [Performance Tips](../performance-tips/index#man-performance-tips)), but they can still be convenient. Therefore, *any* Julia function `f` can be applied elementwise to any array (or other collection) with the syntax `f.(A)`. For example, `sin` can be applied to all elements in the vector `A` like so:
```
julia> A = [1.0, 2.0, 3.0]
3-element Vector{Float64}:
1.0
2.0
3.0
julia> sin.(A)
3-element Vector{Float64}:
0.8414709848078965
0.9092974268256817
0.1411200080598672
```
Of course, you can omit the dot if you write a specialized "vector" method of `f`, e.g. via `f(A::AbstractArray) = map(f, A)`, and this is just as efficient as `f.(A)`. The advantage of the `f.(A)` syntax is that which functions are vectorizable need not be decided upon in advance by the library writer.
More generally, `f.(args...)` is actually equivalent to `broadcast(f, args...)`, which allows you to operate on multiple arrays (even of different shapes), or a mix of arrays and scalars (see [Broadcasting](../arrays/index#Broadcasting)). For example, if you have `f(x,y) = 3x + 4y`, then `f.(pi,A)` will return a new array consisting of `f(pi,a)` for each `a` in `A`, and `f.(vector1,vector2)` will return a new vector consisting of `f(vector1[i],vector2[i])` for each index `i` (throwing an exception if the vectors have different length).
```
julia> f(x,y) = 3x + 4y;
julia> A = [1.0, 2.0, 3.0];
julia> B = [4.0, 5.0, 6.0];
julia> f.(pi, A)
3-element Vector{Float64}:
13.42477796076938
17.42477796076938
21.42477796076938
julia> f.(A, B)
3-element Vector{Float64}:
19.0
26.0
33.0
```
Keyword arguments are not broadcasted over, but are simply passed through to each call of the function. For example, `round.(x, digits=3)` is equivalent to `broadcast(x -> round(x, digits=3), x)`.
Moreover, *nested* `f.(args...)` calls are *fused* into a single `broadcast` loop. For example, `sin.(cos.(X))` is equivalent to `broadcast(x -> sin(cos(x)), X)`, similar to `[sin(cos(x)) for x in X]`: there is only a single loop over `X`, and a single array is allocated for the result. [In contrast, `sin(cos(X))` in a typical "vectorized" language would first allocate one temporary array for `tmp=cos(X)`, and then compute `sin(tmp)` in a separate loop, allocating a second array.] This loop fusion is not a compiler optimization that may or may not occur, it is a *syntactic guarantee* whenever nested `f.(args...)` calls are encountered. Technically, the fusion stops as soon as a "non-dot" function call is encountered; for example, in `sin.(sort(cos.(X)))` the `sin` and `cos` loops cannot be merged because of the intervening `sort` function.
Finally, the maximum efficiency is typically achieved when the output array of a vectorized operation is *pre-allocated*, so that repeated calls do not allocate new arrays over and over again for the results (see [Pre-allocating outputs](../performance-tips/index#Pre-allocating-outputs)). A convenient syntax for this is `X .= ...`, which is equivalent to `broadcast!(identity, X, ...)` except that, as above, the `broadcast!` loop is fused with any nested "dot" calls. For example, `X .= sin.(Y)` is equivalent to `broadcast!(sin, X, Y)`, overwriting `X` with `sin.(Y)` in-place. If the left-hand side is an array-indexing expression, e.g. `X[begin+1:end] .= sin.(Y)`, then it translates to `broadcast!` on a `view`, e.g. `broadcast!(sin, view(X, firstindex(X)+1:lastindex(X)), Y)`, so that the left-hand side is updated in-place.
Since adding dots to many operations and function calls in an expression can be tedious and lead to code that is difficult to read, the macro [`@.`](../../base/arrays/index#Base.Broadcast.@__dot__) is provided to convert *every* function call, operation, and assignment in an expression into the "dotted" version.
```
julia> Y = [1.0, 2.0, 3.0, 4.0];
julia> X = similar(Y); # pre-allocate output array
julia> @. X = sin(cos(Y)) # equivalent to X .= sin.(cos.(Y))
4-element Vector{Float64}:
0.5143952585235492
-0.4042391538522658
-0.8360218615377305
-0.6080830096407656
```
Binary (or unary) operators like `.+` are handled with the same mechanism: they are equivalent to `broadcast` calls and are fused with other nested "dot" calls. `X .+= Y` etcetera is equivalent to `X .= X .+ Y` and results in a fused in-place assignment; see also [dot operators](../mathematical-operations/index#man-dot-operators).
You can also combine dot operations with function chaining using [`|>`](#), as in this example:
```
julia> [1:5;] .|> [x->x^2, inv, x->2*x, -, isodd]
5-element Vector{Real}:
1
0.5
6
-4
true
```
[Further Reading](#Further-Reading)
------------------------------------
We should mention here that this is far from a complete picture of defining functions. Julia has a sophisticated type system and allows multiple dispatch on argument types. None of the examples given here provide any type annotations on their arguments, meaning that they are applicable to all types of arguments. The type system is described in [Types](../types/index#man-types) and defining a function in terms of methods chosen by multiple dispatch on run-time argument types is described in [Methods](../methods/index#Methods).
| programming_docs |
julia Calling C and Fortran Code Calling C and Fortran Code
==========================
Though most code can be written in Julia, there are many high-quality, mature libraries for numerical computing already written in C and Fortran. To allow easy use of this existing code, Julia makes it simple and efficient to call C and Fortran functions. Julia has a "no boilerplate" philosophy: functions can be called directly from Julia without any "glue" code, code generation, or compilation – even from the interactive prompt. This is accomplished just by making an appropriate call with [`ccall`](../../base/c/index#ccall) syntax, which looks like an ordinary function call.
The code to be called must be available as a shared library. Most C and Fortran libraries ship compiled as shared libraries already, but if you are compiling the code yourself using GCC (or Clang), you will need to use the `-shared` and `-fPIC` options. The machine instructions generated by Julia's JIT are the same as a native C call would be, so the resulting overhead is the same as calling a library function from C code. [[1]](#footnote-1)
Shared libraries and functions are referenced by a tuple of the form `(:function, "library")` or `("function", "library")` where `function` is the C-exported function name, and `library` refers to the shared library name. Shared libraries available in the (platform-specific) load path will be resolved by name. The full path to the library may also be specified.
A function name may be used alone in place of the tuple (just `:function` or `"function"`). In this case the name is resolved within the current process. This form can be used to call C library functions, functions in the Julia runtime, or functions in an application linked to Julia.
By default, Fortran compilers [generate mangled names](https://en.wikipedia.org/wiki/Name_mangling#Fortran) (for example, converting function names to lowercase or uppercase, often appending an underscore), and so to call a Fortran function via [`ccall`](../../base/c/index#ccall) you must pass the mangled identifier corresponding to the rule followed by your Fortran compiler. Also, when calling a Fortran function, all inputs must be passed as pointers to allocated values on the heap or stack. This applies not only to arrays and other mutable objects which are normally heap-allocated, but also to scalar values such as integers and floats which are normally stack-allocated and commonly passed in registers when using C or Julia calling conventions.
Finally, you can use [`ccall`](../../base/c/index#ccall) to actually generate a call to the library function. The arguments to [`ccall`](../../base/c/index#ccall) are:
1. A `(:function, "library")` pair (most common),
OR
a `:function` name symbol or `"function"` name string (for symbols in the current process or libc),
OR
a function pointer (for example, from `dlsym`).
2. The function's return type
3. A tuple of input types, corresponding to the function signature
4. The actual argument values to be passed to the function, if any; each is a separate parameter.
The `(:function, "library")` pair, return type, and input types must be literal constants (i.e., they can't be variables, but see [Non-constant Function Specifications](#Non-constant-Function-Specifications) below).
The remaining parameters are evaluated at compile time, when the containing method is defined.
See below for how to [map C types to Julia types](#mapping-c-types-to-julia).
As a complete but simple example, the following calls the `clock` function from the standard C library on most Unix-derived systems:
```
julia> t = ccall(:clock, Int32, ())
2292761
julia> t
2292761
julia> typeof(t)
Int32
```
`clock` takes no arguments and returns an [`Int32`](../../base/numbers/index#Core.Int32). One common mistake is forgetting that a 1-tuple of argument types must be written with a trailing comma. For example, to call the `getenv` function to get a pointer to the value of an environment variable, one makes a call like this:
```
julia> path = ccall(:getenv, Cstring, (Cstring,), "SHELL")
Cstring(@0x00007fff5fbffc45)
julia> unsafe_string(path)
"/bin/bash"
```
Note that the argument type tuple must be written as `(Cstring,)`, not `(Cstring)`. This is because `(Cstring)` is just the expression `Cstring` surrounded by parentheses, rather than a 1-tuple containing `Cstring`:
```
julia> (Cstring)
Cstring
julia> (Cstring,)
(Cstring,)
```
In practice, especially when providing reusable functionality, one generally wraps [`ccall`](../../base/c/index#ccall) uses in Julia functions that set up arguments and then check for errors in whatever manner the C or Fortran function specifies. And if an error occurs it is thrown as a normal Julia exception. This is especially important since C and Fortran APIs are notoriously inconsistent about how they indicate error conditions. For example, the `getenv` C library function is wrapped in the following Julia function, which is a simplified version of the actual definition from [`env.jl`](https://github.com/JuliaLang/julia/blob/master/base/env.jl):
```
function getenv(var::AbstractString)
val = ccall(:getenv, Cstring, (Cstring,), var)
if val == C_NULL
error("getenv: undefined variable: ", var)
end
return unsafe_string(val)
end
```
The C `getenv` function indicates an error by returning `NULL`, but other standard C functions indicate errors in various different ways, including by returning -1, 0, 1 and other special values. This wrapper throws an exception clearly indicating the problem if the caller tries to get a non-existent environment variable:
```
julia> getenv("SHELL")
"/bin/bash"
julia> getenv("FOOBAR")
getenv: undefined variable: FOOBAR
```
Here is a slightly more complex example that discovers the local machine's hostname. In this example, the networking library code is assumed to be in a shared library named "libc". In practice, this function is usually part of the C standard library, and so the "libc" portion should be omitted, but we wish to show here the usage of this syntax.
```
function gethostname()
hostname = Vector{UInt8}(undef, 256) # MAXHOSTNAMELEN
err = ccall((:gethostname, "libc"), Int32,
(Ptr{UInt8}, Csize_t),
hostname, sizeof(hostname))
Base.systemerror("gethostname", err != 0)
hostname[end] = 0 # ensure null-termination
return GC.@preserve hostname unsafe_string(pointer(hostname))
end
```
This example first allocates an array of bytes. It then calls the C library function `gethostname` to populate the array with the hostname. Finally, it takes a pointer to the hostname buffer, and converts the pointer to a Julia string, assuming that it is a NUL-terminated C string.
It is common for C libraries to use this pattern of requiring the caller to allocate memory to be passed to the callee and populated. Allocation of memory from Julia like this is generally accomplished by creating an uninitialized array and passing a pointer to its data to the C function. This is why we don't use the `Cstring` type here: as the array is uninitialized, it could contain NUL bytes. Converting to a `Cstring` as part of the [`ccall`](../../base/c/index#ccall) checks for contained NUL bytes and could therefore throw a conversion error.
Dereferencing `pointer(hostname)` with `unsafe_string` is an unsafe operation as it requires access to the memory allocated for `hostname` that may have been in the meanwhile garbage collected. The macro [`GC.@preserve`](../../base/base/index#Base.GC.@preserve) prevents this from happening and therefore accessing an invalid memory location.
[Creating C-Compatible Julia Function Pointers](#Creating-C-Compatible-Julia-Function-Pointers)
------------------------------------------------------------------------------------------------
It is possible to pass Julia functions to native C functions that accept function pointer arguments. For example, to match C prototypes of the form:
```
typedef returntype (*functiontype)(argumenttype, ...)
```
The macro [`@cfunction`](../../base/c/index#Base.@cfunction) generates the C-compatible function pointer for a call to a Julia function. The arguments to [`@cfunction`](../../base/c/index#Base.@cfunction) are:
1. A Julia function
2. The function's return type
3. A tuple of input types, corresponding to the function signature
As with `ccall`, the return type and tuple of input types must be literal constants.
Currently, only the platform-default C calling convention is supported. This means that `@cfunction`-generated pointers cannot be used in calls where WINAPI expects a `stdcall` function on 32-bit Windows, but can be used on WIN64 (where `stdcall` is unified with the C calling convention).
Callback functions exposed via `@cfunction` should not throw errors, as that will return control to the Julia runtime unexpectedly and may leave the program in an undefined state.
A classic example is the standard C library `qsort` function, declared as:
```
void qsort(void *base, size_t nmemb, size_t size,
int (*compare)(const void*, const void*));
```
The `base` argument is a pointer to an array of length `nmemb`, with elements of `size` bytes each. `compare` is a callback function which takes pointers to two elements `a` and `b` and returns an integer less/greater than zero if `a` should appear before/after `b` (or zero if any order is permitted).
Now, suppose that we have a 1-d array `A` of values in Julia that we want to sort using the `qsort` function (rather than Julia's built-in `sort` function). Before we consider calling `qsort` and passing arguments, we need to write a comparison function:
```
julia> function mycompare(a, b)::Cint
return (a < b) ? -1 : ((a > b) ? +1 : 0)
end
mycompare (generic function with 1 method)
```
`qsort` expects a comparison function that return a C `int`, so we annotate the return type to be `Cint`.
In order to pass this function to C, we obtain its address using the macro `@cfunction`:
```
julia> mycompare_c = @cfunction(mycompare, Cint, (Ref{Cdouble}, Ref{Cdouble}));
```
[`@cfunction`](../../base/c/index#Base.@cfunction) requires three arguments: the Julia function (`mycompare`), the return type (`Cint`), and a literal tuple of the input argument types, in this case to sort an array of `Cdouble` ([`Float64`](../../base/numbers/index#Core.Float64)) elements.
The final call to `qsort` looks like this:
```
julia> A = [1.3, -2.7, 4.4, 3.1]
4-element Vector{Float64}:
1.3
-2.7
4.4
3.1
julia> ccall(:qsort, Cvoid, (Ptr{Cdouble}, Csize_t, Csize_t, Ptr{Cvoid}),
A, length(A), sizeof(eltype(A)), mycompare_c)
julia> A
4-element Vector{Float64}:
-2.7
1.3
3.1
4.4
```
As the example shows, the original Julia array `A` has now been sorted: `[-2.7, 1.3, 3.1, 4.4]`. Note that Julia [takes care of converting the array to a `Ptr{Cdouble}`](#automatic-type-conversion)), computing the size of the element type in bytes, and so on.
For fun, try inserting a `println("mycompare($a, $b)")` line into `mycompare`, which will allow you to see the comparisons that `qsort` is performing (and to verify that it is really calling the Julia function that you passed to it).
[Mapping C Types to Julia](#mapping-c-types-to-julia)
------------------------------------------------------
It is critical to exactly match the declared C type with its declaration in Julia. Inconsistencies can cause code that works correctly on one system to fail or produce indeterminate results on a different system.
Note that no C header files are used anywhere in the process of calling C functions: you are responsible for making sure that your Julia types and call signatures accurately reflect those in the C header file.[[2]](#footnote-2)
###
[Automatic Type Conversion](#automatic-type-conversion)
Julia automatically inserts calls to the [`Base.cconvert`](../../base/c/index#Base.cconvert) function to convert each argument to the specified type. For example, the following call:
```
ccall((:foo, "libfoo"), Cvoid, (Int32, Float64), x, y)
```
will behave as if it were written like this:
```
ccall((:foo, "libfoo"), Cvoid, (Int32, Float64),
Base.unsafe_convert(Int32, Base.cconvert(Int32, x)),
Base.unsafe_convert(Float64, Base.cconvert(Float64, y)))
```
[`Base.cconvert`](../../base/c/index#Base.cconvert) normally just calls [`convert`](../../base/base/index#Base.convert), but can be defined to return an arbitrary new object more appropriate for passing to C. This should be used to perform all allocations of memory that will be accessed by the C code. For example, this is used to convert an `Array` of objects (e.g. strings) to an array of pointers.
[`Base.unsafe_convert`](../../base/c/index#Base.unsafe_convert) handles conversion to [`Ptr`](../../base/c/index#Core.Ptr) types. It is considered unsafe because converting an object to a native pointer can hide the object from the garbage collector, causing it to be freed prematurely.
###
[Type Correspondences](#Type-Correspondences)
First, let's review some relevant Julia type terminology:
| Syntax / Keyword | Example | Description |
| --- | --- | --- |
| `mutable struct` | `BitSet` | "Leaf Type" :: A group of related data that includes a type-tag, is managed by the Julia GC, and is defined by object-identity. The type parameters of a leaf type must be fully defined (no `TypeVars` are allowed) in order for the instance to be constructed. |
| `abstract type` | `Any`, `AbstractArray{T, N}`, `Complex{T}` | "Super Type" :: A super-type (not a leaf-type) that cannot be instantiated, but can be used to describe a group of types. |
| `T{A}` | `Vector{Int}` | "Type Parameter" :: A specialization of a type (typically used for dispatch or storage optimization). |
| | | "TypeVar" :: The `T` in the type parameter declaration is referred to as a TypeVar (short for type variable). |
| `primitive type` | `Int`, `Float64` | "Primitive Type" :: A type with no fields, but a size. It is stored and defined by-value. |
| `struct` | `Pair{Int, Int}` | "Struct" :: A type with all fields defined to be constant. It is defined by-value, and may be stored with a type-tag. |
| | `ComplexF64` (`isbits`) | "Is-Bits" :: A `primitive type`, or a `struct` type where all fields are other `isbits` types. It is defined by-value, and is stored without a type-tag. |
| `struct ...; end` | `nothing` | "Singleton" :: a Leaf Type or Struct with no fields. |
| `(...)` or `tuple(...)` | `(1, 2, 3)` | "Tuple" :: an immutable data-structure similar to an anonymous struct type, or a constant array. Represented as either an array or a struct. |
###
[Bits Types](#man-bits-types)
There are several special types to be aware of, as no other type can be defined to behave the same:
* `Float32`
Exactly corresponds to the `float` type in C (or `REAL*4` in Fortran).
* `Float64`
Exactly corresponds to the `double` type in C (or `REAL*8` in Fortran).
* `ComplexF32`
Exactly corresponds to the `complex float` type in C (or `COMPLEX*8` in Fortran).
* `ComplexF64`
Exactly corresponds to the `complex double` type in C (or `COMPLEX*16` in Fortran).
* `Signed`
Exactly corresponds to the `signed` type annotation in C (or any `INTEGER` type in Fortran). Any Julia type that is not a subtype of [`Signed`](../../base/numbers/index#Core.Signed) is assumed to be unsigned.
* `Ref{T}`
Behaves like a `Ptr{T}` that can manage its memory via the Julia GC.
* `Array{T,N}`
When an array is passed to C as a `Ptr{T}` argument, it is not reinterpret-cast: Julia requires that the element type of the array matches `T`, and the address of the first element is passed.
Therefore, if an `Array` contains data in the wrong format, it will have to be explicitly converted using a call such as `trunc(Int32, a)`.
To pass an array `A` as a pointer of a different type *without* converting the data beforehand (for example, to pass a `Float64` array to a function that operates on uninterpreted bytes), you can declare the argument as `Ptr{Cvoid}`.
If an array of eltype `Ptr{T}` is passed as a `Ptr{Ptr{T}}` argument, [`Base.cconvert`](../../base/c/index#Base.cconvert) will attempt to first make a null-terminated copy of the array with each element replaced by its [`Base.cconvert`](../../base/c/index#Base.cconvert) version. This allows, for example, passing an `argv` pointer array of type `Vector{String}` to an argument of type `Ptr{Ptr{Cchar}}`.
On all systems we currently support, basic C/C++ value types may be translated to Julia types as follows. Every C type also has a corresponding Julia type with the same name, prefixed by C. This can help when writing portable code (and remembering that an `int` in C is not the same as an `Int` in Julia).
**System Independent Types**
| C name | Fortran name | Standard Julia Alias | Julia Base Type |
| --- | --- | --- | --- |
| `unsigned char` | `CHARACTER` | `Cuchar` | `UInt8` |
| `bool` (\_Bool in C99+) | | `Cuchar` | `UInt8` |
| `short` | `INTEGER*2`, `LOGICAL*2` | `Cshort` | `Int16` |
| `unsigned short` | | `Cushort` | `UInt16` |
| `int`, `BOOL` (C, typical) | `INTEGER*4`, `LOGICAL*4` | `Cint` | `Int32` |
| `unsigned int` | | `Cuint` | `UInt32` |
| `long long` | `INTEGER*8`, `LOGICAL*8` | `Clonglong` | `Int64` |
| `unsigned long long` | | `Culonglong` | `UInt64` |
| `intmax_t` | | `Cintmax_t` | `Int64` |
| `uintmax_t` | | `Cuintmax_t` | `UInt64` |
| `float` | `REAL*4i` | `Cfloat` | `Float32` |
| `double` | `REAL*8` | `Cdouble` | `Float64` |
| `complex float` | `COMPLEX*8` | `ComplexF32` | `Complex{Float32}` |
| `complex double` | `COMPLEX*16` | `ComplexF64` | `Complex{Float64}` |
| `ptrdiff_t` | | `Cptrdiff_t` | `Int` |
| `ssize_t` | | `Cssize_t` | `Int` |
| `size_t` | | `Csize_t` | `UInt` |
| `void` | | | `Cvoid` |
| `void` and `[[noreturn]]` or `_Noreturn` | | | `Union{}` |
| `void*` | | | `Ptr{Cvoid}` (or similarly `Ref{Cvoid}`) |
| `T*` (where T represents an appropriately defined type) | | | `Ref{T}` (T may be safely mutated only if T is an isbits type) |
| `char*` (or `char[]`, e.g. a string) | `CHARACTER*N` | | `Cstring` if NUL-terminated, or `Ptr{UInt8}` if not |
| `char**` (or `*char[]`) | | | `Ptr{Ptr{UInt8}}` |
| `jl_value_t*` (any Julia Type) | | | `Any` |
| `jl_value_t* const*` (a reference to a Julia value) | | | `Ref{Any}` (const, since mutation would require a write barrier, which is not possible to insert correctly) |
| `va_arg` | | | Not supported |
| `...` (variadic function specification) | | | `T...` (where `T` is one of the above types, when using the `ccall` function) |
| `...` (variadic function specification) | | | `; va_arg1::T, va_arg2::S, etc.` (only supported with `@ccall` macro) |
The [`Cstring`](../../base/c/index#Base.Cstring) type is essentially a synonym for `Ptr{UInt8}`, except the conversion to `Cstring` throws an error if the Julia string contains any embedded NUL characters (which would cause the string to be silently truncated if the C routine treats NUL as the terminator). If you are passing a `char*` to a C routine that does not assume NUL termination (e.g. because you pass an explicit string length), or if you know for certain that your Julia string does not contain NUL and want to skip the check, you can use `Ptr{UInt8}` as the argument type. `Cstring` can also be used as the [`ccall`](../../base/c/index#ccall) return type, but in that case it obviously does not introduce any extra checks and is only meant to improve readability of the call.
**System Dependent Types**
| C name | Standard Julia Alias | Julia Base Type |
| --- | --- | --- |
| `char` | `Cchar` | `Int8` (x86, x86\_64), `UInt8` (powerpc, arm) |
| `long` | `Clong` | `Int` (UNIX), `Int32` (Windows) |
| `unsigned long` | `Culong` | `UInt` (UNIX), `UInt32` (Windows) |
| `wchar_t` | `Cwchar_t` | `Int32` (UNIX), `UInt16` (Windows) |
When calling Fortran, all inputs must be passed by pointers to heap- or stack-allocated values, so all type correspondences above should contain an additional `Ptr{..}` or `Ref{..}` wrapper around their type specification.
For string arguments (`char*`) the Julia type should be `Cstring` (if NUL- terminated data is expected), or either `Ptr{Cchar}` or `Ptr{UInt8}` otherwise (these two pointer types have the same effect), as described above, not `String`. Similarly, for array arguments (`T[]` or `T*`), the Julia type should again be `Ptr{T}`, not `Vector{T}`.
Julia's `Char` type is 32 bits, which is not the same as the wide character type (`wchar_t` or `wint_t`) on all platforms.
A return type of `Union{}` means the function will not return, i.e., C++11 `[[noreturn]]` or C11 `_Noreturn` (e.g. `jl_throw` or `longjmp`). Do not use this for functions that return no value (`void`) but do return, use `Cvoid` instead.
For `wchar_t*` arguments, the Julia type should be [`Cwstring`](../../base/c/index#Base.Cwstring) (if the C routine expects a NUL-terminated string), or `Ptr{Cwchar_t}` otherwise. Note also that UTF-8 string data in Julia is internally NUL-terminated, so it can be passed to C functions expecting NUL-terminated data without making a copy (but using the `Cwstring` type will cause an error to be thrown if the string itself contains NUL characters).
C functions that take an argument of type `char**` can be called by using a `Ptr{Ptr{UInt8}}` type within Julia. For example, C functions of the form:
```
int main(int argc, char **argv);
```
can be called via the following Julia code:
```
argv = [ "a.out", "arg1", "arg2" ]
ccall(:main, Int32, (Int32, Ptr{Ptr{UInt8}}), length(argv), argv)
```
For Fortran functions taking variable length strings of type `character(len=*)` the string lengths are provided as *hidden arguments*. Type and position of these arguments in the list are compiler specific, where compiler vendors usually default to using `Csize_t` as type and append the hidden arguments at the end of the argument list. While this behaviour is fixed for some compilers (GNU), others *optionally* permit placing hidden arguments directly after the character argument (Intel, PGI). For example, Fortran subroutines of the form
```
subroutine test(str1, str2)
character(len=*) :: str1,str2
```
can be called via the following Julia code, where the lengths are appended
```
str1 = "foo"
str2 = "bar"
ccall(:test, Cvoid, (Ptr{UInt8}, Ptr{UInt8}, Csize_t, Csize_t),
str1, str2, sizeof(str1), sizeof(str2))
```
Fortran compilers *may* also add other hidden arguments for pointers, assumed-shape (`:`) and assumed-size (`*`) arrays. Such behaviour can be avoided by using `ISO_C_BINDING` and including `bind(c)` in the definition of the subroutine, which is strongly recommended for interoperable code. In this case there will be no hidden arguments, at the cost of some language features (e.g. only `character(len=1)` will be permitted to pass strings).
A C function declared to return `Cvoid` will return the value `nothing` in Julia.
###
[Struct Type Correspondences](#Struct-Type-Correspondences)
Composite types such as `struct` in C or `TYPE` in Fortran90 (or `STRUCTURE` / `RECORD` in some variants of F77), can be mirrored in Julia by creating a `struct` definition with the same field layout.
When used recursively, `isbits` types are stored inline. All other types are stored as a pointer to the data. When mirroring a struct used by-value inside another struct in C, it is imperative that you do not attempt to manually copy the fields over, as this will not preserve the correct field alignment. Instead, declare an `isbits` struct type and use that instead. Unnamed structs are not possible in the translation to Julia.
Packed structs and union declarations are not supported by Julia.
You can get an approximation of a `union` if you know, a priori, the field that will have the greatest size (potentially including padding). When translating your fields to Julia, declare the Julia field to be only of that type.
Arrays of parameters can be expressed with `NTuple`. For example, the struct in C notation written as
```
struct B {
int A[3];
};
b_a_2 = B.A[2];
```
can be written in Julia as
```
struct B
A::NTuple{3, Cint}
end
b_a_2 = B.A[3] # note the difference in indexing (1-based in Julia, 0-based in C)
```
Arrays of unknown size (C99-compliant variable length structs specified by `[]` or `[0]`) are not directly supported. Often the best way to deal with these is to deal with the byte offsets directly. For example, if a C library declared a proper string type and returned a pointer to it:
```
struct String {
int strlen;
char data[];
};
```
In Julia, we can access the parts independently to make a copy of that string:
```
str = from_c::Ptr{Cvoid}
len = unsafe_load(Ptr{Cint}(str))
unsafe_string(str + Core.sizeof(Cint), len)
```
###
[Type Parameters](#Type-Parameters)
The type arguments to `ccall` and `@cfunction` are evaluated statically, when the method containing the usage is defined. They therefore must take the form of a literal tuple, not a variable, and cannot reference local variables.
This may sound like a strange restriction, but remember that since C is not a dynamic language like Julia, its functions can only accept argument types with a statically-known, fixed signature.
However, while the type layout must be known statically to compute the intended C ABI, the static parameters of the function are considered to be part of this static environment. The static parameters of the function may be used as type parameters in the call signature, as long as they don't affect the layout of the type. For example, `f(x::T) where {T} = ccall(:valid, Ptr{T}, (Ptr{T},), x)` is valid, since `Ptr` is always a word-size primitive type. But, `g(x::T) where {T} = ccall(:notvalid, T, (T,), x)` is not valid, since the type layout of `T` is not known statically.
###
[SIMD Values](#SIMD-Values)
Note: This feature is currently implemented on 64-bit x86 and AArch64 platforms only.
If a C/C++ routine has an argument or return value that is a native SIMD type, the corresponding Julia type is a homogeneous tuple of `VecElement` that naturally maps to the SIMD type. Specifically:
> * The tuple must be the same size as the SIMD type. For example, a tuple representing an `__m128` on x86 must have a size of 16 bytes.
> * The element type of the tuple must be an instance of `VecElement{T}` where `T` is a primitive type that is 1, 2, 4 or 8 bytes.
>
For instance, consider this C routine that uses AVX intrinsics:
```
#include <immintrin.h>
__m256 dist( __m256 a, __m256 b ) {
return _mm256_sqrt_ps(_mm256_add_ps(_mm256_mul_ps(a, a),
_mm256_mul_ps(b, b)));
}
```
The following Julia code calls `dist` using `ccall`:
```
const m256 = NTuple{8, VecElement{Float32}}
a = m256(ntuple(i -> VecElement(sin(Float32(i))), 8))
b = m256(ntuple(i -> VecElement(cos(Float32(i))), 8))
function call_dist(a::m256, b::m256)
ccall((:dist, "libdist"), m256, (m256, m256), a, b)
end
println(call_dist(a,b))
```
The host machine must have the requisite SIMD registers. For example, the code above will not work on hosts without AVX support.
###
[Memory Ownership](#Memory-Ownership)
**malloc/free**
Memory allocation and deallocation of such objects must be handled by calls to the appropriate cleanup routines in the libraries being used, just like in any C program. Do not try to free an object received from a C library with [`Libc.free`](../../base/libc/index#Base.Libc.free) in Julia, as this may result in the `free` function being called via the wrong library and cause the process to abort. The reverse (passing an object allocated in Julia to be freed by an external library) is equally invalid.
###
[When to use T, Ptr{T} and Ref{T}](#When-to-use-T,-Ptr%7BT%7D-and-Ref%7BT%7D)
In Julia code wrapping calls to external C routines, ordinary (non-pointer) data should be declared to be of type `T` inside the [`ccall`](../../base/c/index#ccall), as they are passed by value. For C code accepting pointers, [`Ref{T}`](../../base/c/index#Core.Ref) should generally be used for the types of input arguments, allowing the use of pointers to memory managed by either Julia or C through the implicit call to [`Base.cconvert`](../../base/c/index#Base.cconvert). In contrast, pointers returned by the C function called should be declared to be of output type [`Ptr{T}`](../../base/c/index#Core.Ptr), reflecting that the memory pointed to is managed by C only. Pointers contained in C structs should be represented as fields of type `Ptr{T}` within the corresponding Julia struct types designed to mimic the internal structure of corresponding C structs.
In Julia code wrapping calls to external Fortran routines, all input arguments should be declared as of type `Ref{T}`, as Fortran passes all variables by pointers to memory locations. The return type should either be `Cvoid` for Fortran subroutines, or a `T` for Fortran functions returning the type `T`.
[Mapping C Functions to Julia](#Mapping-C-Functions-to-Julia)
--------------------------------------------------------------
###
[`ccall` / `@cfunction` argument translation guide](#ccall-/-@cfunction-argument-translation-guide)
For translating a C argument list to Julia:
* `T`, where `T` is one of the primitive types: `char`, `int`, `long`, `short`, `float`, `double`, `complex`, `enum` or any of their `typedef` equivalents
+ `T`, where `T` is an equivalent Julia Bits Type (per the table above)
+ if `T` is an `enum`, the argument type should be equivalent to `Cint` or `Cuint`
+ argument value will be copied (passed by value)
* `struct T` (including typedef to a struct)
+ `T`, where `T` is a Julia leaf type
+ argument value will be copied (passed by value)
* `void*`
+ depends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list
+ this argument may be declared as `Ptr{Cvoid}`, if it really is just an unknown pointer
* `jl_value_t*`
+ `Any`
+ argument value must be a valid Julia object
* `jl_value_t* const*`
+ `Ref{Any}`
+ argument list must be a valid Julia object (or `C_NULL`)
+ cannot be used for an output parameter, unless the user is able to separately arrange for the object to be GC-preserved
* `T*`
+ `Ref{T}`, where `T` is the Julia type corresponding to `T`
+ argument value will be copied if it is an `inlinealloc` type (which includes `isbits` otherwise, the value must be a valid Julia object
* `T (*)(...)` (e.g. a pointer to a function)
+ `Ptr{Cvoid}` (you may need to use [`@cfunction`](../../base/c/index#Base.@cfunction) explicitly to create this pointer)
* `...` (e.g. a vararg)
+ [for `ccall`]: `T...`, where `T` is the single Julia type of all remaining arguments
+ [for `@ccall`]: `; va_arg1::T, va_arg2::S, etc`, where `T` and `S` are the Julia type (i.e. separate the regular arguments from varargs with a `;`)
+ currently unsupported by `@cfunction`
* `va_arg`
+ not supported by `ccall` or `@cfunction`
###
[`ccall` / `@cfunction` return type translation guide](#ccall-/-@cfunction-return-type-translation-guide)
For translating a C return type to Julia:
* `void`
+ `Cvoid` (this will return the singleton instance `nothing::Cvoid`)
* `T`, where `T` is one of the primitive types: `char`, `int`, `long`, `short`, `float`, `double`, `complex`, `enum` or any of their `typedef` equivalents
+ `T`, where `T` is an equivalent Julia Bits Type (per the table above)
+ if `T` is an `enum`, the argument type should be equivalent to `Cint` or `Cuint`
+ argument value will be copied (returned by-value)
* `struct T` (including typedef to a struct)
+ `T`, where `T` is a Julia Leaf Type
+ argument value will be copied (returned by-value)
* `void*`
+ depends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list
+ this argument may be declared as `Ptr{Cvoid}`, if it really is just an unknown pointer
* `jl_value_t*`
+ `Any`
+ argument value must be a valid Julia object
* `jl_value_t**`
+ `Ptr{Any}` (`Ref{Any}` is invalid as a return type)
* `T*`
+ If the memory is already owned by Julia, or is an `isbits` type, and is known to be non-null:
- `Ref{T}`, where `T` is the Julia type corresponding to `T`
- a return type of `Ref{Any}` is invalid, it should either be `Any` (corresponding to `jl_value_t*`) or `Ptr{Any}` (corresponding to `jl_value_t**`)
- C **MUST NOT** modify the memory returned via `Ref{T}` if `T` is an `isbits` type
+ If the memory is owned by C:
- `Ptr{T}`, where `T` is the Julia type corresponding to `T`
* `T (*)(...)` (e.g. a pointer to a function)
+ `Ptr{Cvoid}` to call this directly from Julia you will need to pass this as the first argument to [`ccall`](../../base/c/index#ccall). See [Indirect Calls](#Indirect-Calls).
###
[Passing Pointers for Modifying Inputs](#Passing-Pointers-for-Modifying-Inputs)
Because C doesn't support multiple return values, often C functions will take pointers to data that the function will modify. To accomplish this within a [`ccall`](../../base/c/index#ccall), you need to first encapsulate the value inside a [`Ref{T}`](../../base/c/index#Core.Ref) of the appropriate type. When you pass this `Ref` object as an argument, Julia will automatically pass a C pointer to the encapsulated data:
```
width = Ref{Cint}(0)
range = Ref{Cfloat}(0)
ccall(:foo, Cvoid, (Ref{Cint}, Ref{Cfloat}), width, range)
```
Upon return, the contents of `width` and `range` can be retrieved (if they were changed by `foo`) by `width[]` and `range[]`; that is, they act like zero-dimensional arrays.
[C Wrapper Examples](#C-Wrapper-Examples)
------------------------------------------
Let's start with a simple example of a C wrapper that returns a `Ptr` type:
```
mutable struct gsl_permutation
end
# The corresponding C signature is
# gsl_permutation * gsl_permutation_alloc (size_t n);
function permutation_alloc(n::Integer)
output_ptr = ccall(
(:gsl_permutation_alloc, :libgsl), # name of C function and library
Ptr{gsl_permutation}, # output type
(Csize_t,), # tuple of input types
n # name of Julia variable to pass in
)
if output_ptr == C_NULL # Could not allocate memory
throw(OutOfMemoryError())
end
return output_ptr
end
```
The [GNU Scientific Library](https://www.gnu.org/software/gsl/) (here assumed to be accessible through `:libgsl`) defines an opaque pointer, `gsl_permutation *`, as the return type of the C function `gsl_permutation_alloc`. As user code never has to look inside the `gsl_permutation` struct, the corresponding Julia wrapper simply needs a new type declaration, `gsl_permutation`, that has no internal fields and whose sole purpose is to be placed in the type parameter of a `Ptr` type. The return type of the [`ccall`](../../base/c/index#ccall) is declared as `Ptr{gsl_permutation}`, since the memory allocated and pointed to by `output_ptr` is controlled by C.
The input `n` is passed by value, and so the function's input signature is simply declared as `(Csize_t,)` without any `Ref` or `Ptr` necessary. (If the wrapper was calling a Fortran function instead, the corresponding function input signature would instead be `(Ref{Csize_t},)`, since Fortran variables are passed by pointers.) Furthermore, `n` can be any type that is convertible to a `Csize_t` integer; the [`ccall`](../../base/c/index#ccall) implicitly calls [`Base.cconvert(Csize_t, n)`](../../base/c/index#Base.cconvert).
Here is a second example wrapping the corresponding destructor:
```
# The corresponding C signature is
# void gsl_permutation_free (gsl_permutation * p);
function permutation_free(p::Ref{gsl_permutation})
ccall(
(:gsl_permutation_free, :libgsl), # name of C function and library
Cvoid, # output type
(Ref{gsl_permutation},), # tuple of input types
p # name of Julia variable to pass in
)
end
```
Here, the input `p` is declared to be of type `Ref{gsl_permutation}`, meaning that the memory that `p` points to may be managed by Julia or by C. A pointer to memory allocated by C should be of type `Ptr{gsl_permutation}`, but it is convertible using [`Base.cconvert`](../../base/c/index#Base.cconvert) and therefore
Now if you look closely enough at this example, you may notice that it is incorrect, given our explanation above of preferred declaration types. Do you see it? The function we are calling is going to free the memory. This type of operation cannot be given a Julia object (it will crash or cause memory corruption). Therefore, it may be preferable to declare the `p` type as `Ptr{gsl_permutation }`, to make it harder for the user to mistakenly pass another sort of object there than one obtained via `gsl_permutation_alloc`.
If the C wrapper never expects the user to pass pointers to memory managed by Julia, then using `p::Ptr{gsl_permutation}` for the method signature of the wrapper and similarly in the [`ccall`](../../base/c/index#ccall) is also acceptable.
Here is a third example passing Julia arrays:
```
# The corresponding C signature is
# int gsl_sf_bessel_Jn_array (int nmin, int nmax, double x,
# double result_array[])
function sf_bessel_Jn_array(nmin::Integer, nmax::Integer, x::Real)
if nmax < nmin
throw(DomainError())
end
result_array = Vector{Cdouble}(undef, nmax - nmin + 1)
errorcode = ccall(
(:gsl_sf_bessel_Jn_array, :libgsl), # name of C function and library
Cint, # output type
(Cint, Cint, Cdouble, Ref{Cdouble}),# tuple of input types
nmin, nmax, x, result_array # names of Julia variables to pass in
)
if errorcode != 0
error("GSL error code $errorcode")
end
return result_array
end
```
The C function wrapped returns an integer error code; the results of the actual evaluation of the Bessel J function populate the Julia array `result_array`. This variable is declared as a `Ref{Cdouble}`, since its memory is allocated and managed by Julia. The implicit call to [`Base.cconvert(Ref{Cdouble}, result_array)`](../../base/c/index#Base.cconvert) unpacks the Julia pointer to a Julia array data structure into a form understandable by C.
[Fortran Wrapper Example](#Fortran-Wrapper-Example)
----------------------------------------------------
The following example utilizes `ccall` to call a function in a common Fortran library (libBLAS) to computes a dot product. Notice that the argument mapping is a bit different here than above, as we need to map from Julia to Fortran. On every argument type, we specify `Ref` or `Ptr`. This mangling convention may be specific to your fortran compiler and operating system, and is likely undocumented. However, wrapping each in a `Ref` (or `Ptr`, where equivalent) is a frequent requirement of Fortran compiler implementations:
```
function compute_dot(DX::Vector{Float64}, DY::Vector{Float64})
@assert length(DX) == length(DY)
n = length(DX)
incx = incy = 1
product = ccall((:ddot_, "libLAPACK"),
Float64,
(Ref{Int32}, Ptr{Float64}, Ref{Int32}, Ptr{Float64}, Ref{Int32}),
n, DX, incx, DY, incy)
return product
end
```
[Garbage Collection Safety](#Garbage-Collection-Safety)
--------------------------------------------------------
When passing data to a [`ccall`](../../base/c/index#ccall), it is best to avoid using the [`pointer`](../../base/c/index#Base.pointer) function. Instead define a convert method and pass the variables directly to the [`ccall`](../../base/c/index#ccall). [`ccall`](../../base/c/index#ccall) automatically arranges that all of its arguments will be preserved from garbage collection until the call returns. If a C API will store a reference to memory allocated by Julia, after the [`ccall`](../../base/c/index#ccall) returns, you must ensure that the object remains visible to the garbage collector. The suggested way to do this is to make a global variable of type `Array{Ref,1}` to hold these values, until the C library notifies you that it is finished with them.
Whenever you have created a pointer to Julia data, you must ensure the original data exists until you have finished using the pointer. Many methods in Julia such as [`unsafe_load`](../../base/c/index#Base.unsafe_load) and [`String`](#) make copies of data instead of taking ownership of the buffer, so that it is safe to free (or alter) the original data without affecting Julia. A notable exception is [`unsafe_wrap`](#) which, for performance reasons, shares (or can be told to take ownership of) the underlying buffer.
The garbage collector does not guarantee any order of finalization. That is, if `a` contained a reference to `b` and both `a` and `b` are due for garbage collection, there is no guarantee that `b` would be finalized after `a`. If proper finalization of `a` depends on `b` being valid, it must be handled in other ways.
[Non-constant Function Specifications](#Non-constant-Function-Specifications)
------------------------------------------------------------------------------
In some cases, the exact name or path of the needed library is not known in advance and must be computed at run time. To handle such cases, the library component of a `(name, library)` specification can be a function call, e.g. `(:dgemm_, find_blas())`. The call expression will be executed when the `ccall` itself is executed. However, it is assumed that the library location does not change once it is determined, so the result of the call can be cached and reused. Therefore, the number of times the expression executes is unspecified, and returning different values for multiple calls results in unspecified behavior.
If even more flexibility is needed, it is possible to use computed values as function names by staging through [`eval`](../../base/base/index#Base.MainInclude.eval) as follows:
```
@eval ccall(($(string("a", "b")), "lib"), ...
```
This expression constructs a name using `string`, then substitutes this name into a new [`ccall`](../../base/c/index#ccall) expression, which is then evaluated. Keep in mind that `eval` only operates at the top level, so within this expression local variables will not be available (unless their values are substituted with `$`). For this reason, `eval` is typically only used to form top-level definitions, for example when wrapping libraries that contain many similar functions. A similar example can be constructed for [`@cfunction`](../../base/c/index#Base.@cfunction).
However, doing this will also be very slow and leak memory, so you should usually avoid this and instead keep reading. The next section discusses how to use indirect calls to efficiently achieve a similar effect.
[Indirect Calls](#Indirect-Calls)
----------------------------------
The first argument to [`ccall`](../../base/c/index#ccall) can also be an expression evaluated at run time. In this case, the expression must evaluate to a `Ptr`, which will be used as the address of the native function to call. This behavior occurs when the first [`ccall`](../../base/c/index#ccall) argument contains references to non-constants, such as local variables, function arguments, or non-constant globals.
For example, you might look up the function via `dlsym`, then cache it in a shared reference for that session. For example:
```
macro dlsym(func, lib)
z = Ref{Ptr{Cvoid}}(C_NULL)
quote
let zlocal = $z[]
if zlocal == C_NULL
zlocal = dlsym($(esc(lib))::Ptr{Cvoid}, $(esc(func)))::Ptr{Cvoid}
$z[] = zlocal
end
zlocal
end
end
end
mylibvar = Libdl.dlopen("mylib")
ccall(@dlsym("myfunc", mylibvar), Cvoid, ())
```
[Closure cfunctions](#Closure-cfunctions)
------------------------------------------
The first argument to [`@cfunction`](../../base/c/index#Base.@cfunction) can be marked with a `$`, in which case the return value will instead be a `struct CFunction` which closes over the argument. You must ensure that this return object is kept alive until all uses of it are done. The contents and code at the cfunction pointer will be erased via a [`finalizer`](../../base/base/index#Base.finalizer) when this reference is dropped and atexit. This is not usually needed, since this functionality is not present in C, but can be useful for dealing with ill-designed APIs which don't provide a separate closure environment parameter.
```
function qsort(a::Vector{T}, cmp) where T
isbits(T) || throw(ArgumentError("this method can only qsort isbits arrays"))
callback = @cfunction $cmp Cint (Ref{T}, Ref{T})
# Here, `callback` isa Base.CFunction, which will be converted to Ptr{Cvoid}
# (and protected against finalization) by the ccall
ccall(:qsort, Cvoid, (Ptr{T}, Csize_t, Csize_t, Ptr{Cvoid}),
a, length(a), Base.elsize(a), callback)
# We could instead use:
# GC.@preserve callback begin
# use(Base.unsafe_convert(Ptr{Cvoid}, callback))
# end
# if we needed to use it outside of a `ccall`
return a
end
```
Closure [`@cfunction`](../../base/c/index#Base.@cfunction) rely on LLVM trampolines, which are not available on all platforms (for example ARM and PowerPC).
[Closing a Library](#Closing-a-Library)
----------------------------------------
It is sometimes useful to close (unload) a library so that it can be reloaded. For instance, when developing C code for use with Julia, one may need to compile, call the C code from Julia, then close the library, make an edit, recompile, and load in the new changes. One can either restart Julia or use the `Libdl` functions to manage the library explicitly, such as:
```
lib = Libdl.dlopen("./my_lib.so") # Open the library explicitly.
sym = Libdl.dlsym(lib, :my_fcn) # Get a symbol for the function to call.
ccall(sym, ...) # Use the pointer `sym` instead of the (symbol, library) tuple (remaining arguments are the same).
Libdl.dlclose(lib) # Close the library explicitly.
```
Note that when using `ccall` with the tuple input (e.g., `ccall((:my_fcn, "./my_lib.so"), ...)`), the library is opened implicitly and it may not be explicitly closed.
[Calling Convention](#Calling-Convention)
------------------------------------------
The second argument to [`ccall`](../../base/c/index#ccall) can optionally be a calling convention specifier (immediately preceding return type). Without any specifier, the platform-default C calling convention is used. Other supported conventions are: `stdcall`, `cdecl`, `fastcall`, and `thiscall` (no-op on 64-bit Windows). For example (from `base/libc.jl`) we see the same `gethostname`[`ccall`](../../base/c/index#ccall) as above, but with the correct signature for Windows:
```
hn = Vector{UInt8}(undef, 256)
err = ccall(:gethostname, stdcall, Int32, (Ptr{UInt8}, UInt32), hn, length(hn))
```
For more information, please see the [LLVM Language Reference](https://llvm.org/docs/LangRef.html#calling-conventions).
There is one additional special calling convention [`llvmcall`](../../base/c/index#Core.Intrinsics.llvmcall), which allows inserting calls to LLVM intrinsics directly. This can be especially useful when targeting unusual platforms such as GPGPUs. For example, for [CUDA](https://llvm.org/docs/NVPTXUsage.html), we need to be able to read the thread index:
```
ccall("llvm.nvvm.read.ptx.sreg.tid.x", llvmcall, Int32, ())
```
As with any `ccall`, it is essential to get the argument signature exactly correct. Also, note that there is no compatibility layer that ensures the intrinsic makes sense and works on the current target, unlike the equivalent Julia functions exposed by `Core.Intrinsics`.
[Accessing Global Variables](#Accessing-Global-Variables)
----------------------------------------------------------
Global variables exported by native libraries can be accessed by name using the [`cglobal`](../../base/c/index#Core.Intrinsics.cglobal) function. The arguments to [`cglobal`](../../base/c/index#Core.Intrinsics.cglobal) are a symbol specification identical to that used by [`ccall`](../../base/c/index#ccall), and a type describing the value stored in the variable:
```
julia> cglobal((:errno, :libc), Int32)
Ptr{Int32} @0x00007f418d0816b8
```
The result is a pointer giving the address of the value. The value can be manipulated through this pointer using [`unsafe_load`](../../base/c/index#Base.unsafe_load) and [`unsafe_store!`](../../base/c/index#Base.unsafe_store!).
This `errno` symbol may not be found in a library named "libc", as this is an implementation detail of your system compiler. Typically standard library symbols should be accessed just by name, allowing the compiler to fill in the correct one. Also, however, the `errno` symbol shown in this example is special in most compilers, and so the value seen here is probably not what you expect or want. Compiling the equivalent code in C on any multi-threaded-capable system would typically actually call a different function (via macro preprocessor overloading), and may give a different result than the legacy value printed here.
[Accessing Data through a Pointer](#Accessing-Data-through-a-Pointer)
----------------------------------------------------------------------
The following methods are described as "unsafe" because a bad pointer or type declaration can cause Julia to terminate abruptly.
Given a `Ptr{T}`, the contents of type `T` can generally be copied from the referenced memory into a Julia object using `unsafe_load(ptr, [index])`. The index argument is optional (default is 1), and follows the Julia-convention of 1-based indexing. This function is intentionally similar to the behavior of [`getindex`](../../base/collections/index#Base.getindex) and [`setindex!`](../../base/collections/index#Base.setindex!) (e.g. `[]` access syntax).
The return value will be a new object initialized to contain a copy of the contents of the referenced memory. The referenced memory can safely be freed or released.
If `T` is `Any`, then the memory is assumed to contain a reference to a Julia object (a `jl_value_t*`), the result will be a reference to this object, and the object will not be copied. You must be careful in this case to ensure that the object was always visible to the garbage collector (pointers do not count, but the new reference does) to ensure the memory is not prematurely freed. Note that if the object was not originally allocated by Julia, the new object will never be finalized by Julia's garbage collector. If the `Ptr` itself is actually a `jl_value_t*`, it can be converted back to a Julia object reference by [`unsafe_pointer_to_objref(ptr)`](../../base/c/index#Base.unsafe_pointer_to_objref). (Julia values `v` can be converted to `jl_value_t*` pointers, as `Ptr{Cvoid}`, by calling [`pointer_from_objref(v)`](../../base/c/index#Base.pointer_from_objref).)
The reverse operation (writing data to a `Ptr{T}`), can be performed using [`unsafe_store!(ptr, value, [index])`](../../base/c/index#Base.unsafe_store!). Currently, this is only supported for primitive types or other pointer-free (`isbits`) immutable struct types.
Any operation that throws an error is probably currently unimplemented and should be posted as a bug so that it can be resolved.
If the pointer of interest is a plain-data array (primitive type or immutable struct), the function [`unsafe_wrap(Array, ptr,dims, own = false)`](#) may be more useful. The final parameter should be true if Julia should "take ownership" of the underlying buffer and call `free(ptr)` when the returned `Array` object is finalized. If the `own` parameter is omitted or false, the caller must ensure the buffer remains in existence until all access is complete.
Arithmetic on the `Ptr` type in Julia (e.g. using `+`) does not behave the same as C's pointer arithmetic. Adding an integer to a `Ptr` in Julia always moves the pointer by some number of *bytes*, not elements. This way, the address values obtained from pointer arithmetic do not depend on the element types of pointers.
[Thread-safety](#Thread-safety)
--------------------------------
Some C libraries execute their callbacks from a different thread, and since Julia isn't thread-safe you'll need to take some extra precautions. In particular, you'll need to set up a two-layered system: the C callback should only *schedule* (via Julia's event loop) the execution of your "real" callback. To do this, create an [`AsyncCondition`](../../base/base/index#Base.AsyncCondition) object and [`wait`](../../base/parallel/index#Base.wait) on it:
```
cond = Base.AsyncCondition()
wait(cond)
```
The callback you pass to C should only execute a [`ccall`](../../base/c/index#ccall) to `:uv_async_send`, passing `cond.handle` as the argument, taking care to avoid any allocations or other interactions with the Julia runtime.
Note that events may be coalesced, so multiple calls to `uv_async_send` may result in a single wakeup notification to the condition.
[More About Callbacks](#More-About-Callbacks)
----------------------------------------------
For more details on how to pass callbacks to C libraries, see this [blog post](https://julialang.org/blog/2013/05/callback).
[C++](#C)
----------
For direct C++ interfacing, see the [Cxx](https://github.com/Keno/Cxx.jl) package. For tools to create C++ bindings, see the [CxxWrap](https://github.com/JuliaInterop/CxxWrap.jl) package.
* [1](#citeref-1)Non-library function calls in both C and Julia can be inlined and thus may have even less overhead than calls to shared library functions. The point above is that the cost of actually doing foreign function call is about the same as doing a call in either native language.
* [2](#citeref-2)The [Clang package](https://github.com/ihnorton/Clang.jl) can be used to auto-generate Julia code from a C header file.
| programming_docs |
julia Modules Modules
=======
Modules in Julia help organize code into coherent units. They are delimited syntactically inside `module NameOfModule ... end`, and have the following features:
1. Modules are separate namespaces, each introducing a new global scope. This is useful, because it allows the same name to be used for different functions or global variables without conflict, as long as they are in separate modules.
2. Modules have facilities for detailed namespace management: each defines a set of names it `export`s, and can import names from other modules with `using` and `import` (we explain these below).
3. Modules can be precompiled for faster loading, and contain code for runtime initialization.
Typically, in larger Julia packages you will see module code organized into files, eg
```
module SomeModule
# export, using, import statements are usually here; we discuss these below
include("file1.jl")
include("file2.jl")
end
```
Files and file names are mostly unrelated to modules; modules are associated only with module expressions. One can have multiple files per module, and multiple modules per file. `include` behaves as if the contents of the source file were evaluated in the global scope of the including module. In this chapter, we use short and simplified examples, so we won't use `include`.
The recommended style is not to indent the body of the module, since that would typically lead to whole files being indented. Also, it is common to use `UpperCamelCase` for module names (just like types), and use the plural form if applicable, especially if the module contains a similarly named identifier, to avoid name clashes. For example,
```
module FastThings
struct FastThing
...
end
end
```
[Namespace management](#namespace-management)
----------------------------------------------
Namespace management refers to the facilities the language offers for making names in a module available in other modules. We discuss the related concepts and functionality below in detail.
###
[Qualified names](#Qualified-names)
Names for functions, variables and types in the global scope like `sin`, `ARGS`, and `UnitRange` always belong to a module, called the *parent module*, which can be found interactively with [`parentmodule`](../../base/base/index#Base.parentmodule), for example
```
julia> parentmodule(UnitRange)
Base
```
One can also refer to these names outside their parent module by prefixing them with their module, eg `Base.UnitRange`. This is called a *qualified name*. The parent module may be accessible using a chain of submodules like `Base.Math.sin`, where `Base.Math` is called the *module path*. Due to syntactic ambiguities, qualifying a name that contains only symbols, such as an operator, requires inserting a colon, e.g. `Base.:+`. A small number of operators additionally require parentheses, e.g. `Base.:(==)`.
If a name is qualified, then it is always *accessible*, and in case of a function, it can also have methods added to it by using the qualified name as the function name.
Within a module, a variable name can be “reserved” without assigning to it by declaring it as `global x`. This prevents name conflicts for globals initialized after load time. The syntax `M.x = y` does not work to assign a global in another module; global assignment is always module-local.
###
[Export lists](#Export-lists)
Names (referring to functions, types, global variables, and constants) can be added to the *export list* of a module with `export`. Typically, they are at or near the top of the module definition so that readers of the source code can find them easily, as in
```
julia> module NiceStuff
export nice, DOG
struct Dog end # singleton type, not exported
const DOG = Dog() # named instance, exported
nice(x) = "nice $x" # function, exported
end;
```
but this is just a style suggestion — a module can have multiple `export` statements in arbitrary locations.
It is common to export names which form part of the API (application programming interface). In the above code, the export list suggests that users should use `nice` and `DOG`. However, since qualified names always make identifiers accessible, this is just an option for organizing APIs: unlike other languages, Julia has no facilities for truly hiding module internals.
Also, some modules don't export names at all. This is usually done if they use common words, such as `derivative`, in their API, which could easily clash with the export lists of other modules. We will see how to manage name clashes below.
###
[Standalone `using` and `import`](#Standalone-using-and-import)
Possibly the most common way of loading a module is `using ModuleName`. This [loads](../code-loading/index#code-loading) the code associated with `ModuleName`, and brings
1. the module name
2. and the elements of the export list into the surrounding global namespace.
Technically, the statement `using ModuleName` means that a module called `ModuleName` will be available for resolving names as needed. When a global variable is encountered that has no definition in the current module, the system will search for it among variables exported by `ModuleName` and use it if it is found there. This means that all uses of that global within the current module will resolve to the definition of that variable in `ModuleName`.
To load a module from a package, the statement `using ModuleName` can be used. To load a module from a locally defined module, a dot needs to be added before the module name like `using .ModuleName`.
To continue with our example,
```
julia> using .NiceStuff
```
would load the above code, making `NiceStuff` (the module name), `DOG` and `nice` available. `Dog` is not on the export list, but it can be accessed if the name is qualified with the module path (which here is just the module name) as `NiceStuff.Dog`.
Importantly, **`using ModuleName` is the only form for which export lists matter at all**.
In contrast,
```
julia> import .NiceStuff
```
brings *only* the module name into scope. Users would need to use `NiceStuff.DOG`, `NiceStuff.Dog`, and `NiceStuff.nice` to access its contents. Usually, `import ModuleName` is used in contexts when the user wants to keep the namespace clean. As we will see in the next section `import .NiceStuff` is equivalent to `using .NiceStuff: NiceStuff`.
You can combine multiple `using` and `import` statements of the same kind in a comma-separated expression, e.g.
```
julia> using LinearAlgebra, Statistics
```
###
[`using` and `import` with specific identifiers, and adding methods](#using-and-import-with-specific-identifiers,-and-adding-methods)
When `using ModuleName:` or `import ModuleName:` is followed by a comma-separated list of names, the module is loaded, but *only those specific names are brought into the namespace* by the statement. For example,
```
julia> using .NiceStuff: nice, DOG
```
will import the names `nice` and `DOG`.
Importantly, the module name `NiceStuff` will *not* be in the namespace. If you want to make it accessible, you have to list it explicitly, as
```
julia> using .NiceStuff: nice, DOG, NiceStuff
```
Julia has two forms for seemingly the same thing because only `import ModuleName: f` allows adding methods to `f` *without a module path*. That is to say, the following example will give an error:
```
julia> using .NiceStuff: nice
julia> struct Cat end
julia> nice(::Cat) = "nice 😸"
ERROR: error in method definition: function NiceStuff.nice must be explicitly imported to be extended
Stacktrace:
[1] top-level scope
@ none:0
[2] top-level scope
@ none:1
```
This error prevents accidentally adding methods to functions in other modules that you only intended to use.
There are two ways to deal with this. You can always qualify function names with a module path:
```
julia> using .NiceStuff
julia> struct Cat end
julia> NiceStuff.nice(::Cat) = "nice 😸"
```
Alternatively, you can `import` the specific function name:
```
julia> import .NiceStuff: nice
julia> struct Cat end
julia> nice(::Cat) = "nice 😸"
nice (generic function with 2 methods)
```
Which one you choose is a matter of style. The first form makes it clear that you are adding a method to a function in another module (remember, that the imports and the method definition may be in separate files), while the second one is shorter, which is especially convenient if you are defining multiple methods.
Once a variable is made visible via `using` or `import`, a module may not create its own variable with the same name. Imported variables are read-only; assigning to a global variable always affects a variable owned by the current module, or else raises an error.
###
[Renaming with `as`](#Renaming-with-as)
An identifier brought into scope by `import` or `using` can be renamed with the keyword `as`. This is useful for working around name conflicts as well as for shortening names. For example, `Base` exports the function name `read`, but the CSV.jl package also provides `CSV.read`. If we are going to invoke CSV reading many times, it would be convenient to drop the `CSV.` qualifier. But then it is ambiguous whether we are referring to `Base.read` or `CSV.read`:
```
julia> read;
julia> import CSV: read
WARNING: ignoring conflicting import of CSV.read into Main
```
Renaming provides a solution:
```
julia> import CSV: read as rd
```
Imported packages themselves can also be renamed:
```
import BenchmarkTools as BT
```
`as` works with `using` only when a single identifier is brought into scope. For example `using CSV: read as rd` works, but `using CSV as C` does not, since it operates on all of the exported names in `CSV`.
###
[Mixing multiple `using` and `import` statements](#Mixing-multiple-using-and-import-statements)
When multiple `using` or `import` statements of any of the forms above are used, their effect is combined in the order they appear. For example,
```
julia> using .NiceStuff # exported names and the module name
julia> import .NiceStuff: nice # allows adding methods to unqualified functions
```
would bring all the exported names of `NiceStuff` and the module name itself into scope, and also allow adding methods to `nice` without prefixing it with a module name.
###
[Handling name conflicts](#Handling-name-conflicts)
Consider the situation where two (or more) packages export the same name, as in
```
julia> module A
export f
f() = 1
end
A
julia> module B
export f
f() = 2
end
B
```
The statement `using .A, .B` works, but when you try to call `f`, you get a warning
```
julia> using .A, .B
julia> f
WARNING: both B and A export "f"; uses of it in module Main must be qualified
ERROR: UndefVarError: f not defined
```
Here, Julia cannot decide which `f` you are referring to, so you have to make a choice. The following solutions are commonly used:
1. Simply proceed with qualified names like `A.f` and `B.f`. This makes the context clear to the reader of your code, especially if `f` just happens to coincide but has different meaning in various packages. For example, `degree` has various uses in mathematics, the natural sciences, and in everyday life, and these meanings should be kept separate.
2. Use the `as` keyword above to rename one or both identifiers, eg
```
julia> using .A: f as f
julia> using .B: f as g
```
would make `B.f` available as `g`. Here, we are assuming that you did not use `using A` before, which would have brought `f` into the namespace.
3. When the names in question *do* share a meaning, it is common for one module to import it from another, or have a lightweight “base” package with the sole function of defining an interface like this, which can be used by other packages. It is conventional to have such package names end in `...Base` (which has nothing to do with Julia's `Base` module).
###
[Default top-level definitions and bare modules](#Default-top-level-definitions-and-bare-modules)
Modules automatically contain `using Core`, `using Base`, and definitions of the [`eval`](../../base/base/index#Base.MainInclude.eval) and [`include`](../../base/base/index#Base.MainInclude.include) functions, which evaluate expressions/files within the global scope of that module.
If these default definitions are not wanted, modules can be defined using the keyword [`baremodule`](../../base/base/index#baremodule) instead (note: `Core` is still imported). In terms of `baremodule`, a standard `module` looks like this:
```
baremodule Mod
using Base
eval(x) = Core.eval(Mod, x)
include(p) = Base.include(Mod, p)
...
end
```
If even `Core` is not wanted, a module that imports nothing and defines no names at all can be defined with `Module(:YourNameHere, false, false)` and code can be evaluated into it with [`@eval`](../../base/base/index#Base.@eval) or [`Core.eval`](../../base/base/index#Core.eval).
###
[Standard modules](#Standard-modules)
There are three important standard modules:
* [`Core`](../../base/base/index#Core) contains all functionality "built into" the language.
* [`Base`](../../base/base/index#Base) contains basic functionality that is useful in almost all cases.
* [`Main`](../../base/base/index#Main) is the top-level module and the current module, when Julia is started.
By default Julia ships with some standard library modules. These behave like regular Julia packages except that you don't need to install them explicitly. For example, if you wanted to perform some unit testing, you could load the `Test` standard library as follows:
```
using Test
```
[Submodules and relative paths](#Submodules-and-relative-paths)
----------------------------------------------------------------
Modules can contain *submodules*, nesting the same syntax `module ... end`. They can be used to introduce separate namespaces, which can be helpful for organizing complex codebases. Note that each `module` introduces its own [scope](../variables-and-scoping/index#scope-of-variables), so submodules do not automatically “inherit” names from their parent.
It is recommended that submodules refer to other modules within the enclosing parent module (including the latter) using *relative module qualifiers* in `using` and `import` statements. A relative module qualifier starts with a period (`.`), which corresponds to the current module, and each successive `.` leads to the parent of the current module. This should be followed by modules if necessary, and eventually the actual name to access, all separated by `.`s.
Consider the following example, where the submodule `SubA` defines a function, which is then extended in its “sibling” module:
```
julia> module ParentModule
module SubA
export add_D # exported interface
const D = 3
add_D(x) = x + D
end
using .SubA # brings `add_D` into the namespace
export add_D # export it from ParentModule too
module SubB
import ..SubA: add_D # relative path for a “sibling” module
struct Infinity end
add_D(x::Infinity) = x
end
end;
```
You may see code in packages, which, in a similar situation, uses
```
julia> import .ParentModule.SubA: add_D
```
However, this operates through [code loading](../code-loading/index#code-loading), and thus only works if `ParentModule` is in a package. It is better to use relative paths.
Note that the order of definitions also matters if you are evaluating values. Consider
```
module TestPackage
export x, y
x = 0
module Sub
using ..TestPackage
z = y # ERROR: UndefVarError: y not defined
end
y = 1
end
```
where `Sub` is trying to use `TestPackage.y` before it was defined, so it does not have a value.
For similar reasons, you cannot use a cyclic ordering:
```
module A
module B
using ..C # ERROR: UndefVarError: C not defined
end
module C
using ..B
end
end
```
[Module initialization and precompilation](#Module-initialization-and-precompilation)
--------------------------------------------------------------------------------------
Large modules can take several seconds to load because executing all of the statements in a module often involves compiling a large amount of code. Julia creates precompiled caches of the module to reduce this time.
The incremental precompiled module file are created and used automatically when using `import` or `using` to load a module. This will cause it to be automatically compiled the first time it is imported. Alternatively, you can manually call [`Base.compilecache(modulename)`](../../base/base/index#Base.compilecache). The resulting cache files will be stored in `DEPOT_PATH[1]/compiled/`. Subsequently, the module is automatically recompiled upon `using` or `import` whenever any of its dependencies change; dependencies are modules it imports, the Julia build, files it includes, or explicit dependencies declared by [`include_dependency(path)`](../../base/base/index#Base.include_dependency) in the module file(s).
For file dependencies, a change is determined by examining whether the modification time (`mtime`) of each file loaded by `include` or added explicitly by `include_dependency` is unchanged, or equal to the modification time truncated to the nearest second (to accommodate systems that can't copy mtime with sub-second accuracy). It also takes into account whether the path to the file chosen by the search logic in `require` matches the path that had created the precompile file. It also takes into account the set of dependencies already loaded into the current process and won't recompile those modules, even if their files change or disappear, in order to avoid creating incompatibilities between the running system and the precompile cache.
If you know that a module is *not* safe to precompile (for example, for one of the reasons described below), you should put `__precompile__(false)` in the module file (typically placed at the top). This will cause `Base.compilecache` to throw an error, and will cause `using` / `import` to load it directly into the current process and skip the precompile and caching. This also thereby prevents the module from being imported by any other precompiled module.
You may need to be aware of certain behaviors inherent in the creation of incremental shared libraries which may require care when writing your module. For example, external state is not preserved. To accommodate this, explicitly separate any initialization steps that must occur at *runtime* from steps that can occur at *compile time*. For this purpose, Julia allows you to define an `__init__()` function in your module that executes any initialization steps that must occur at runtime. This function will not be called during compilation (`--output-*`). Effectively, you can assume it will be run exactly once in the lifetime of the code. You may, of course, call it manually if necessary, but the default is to assume this function deals with computing state for the local machine, which does not need to be – or even should not be – captured in the compiled image. It will be called after the module is loaded into a process, including if it is being loaded into an incremental compile (`--output-incremental=yes`), but not if it is being loaded into a full-compilation process.
In particular, if you define a `function __init__()` in a module, then Julia will call `__init__()` immediately *after* the module is loaded (e.g., by `import`, `using`, or `require`) at runtime for the *first* time (i.e., `__init__` is only called once, and only after all statements in the module have been executed). Because it is called after the module is fully imported, any submodules or other imported modules have their `__init__` functions called *before* the `__init__` of the enclosing module.
Two typical uses of `__init__` are calling runtime initialization functions of external C libraries and initializing global constants that involve pointers returned by external libraries. For example, suppose that we are calling a C library `libfoo` that requires us to call a `foo_init()` initialization function at runtime. Suppose that we also want to define a global constant `foo_data_ptr` that holds the return value of a `void *foo_data()` function defined by `libfoo` – this constant must be initialized at runtime (not at compile time) because the pointer address will change from run to run. You could accomplish this by defining the following `__init__` function in your module:
```
const foo_data_ptr = Ref{Ptr{Cvoid}}(0)
function __init__()
ccall((:foo_init, :libfoo), Cvoid, ())
foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Cvoid}, ())
nothing
end
```
Notice that it is perfectly possible to define a global inside a function like `__init__`; this is one of the advantages of using a dynamic language. But by making it a constant at global scope, we can ensure that the type is known to the compiler and allow it to generate better optimized code. Obviously, any other globals in your module that depends on `foo_data_ptr` would also have to be initialized in `__init__`.
Constants involving most Julia objects that are not produced by [`ccall`](../../base/c/index#ccall) do not need to be placed in `__init__`: their definitions can be precompiled and loaded from the cached module image. This includes complicated heap-allocated objects like arrays. However, any routine that returns a raw pointer value must be called at runtime for precompilation to work ([`Ptr`](../../base/c/index#Core.Ptr) objects will turn into null pointers unless they are hidden inside an [`isbits`](../../base/base/index#Base.isbits) object). This includes the return values of the Julia functions [`@cfunction`](../../base/c/index#Base.@cfunction) and [`pointer`](../../base/c/index#Base.pointer).
Dictionary and set types, or in general anything that depends on the output of a `hash(key)` method, are a trickier case. In the common case where the keys are numbers, strings, symbols, ranges, `Expr`, or compositions of these types (via arrays, tuples, sets, pairs, etc.) they are safe to precompile. However, for a few other key types, such as `Function` or `DataType` and generic user-defined types where you haven't defined a `hash` method, the fallback `hash` method depends on the memory address of the object (via its `objectid`) and hence may change from run to run. If you have one of these key types, or if you aren't sure, to be safe you can initialize this dictionary from within your `__init__` function. Alternatively, you can use the [`IdDict`](../../base/collections/index#Base.IdDict) dictionary type, which is specially handled by precompilation so that it is safe to initialize at compile-time.
When using precompilation, it is important to keep a clear sense of the distinction between the compilation phase and the execution phase. In this mode, it will often be much more clearly apparent that Julia is a compiler which allows execution of arbitrary Julia code, not a standalone interpreter that also generates compiled code.
Other known potential failure scenarios include:
1. Global counters (for example, for attempting to uniquely identify objects). Consider the following code snippet:
```
mutable struct UniquedById
myid::Int
let counter = 0
UniquedById() = new(counter += 1)
end
end
```
while the intent of this code was to give every instance a unique id, the counter value is recorded at the end of compilation. All subsequent usages of this incrementally compiled module will start from that same counter value.
Note that `objectid` (which works by hashing the memory pointer) has similar issues (see notes on `Dict` usage below).
One alternative is to use a macro to capture [`@__MODULE__`](../../base/base/index#Base.@__MODULE__) and store it alone with the current `counter` value, however, it may be better to redesign the code to not depend on this global state.
2. Associative collections (such as `Dict` and `Set`) need to be re-hashed in `__init__`. (In the future, a mechanism may be provided to register an initializer function.)
3. Depending on compile-time side-effects persisting through load-time. Example include: modifying arrays or other variables in other Julia modules; maintaining handles to open files or devices; storing pointers to other system resources (including memory);
4. Creating accidental "copies" of global state from another module, by referencing it directly instead of via its lookup path. For example, (in global scope):
```
#mystdout = Base.stdout #= will not work correctly, since this will copy Base.stdout into this module =#
# instead use accessor functions:
getstdout() = Base.stdout #= best option =#
# or move the assignment into the runtime:
__init__() = global mystdout = Base.stdout #= also works =#
```
Several additional restrictions are placed on the operations that can be done while precompiling code to help the user avoid other wrong-behavior situations:
1. Calling [`eval`](../../base/base/index#Base.MainInclude.eval) to cause a side-effect in another module. This will also cause a warning to be emitted when the incremental precompile flag is set.
2. `global const` statements from local scope after `__init__()` has been started (see issue #12010 for plans to add an error for this)
3. Replacing a module is a runtime error while doing an incremental precompile.
A few other points to be aware of:
1. No code reload / cache invalidation is performed after changes are made to the source files themselves, (including by `Pkg.update`), and no cleanup is done after `Pkg.rm`
2. The memory sharing behavior of a reshaped array is disregarded by precompilation (each view gets its own copy)
3. Expecting the filesystem to be unchanged between compile-time and runtime e.g. [`@__FILE__`](../../base/base/index#Base.@__FILE__)/`source_path()` to find resources at runtime, or the BinDeps `@checked_lib` macro. Sometimes this is unavoidable. However, when possible, it can be good practice to copy resources into the module at compile-time so they won't need to be found at runtime.
4. `WeakRef` objects and finalizers are not currently handled properly by the serializer (this will be fixed in an upcoming release).
5. It is usually best to avoid capturing references to instances of internal metadata objects such as `Method`, `MethodInstance`, `MethodTable`, `TypeMapLevel`, `TypeMapEntry` and fields of those objects, as this can confuse the serializer and may not lead to the outcome you desire. It is not necessarily an error to do this, but you simply need to be prepared that the system will try to copy some of these and to create a single unique instance of others.
It is sometimes helpful during module development to turn off incremental precompilation. The command line flag `--compiled-modules={yes|no}` enables you to toggle module precompilation on and off. When Julia is started with `--compiled-modules=no` the serialized modules in the compile cache are ignored when loading modules and module dependencies. `Base.compilecache` can still be called manually. The state of this command line flag is passed to `Pkg.build` to disable automatic precompilation triggering when installing, updating, and explicitly building packages.
| programming_docs |
julia Code Loading Code Loading
============
This chapter covers the technical details of package loading. To install packages, use [`Pkg`](../../stdlib/pkg/index#Pkg), Julia's built-in package manager, to add packages to your active environment. To use packages already in your active environment, write `import X` or `using X`, as described in the [Modules documentation](../modules/index#modules).
[Definitions](#Definitions)
----------------------------
Julia has two mechanisms for loading code:
1. **Code inclusion:** e.g. `include("source.jl")`. Inclusion allows you to split a single program across multiple source files. The expression `include("source.jl")` causes the contents of the file `source.jl` to be evaluated in the global scope of the module where the `include` call occurs. If `include("source.jl")` is called multiple times, `source.jl` is evaluated multiple times. The included path, `source.jl`, is interpreted relative to the file where the `include` call occurs. This makes it simple to relocate a subtree of source files. In the REPL, included paths are interpreted relative to the current working directory, [`pwd()`](../../base/file/index#Base.Filesystem.pwd).
2. **Package loading:** e.g. `import X` or `using X`. The import mechanism allows you to load a package—i.e. an independent, reusable collection of Julia code, wrapped in a module—and makes the resulting module available by the name `X` inside of the importing module. If the same `X` package is imported multiple times in the same Julia session, it is only loaded the first time—on subsequent imports, the importing module gets a reference to the same module. Note though, that `import X` can load different packages in different contexts: `X` can refer to one package named `X` in the main project but potentially to different packages also named `X` in each dependency. More on this below.
Code inclusion is quite straightforward and simple: it evaluates the given source file in the context of the caller. Package loading is built on top of code inclusion and serves a [different purpose](../modules/index#modules). The rest of this chapter focuses on the behavior and mechanics of package loading.
A *package* is a source tree with a standard layout providing functionality that can be reused by other Julia projects. A package is loaded by `import X` or `using X` statements. These statements also make the module named `X`—which results from loading the package code—available within the module where the import statement occurs. The meaning of `X` in `import X` is context-dependent: which `X` package is loaded depends on what code the statement occurs in. Thus, handling of `import X` happens in two stages: first, it determines **what** package is defined to be `X` in this context; second, it determines **where** that particular `X` package is found.
These questions are answered by searching through the project environments listed in [`LOAD_PATH`](../../base/constants/index#Base.LOAD_PATH) for project files (`Project.toml` or `JuliaProject.toml`), manifest files (`Manifest.toml` or `JuliaManifest.toml`), or folders of source files.
[Federation of packages](#Federation-of-packages)
--------------------------------------------------
Most of the time, a package is uniquely identifiable simply from its name. However, sometimes a project might encounter a situation where it needs to use two different packages that share the same name. While you might be able fix this by renaming one of the packages, being forced to do so can be highly disruptive in a large, shared code base. Instead, Julia's code loading mechanism allows the same package name to refer to different packages in different components of an application.
Julia supports federated package management, which means that multiple independent parties can maintain both public and private packages and registries of packages, and that projects can depend on a mix of public and private packages from different registries. Packages from various registries are installed and managed using a common set of tools and workflows. The `Pkg` package manager that ships with Julia lets you install and manage your projects' dependencies. It assists in creating and manipulating project files (which describe what other projects that your project depends on), and manifest files (which snapshot exact versions of your project's complete dependency graph).
One consequence of federation is that there cannot be a central authority for package naming. Different entities may use the same name to refer to unrelated packages. This possibility is unavoidable since these entities do not coordinate and may not even know about each other. Because of the lack of a central naming authority, a single project may end up depending on different packages that have the same name. Julia's package loading mechanism does not require package names to be globally unique, even within the dependency graph of a single project. Instead, packages are identified by [universally unique identifiers](https://en.wikipedia.org/wiki/Universally_unique_identifier) (UUIDs), which get assigned when each package is created. Usually you won't have to work directly with these somewhat cumbersome 128-bit identifiers since `Pkg` will take care of generating and tracking them for you. However, these UUIDs provide the definitive answer to the question of *"what package does `X` refer to?"*
Since the decentralized naming problem is somewhat abstract, it may help to walk through a concrete scenario to understand the issue. Suppose you're developing an application called `App`, which uses two packages: `Pub` and `Priv`. `Priv` is a private package that you created, whereas `Pub` is a public package that you use but don't control. When you created `Priv`, there was no public package by the name `Priv`. Subsequently, however, an unrelated package also named `Priv` has been published and become popular. In fact, the `Pub` package has started to use it. Therefore, when you next upgrade `Pub` to get the latest bug fixes and features, `App` will end up depending on two different packages named `Priv`—through no action of yours other than upgrading. `App` has a direct dependency on your private `Priv` package, and an indirect dependency, through `Pub`, on the new public `Priv` package. Since these two `Priv` packages are different but are both required for `App` to continue working correctly, the expression `import Priv` must refer to different `Priv` packages depending on whether it occurs in `App`'s code or in `Pub`'s code. To handle this, Julia's package loading mechanism distinguishes the two `Priv` packages by their UUID and picks the correct one based on its context (the module that called `import`). How this distinction works is determined by environments, as explained in the following sections.
[Environments](#Environments)
------------------------------
An *environment* determines what `import X` and `using X` mean in various code contexts and what files these statements cause to be loaded. Julia understands two kinds of environments:
1. **A project environment** is a directory with a project file and an optional manifest file, and forms an *explicit environment*. The project file determines what the names and identities of the direct dependencies of a project are. The manifest file, if present, gives a complete dependency graph, including all direct and indirect dependencies, exact versions of each dependency, and sufficient information to locate and load the correct version.
2. **A package directory** is a directory containing the source trees of a set of packages as subdirectories, and forms an *implicit environment*. If `X` is a subdirectory of a package directory and `X/src/X.jl` exists, then the package `X` is available in the package directory environment and `X/src/X.jl` is the source file by which it is loaded.
These can be intermixed to create **a stacked environment**: an ordered set of project environments and package directories, overlaid to make a single composite environment. The precedence and visibility rules then combine to determine which packages are available and where they get loaded from. Julia's load path forms a stacked environment, for example.
These environment each serve a different purpose:
* Project environments provide **reproducibility**. By checking a project environment into version control—e.g. a git repository—along with the rest of the project's source code, you can reproduce the exact state of the project and all of its dependencies. The manifest file, in particular, captures the exact version of every dependency, identified by a cryptographic hash of its source tree, which makes it possible for `Pkg` to retrieve the correct versions and be sure that you are running the exact code that was recorded for all dependencies.
* Package directories provide **convenience** when a full carefully-tracked project environment is unnecessary. They are useful when you want to put a set of packages somewhere and be able to directly use them, without needing to create a project environment for them.
* Stacked environments allow for **adding** tools to the primary environment. You can push an environment of development tools onto the end of the stack to make them available from the REPL and scripts, but not from inside packages.
At a high-level, each environment conceptually defines three maps: roots, graph and paths. When resolving the meaning of `import X`, the roots and graph maps are used to determine the identity of `X`, while the paths map is used to locate the source code of `X`. The specific roles of the three maps are:
* **roots:** `name::Symbol` ⟶ `uuid::UUID`
An environment's roots map assigns package names to UUIDs for all the top-level dependencies that the environment makes available to the main project (i.e. the ones that can be loaded in `Main`). When Julia encounters `import X` in the main project, it looks up the identity of `X` as `roots[:X]`.
* **graph:** `context::UUID` ⟶ `name::Symbol` ⟶ `uuid::UUID`
An environment's graph is a multilevel map which assigns, for each `context` UUID, a map from names to UUIDs, similar to the roots map but specific to that `context`. When Julia sees `import X` in the code of the package whose UUID is `context`, it looks up the identity of `X` as `graph[context][:X]`. In particular, this means that `import X` can refer to different packages depending on `context`.
* **paths:** `uuid::UUID` × `name::Symbol` ⟶ `path::String`
The paths map assigns to each package UUID-name pair, the location of that package's entry-point source file. After the identity of `X` in `import X` has been resolved to a UUID via roots or graph (depending on whether it is loaded from the main project or a dependency), Julia determines what file to load to acquire `X` by looking up `paths[uuid,:X]` in the environment. Including this file should define a module named `X`. Once this package is loaded, any subsequent import resolving to the same `uuid` will create a new binding to the already-loaded package module.
Each kind of environment defines these three maps differently, as detailed in the following sections.
For ease of understanding, the examples throughout this chapter show full data structures for roots, graph and paths. However, Julia's package loading code does not explicitly create these. Instead, it lazily computes only as much of each structure as it needs to load a given package.
###
[Project environments](#Project-environments)
A project environment is determined by a directory containing a project file called `Project.toml`, and optionally a manifest file called `Manifest.toml`. These files may also be called `JuliaProject.toml` and `JuliaManifest.toml`, in which case `Project.toml` and `Manifest.toml` are ignored. This allows for coexistence with other tools that might consider files called `Project.toml` and `Manifest.toml` significant. For pure Julia projects, however, the names `Project.toml` and `Manifest.toml` are preferred.
The roots, graph and paths maps of a project environment are defined as follows:
**The roots map** of the environment is determined by the contents of the project file, specifically, its top-level `name` and `uuid` entries and its `[deps]` section (all optional). Consider the following example project file for the hypothetical application, `App`, as described earlier:
```
name = "App"
uuid = "8f986787-14fe-4607-ba5d-fbff2944afa9"
[deps]
Priv = "ba13f791-ae1d-465a-978b-69c3ad90f72b"
Pub = "c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"
```
This project file implies the following roots map, if it was represented by a Julia dictionary:
```
roots = Dict(
:App => UUID("8f986787-14fe-4607-ba5d-fbff2944afa9"),
:Priv => UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b"),
:Pub => UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"),
)
```
Given this roots map, in `App`'s code the statement `import Priv` will cause Julia to look up `roots[:Priv]`, which yields `ba13f791-ae1d-465a-978b-69c3ad90f72b`, the UUID of the `Priv` package that is to be loaded in that context. This UUID identifies which `Priv` package to load and use when the main application evaluates `import Priv`.
**The dependency graph** of a project environment is determined by the contents of the manifest file, if present. If there is no manifest file, graph is empty. A manifest file contains a stanza for each of a project's direct or indirect dependencies. For each dependency, the file lists the package's UUID and a source tree hash or an explicit path to the source code. Consider the following example manifest file for `App`:
```
[[Priv]] # the private one
deps = ["Pub", "Zebra"]
uuid = "ba13f791-ae1d-465a-978b-69c3ad90f72b"
path = "deps/Priv"
[[Priv]] # the public one
uuid = "2d15fe94-a1f7-436c-a4d8-07a9a496e01c"
git-tree-sha1 = "1bf63d3be994fe83456a03b874b409cfd59a6373"
version = "0.1.5"
[[Pub]]
uuid = "c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"
git-tree-sha1 = "9ebd50e2b0dd1e110e842df3b433cb5869b0dd38"
version = "2.1.4"
[Pub.deps]
Priv = "2d15fe94-a1f7-436c-a4d8-07a9a496e01c"
Zebra = "f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"
[[Zebra]]
uuid = "f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"
git-tree-sha1 = "e808e36a5d7173974b90a15a353b564f3494092f"
version = "3.4.2"
```
This manifest file describes a possible complete dependency graph for the `App` project:
* There are two different packages named `Priv` that the application uses. It uses a private package, which is a root dependency, and a public one, which is an indirect dependency through `Pub`. These are differentiated by their distinct UUIDs, and they have different deps:
+ The private `Priv` depends on the `Pub` and `Zebra` packages.
+ The public `Priv` has no dependencies.
* The application also depends on the `Pub` package, which in turn depends on the public `Priv` and the same `Zebra` package that the private `Priv` package depends on.
This dependency graph represented as a dictionary, looks like this:
```
graph = Dict(
# Priv – the private one:
UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b") => Dict(
:Pub => UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"),
:Zebra => UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"),
),
# Priv – the public one:
UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c") => Dict(),
# Pub:
UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1") => Dict(
:Priv => UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c"),
:Zebra => UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"),
),
# Zebra:
UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62") => Dict(),
)
```
Given this dependency `graph`, when Julia sees `import Priv` in the `Pub` package—which has UUID `c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1`—it looks up:
```
graph[UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1")][:Priv]
```
and gets `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`, which indicates that in the context of the `Pub` package, `import Priv` refers to the public `Priv` package, rather than the private one which the app depends on directly. This is how the name `Priv` can refer to different packages in the main project than it does in one of its package's dependencies, which allows for duplicate names in the package ecosystem.
What happens if `import Zebra` is evaluated in the main `App` code base? Since `Zebra` does not appear in the project file, the import will fail even though `Zebra` *does* appear in the manifest file. Moreover, if `import Zebra` occurs in the public `Priv` package—the one with UUID `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`—then that would also fail since that `Priv` package has no declared dependencies in the manifest file and therefore cannot load any packages. The `Zebra` package can only be loaded by packages for which it appear as an explicit dependency in the manifest file: the `Pub` package and one of the `Priv` packages.
**The paths map** of a project environment is extracted from the manifest file. The path of a package `uuid` named `X` is determined by these rules (in order):
1. If the project file in the directory matches `uuid` and name `X`, then either:
* It has a toplevel `path` entry, then `uuid` will be mapped to that path, interpreted relative to the directory containing the project file.
* Otherwise, `uuid` is mapped to `src/X.jl` relative to the directory containing the project file.
2. If the above is not the case and the project file has a corresponding manifest file and the manifest contains a stanza matching `uuid` then:
* If it has a `path` entry, use that path (relative to the directory containing the manifest file).
* If it has a `git-tree-sha1` entry, compute a deterministic hash function of `uuid` and `git-tree-sha1`—call it `slug`—and look for a directory named `packages/X/$slug` in each directory in the Julia `DEPOT_PATH` global array. Use the first such directory that exists.
If any of these result in success, the path to the source code entry point will be either that result, the relative path from that result plus `src/X.jl`; otherwise, there is no path mapping for `uuid`. When loading `X`, if no source code path is found, the lookup will fail, and the user may be prompted to install the appropriate package version or to take other corrective action (e.g. declaring `X` as a dependency).
In the example manifest file above, to find the path of the first `Priv` package—the one with UUID `ba13f791-ae1d-465a-978b-69c3ad90f72b`—Julia looks for its stanza in the manifest file, sees that it has a `path` entry, looks at `deps/Priv` relative to the `App` project directory—let's suppose the `App` code lives in `/home/me/projects/App`—sees that `/home/me/projects/App/deps/Priv` exists and therefore loads `Priv` from there.
If, on the other hand, Julia was loading the *other* `Priv` package—the one with UUID `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`—it finds its stanza in the manifest, see that it does *not* have a `path` entry, but that it does have a `git-tree-sha1` entry. It then computes the `slug` for this UUID/SHA-1 pair, which is `HDkrT` (the exact details of this computation aren't important, but it is consistent and deterministic). This means that the path to this `Priv` package will be `packages/Priv/HDkrT/src/Priv.jl` in one of the package depots. Suppose the contents of `DEPOT_PATH` is `["/home/me/.julia", "/usr/local/julia"]`, then Julia will look at the following paths to see if they exist:
1. `/home/me/.julia/packages/Priv/HDkrT`
2. `/usr/local/julia/packages/Priv/HDkrT`
Julia uses the first of these that exists to try to load the public `Priv` package from the file `packages/Priv/HDKrT/src/Priv.jl` in the depot where it was found.
Here is a representation of a possible paths map for our example `App` project environment, as provided in the Manifest given above for the dependency graph, after searching the local file system:
```
paths = Dict(
# Priv – the private one:
(UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b"), :Priv) =>
# relative entry-point inside `App` repo:
"/home/me/projects/App/deps/Priv/src/Priv.jl",
# Priv – the public one:
(UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c"), :Priv) =>
# package installed in the system depot:
"/usr/local/julia/packages/Priv/HDkr/src/Priv.jl",
# Pub:
(UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"), :Pub) =>
# package installed in the user depot:
"/home/me/.julia/packages/Pub/oKpw/src/Pub.jl",
# Zebra:
(UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"), :Zebra) =>
# package installed in the system depot:
"/usr/local/julia/packages/Zebra/me9k/src/Zebra.jl",
)
```
This example map includes three different kinds of package locations (the first and third are part of the default load path):
1. The private `Priv` package is "[vendored](https://stackoverflow.com/a/35109534)" inside the `App` repository.
2. The public `Priv` and `Zebra` packages are in the system depot, where packages installed and managed by the system administrator live. These are available to all users on the system.
3. The `Pub` package is in the user depot, where packages installed by the user live. These are only available to the user who installed them.
###
[Package directories](#Package-directories)
Package directories provide a simpler kind of environment without the ability to handle name collisions. In a package directory, the set of top-level packages is the set of subdirectories that "look like" packages. A package `X` exists in a package directory if the directory contains one of the following "entry point" files:
* `X.jl`
* `X/src/X.jl`
* `X.jl/src/X.jl`
Which dependencies a package in a package directory can import depends on whether the package contains a project file:
* If it has a project file, it can only import those packages which are identified in the `[deps]` section of the project file.
* If it does not have a project file, it can import any top-level package—i.e. the same packages that can be loaded in `Main` or the REPL.
**The roots map** is determined by examining the contents of the package directory to generate a list of all packages that exist. Additionally, a UUID will be assigned to each entry as follows: For a given package found inside the folder `X`...
1. If `X/Project.toml` exists and has a `uuid` entry, then `uuid` is that value.
2. If `X/Project.toml` exists and but does *not* have a top-level UUID entry, `uuid` is a dummy UUID generated by hashing the canonical (real) path to `X/Project.toml`.
3. Otherwise (if `Project.toml` does not exist), then `uuid` is the all-zero [nil UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Nil_UUID).
**The dependency graph** of a project directory is determined by the presence and contents of project files in the subdirectory of each package. The rules are:
* If a package subdirectory has no project file, then it is omitted from graph and import statements in its code are treated as top-level, the same as the main project and REPL.
* If a package subdirectory has a project file, then the graph entry for its UUID is the `[deps]` map of the project file, which is considered to be empty if the section is absent.
As an example, suppose a package directory has the following structure and content:
```
Aardvark/
src/Aardvark.jl:
import Bobcat
import Cobra
Bobcat/
Project.toml:
[deps]
Cobra = "4725e24d-f727-424b-bca0-c4307a3456fa"
Dingo = "7a7925be-828c-4418-bbeb-bac8dfc843bc"
src/Bobcat.jl:
import Cobra
import Dingo
Cobra/
Project.toml:
uuid = "4725e24d-f727-424b-bca0-c4307a3456fa"
[deps]
Dingo = "7a7925be-828c-4418-bbeb-bac8dfc843bc"
src/Cobra.jl:
import Dingo
Dingo/
Project.toml:
uuid = "7a7925be-828c-4418-bbeb-bac8dfc843bc"
src/Dingo.jl:
# no imports
```
Here is a corresponding roots structure, represented as a dictionary:
```
roots = Dict(
:Aardvark => UUID("00000000-0000-0000-0000-000000000000"), # no project file, nil UUID
:Bobcat => UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf"), # dummy UUID based on path
:Cobra => UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), # UUID from project file
:Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), # UUID from project file
)
```
Here is the corresponding graph structure, represented as a dictionary:
```
graph = Dict(
# Bobcat:
UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf") => Dict(
:Cobra => UUID("4725e24d-f727-424b-bca0-c4307a3456fa"),
:Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"),
),
# Cobra:
UUID("4725e24d-f727-424b-bca0-c4307a3456fa") => Dict(
:Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"),
),
# Dingo:
UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc") => Dict(),
)
```
A few general rules to note:
1. A package without a project file can depend on any top-level dependency, and since every package in a package directory is available at the top-level, it can import all packages in the environment.
2. A package with a project file cannot depend on one without a project file since packages with project files can only load packages in `graph` and packages without project files do not appear in `graph`.
3. A package with a project file but no explicit UUID can only be depended on by packages without project files since dummy UUIDs assigned to these packages are strictly internal.
Observe the following specific instances of these rules in our example:
* `Aardvark` can import on any of `Bobcat`, `Cobra` or `Dingo`; it does import `Bobcat` and `Cobra`.
* `Bobcat` can and does import both `Cobra` and `Dingo`, which both have project files with UUIDs and are declared as dependencies in `Bobcat`'s `[deps]` section.
* `Bobcat` cannot depend on `Aardvark` since `Aardvark` does not have a project file.
* `Cobra` can and does import `Dingo`, which has a project file and UUID, and is declared as a dependency in `Cobra`'s `[deps]` section.
* `Cobra` cannot depend on `Aardvark` or `Bobcat` since neither have real UUIDs.
* `Dingo` cannot import anything because it has a project file without a `[deps]` section.
**The paths map** in a package directory is simple: it maps subdirectory names to their corresponding entry-point paths. In other words, if the path to our example project directory is `/home/me/animals` then the `paths` map could be represented by this dictionary:
```
paths = Dict(
(UUID("00000000-0000-0000-0000-000000000000"), :Aardvark) =>
"/home/me/AnimalPackages/Aardvark/src/Aardvark.jl",
(UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf"), :Bobcat) =>
"/home/me/AnimalPackages/Bobcat/src/Bobcat.jl",
(UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), :Cobra) =>
"/home/me/AnimalPackages/Cobra/src/Cobra.jl",
(UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), :Dingo) =>
"/home/me/AnimalPackages/Dingo/src/Dingo.jl",
)
```
Since all packages in a package directory environment are, by definition, subdirectories with the expected entry-point files, their `paths` map entries always have this form.
###
[Environment stacks](#Environment-stacks)
The third and final kind of environment is one that combines other environments by overlaying several of them, making the packages in each available in a single composite environment. These composite environments are called *environment stacks*. The Julia `LOAD_PATH` global defines an environment stack—the environment in which the Julia process operates. If you want your Julia process to have access only to the packages in one project or package directory, make it the only entry in `LOAD_PATH`. It is often quite useful, however, to have access to some of your favorite tools—standard libraries, profilers, debuggers, personal utilities, etc.—even if they are not dependencies of the project you're working on. By adding an environment containing these tools to the load path, you immediately have access to them in top-level code without needing to add them to your project.
The mechanism for combining the roots, graph and paths data structures of the components of an environment stack is simple: they are merged as dictionaries, favoring earlier entries over later ones in the case of key collisions. In other words, if we have `stack = [env₁, env₂, …]` then we have:
```
roots = reduce(merge, reverse([roots₁, roots₂, …]))
graph = reduce(merge, reverse([graph₁, graph₂, …]))
paths = reduce(merge, reverse([paths₁, paths₂, …]))
```
The subscripted `rootsᵢ`, `graphᵢ` and `pathsᵢ` variables correspond to the subscripted environments, `envᵢ`, contained in `stack`. The `reverse` is present because `merge` favors the last argument rather than first when there are collisions between keys in its argument dictionaries. There are a couple of noteworthy features of this design:
1. The *primary environment*—i.e. the first environment in a stack—is faithfully embedded in a stacked environment. The full dependency graph of the first environment in a stack is guaranteed to be included intact in the stacked environment including the same versions of all dependencies.
2. Packages in non-primary environments can end up using incompatible versions of their dependencies even if their own environments are entirely compatible. This can happen when one of their dependencies is shadowed by a version in an earlier environment in the stack (either by graph or path, or both).
Since the primary environment is typically the environment of a project you're working on, while environments later in the stack contain additional tools, this is the right trade-off: it's better to break your development tools but keep the project working. When such incompatibilities occur, you'll typically want to upgrade your dev tools to versions that are compatible with the main project.
###
[Package/Environment Preferences](#Package/Environment-Preferences)
Preferences are dictionaries of metadata that influence package behavior within an environment. The preferences system supports reading preferences at compile-time, which means that at code-loading time, we must ensure that a particular `.ji` file was built with the same preferences as the current environment before loading it. The public API for modifying Preferences is contained within the [Preferences.jl](https://github.com/JuliaPackaging/Preferences.jl) package. Preferences are stored as TOML dictionaries within a `(Julia)LocalPreferences.toml` file next to the currently-active project. If a preference is "exported", it is instead stored within the `(Julia)Project.toml` instead. The intention is to allow shared projects to contain shared preferences, while allowing for users themselves to override those preferences with their own settings in the LocalPreferences.toml file, which should be .gitignored as the name implies.
Preferences that are accessed during compilation are automatically marked as compile-time preferences, and any change recorded to these preferences will cause the Julia compiler to recompile any cached precompilation `.ji` files for that module. This is done by serializing the hash of all compile-time preferences during compilation, then checking that hash against the current environment when searching for the proper `.ji` file to load.
Preferences can be set with depot-wide defaults; if package Foo is installed within your global environment and it has preferences set, these preferences will apply as long as your global environment is part of your `LOAD_PATH`. Preferences in environments higher up in the environment stack get overridden by the more proximal entries in the load path, ending with the currently active project. This allows depot-wide preference defaults to exist, with active projects able to merge or even completely overwrite these inherited preferences. See the docstring for `Preferences.set_preferences!()` for the full details of how to set preferences to allow or disallow merging.
[Conclusion](#Conclusion)
--------------------------
Federated package management and precise software reproducibility are difficult but worthy goals in a package system. In combination, these goals lead to a more complex package loading mechanism than most dynamic languages have, but it also yields scalability and reproducibility that is more commonly associated with static languages. Typically, Julia users should be able to use the built-in package manager to manage their projects without needing a precise understanding of these interactions. A call to `Pkg.add("X")` will add to the appropriate project and manifest files, selected via `Pkg.activate("Y")`, so that a future call to `import X` will load `X` without further thought.
| programming_docs |
julia Style Guide Style Guide
===========
The following sections explain a few aspects of idiomatic Julia coding style. None of these rules are absolute; they are only suggestions to help familiarize you with the language and to help you choose among alternative designs.
[Indentation](#Indentation)
----------------------------
Use 4 spaces per indentation level.
[Write functions, not just scripts](#Write-functions,-not-just-scripts)
------------------------------------------------------------------------
Writing code as a series of steps at the top level is a quick way to get started solving a problem, but you should try to divide a program into functions as soon as possible. Functions are more reusable and testable, and clarify what steps are being done and what their inputs and outputs are. Furthermore, code inside functions tends to run much faster than top level code, due to how Julia's compiler works.
It is also worth emphasizing that functions should take arguments, instead of operating directly on global variables (aside from constants like [`pi`](../../base/numbers/index#Base.MathConstants.pi)).
[Avoid writing overly-specific types](#Avoid-writing-overly-specific-types)
----------------------------------------------------------------------------
Code should be as generic as possible. Instead of writing:
```
Complex{Float64}(x)
```
it's better to use available generic functions:
```
complex(float(x))
```
The second version will convert `x` to an appropriate type, instead of always the same type.
This style point is especially relevant to function arguments. For example, don't declare an argument to be of type `Int` or [`Int32`](../../base/numbers/index#Core.Int32) if it really could be any integer, expressed with the abstract type [`Integer`](../../base/numbers/index#Core.Integer). In fact, in many cases you can omit the argument type altogether, unless it is needed to disambiguate from other method definitions, since a [`MethodError`](../../base/base/index#Core.MethodError) will be thrown anyway if a type is passed that does not support any of the requisite operations. (This is known as [duck typing](https://en.wikipedia.org/wiki/Duck_typing).)
For example, consider the following definitions of a function `addone` that returns one plus its argument:
```
addone(x::Int) = x + 1 # works only for Int
addone(x::Integer) = x + oneunit(x) # any integer type
addone(x::Number) = x + oneunit(x) # any numeric type
addone(x) = x + oneunit(x) # any type supporting + and oneunit
```
The last definition of `addone` handles any type supporting [`oneunit`](../../base/numbers/index#Base.oneunit) (which returns 1 in the same type as `x`, which avoids unwanted type promotion) and the [`+`](../../base/math/index#Base.:+) function with those arguments. The key thing to realize is that there is *no performance penalty* to defining *only* the general `addone(x) = x + oneunit(x)`, because Julia will automatically compile specialized versions as needed. For example, the first time you call `addone(12)`, Julia will automatically compile a specialized `addone` function for `x::Int` arguments, with the call to `oneunit` replaced by its inlined value `1`. Therefore, the first three definitions of `addone` above are completely redundant with the fourth definition.
[Handle excess argument diversity in the caller](#Handle-excess-argument-diversity-in-the-caller)
--------------------------------------------------------------------------------------------------
Instead of:
```
function foo(x, y)
x = Int(x); y = Int(y)
...
end
foo(x, y)
```
use:
```
function foo(x::Int, y::Int)
...
end
foo(Int(x), Int(y))
```
This is better style because `foo` does not really accept numbers of all types; it really needs `Int` s.
One issue here is that if a function inherently requires integers, it might be better to force the caller to decide how non-integers should be converted (e.g. floor or ceiling). Another issue is that declaring more specific types leaves more "space" for future method definitions.
[Append `!` to names of functions that modify their arguments](#bang-convention)
---------------------------------------------------------------------------------
Instead of:
```
function double(a::AbstractArray{<:Number})
for i = firstindex(a):lastindex(a)
a[i] *= 2
end
return a
end
```
use:
```
function double!(a::AbstractArray{<:Number})
for i = firstindex(a):lastindex(a)
a[i] *= 2
end
return a
end
```
Julia Base uses this convention throughout and contains examples of functions with both copying and modifying forms (e.g., [`sort`](../../base/sort/index#Base.sort) and [`sort!`](../../base/sort/index#Base.sort!)), and others which are just modifying (e.g., [`push!`](../../base/collections/index#Base.push!), [`pop!`](../../base/collections/index#Base.pop!), [`splice!`](../../base/collections/index#Base.splice!)). It is typical for such functions to also return the modified array for convenience.
[Avoid strange type `Union`s](#Avoid-strange-type-Unions)
----------------------------------------------------------
Types such as `Union{Function,AbstractString}` are often a sign that some design could be cleaner.
[Avoid elaborate container types](#Avoid-elaborate-container-types)
--------------------------------------------------------------------
It is usually not much help to construct arrays like the following:
```
a = Vector{Union{Int,AbstractString,Tuple,Array}}(undef, n)
```
In this case `Vector{Any}(undef, n)` is better. It is also more helpful to the compiler to annotate specific uses (e.g. `a[i]::Int`) than to try to pack many alternatives into one type.
[Prefer exported methods over direct field access](#Prefer-exported-methods-over-direct-field-access)
------------------------------------------------------------------------------------------------------
Idiomatic Julia code should generally treat a module's exported methods as the interface to its types. An object's fields are generally considered implementation details and user code should only access them directly if this is stated to be the API. This has several benefits:
* Package developers are freer to change the implementation without breaking user code.
* Methods can be passed to higher-order constructs like [`map`](../../base/collections/index#Base.map) (e.g. `map(imag, zs)`) rather than `[z.im for z in zs]`).
* Methods can be defined on abstract types.
* Methods can describe a conceptual operation that can be shared across disparate types (e.g. `real(z)` works on Complex numbers or Quaternions).
Julia's dispatch system encourages this style because `play(x::MyType)` only defines the `play` method on that particular type, leaving other types to have their own implementation.
Similarly, non-exported functions are typically internal and subject to change, unless the documentations states otherwise. Names sometimes are given a `_` prefix (or suffix) to further suggest that something is "internal" or an implementation-detail, but it is not a rule.
Counter-examples to this rule include [`NamedTuple`](../../base/base/index#Core.NamedTuple), [`RegexMatch`](../../base/strings/index#Base.match), [`StatStruct`](../../base/file/index#Base.stat).
[Use naming conventions consistent with Julia `base/`](#Use-naming-conventions-consistent-with-Julia-base/)
------------------------------------------------------------------------------------------------------------
* modules and type names use capitalization and camel case: `module SparseArrays`, `struct UnitRange`.
* functions are lowercase ([`maximum`](../../base/collections/index#Base.maximum), [`convert`](../../base/base/index#Base.convert)) and, when readable, with multiple words squashed together ([`isequal`](../../base/base/index#Base.isequal), [`haskey`](../../base/collections/index#Base.haskey)). When necessary, use underscores as word separators. Underscores are also used to indicate a combination of concepts ([`remotecall_fetch`](#) as a more efficient implementation of `fetch(remotecall(...))`) or as modifiers.
* functions mutating at least one of their arguments end in `!`.
* conciseness is valued, but avoid abbreviation ([`indexin`](../../base/collections/index#Base.indexin) rather than `indxin`) as it becomes difficult to remember whether and how particular words are abbreviated.
If a function name requires multiple words, consider whether it might represent more than one concept and might be better split into pieces.
[Write functions with argument ordering similar to Julia Base](#Write-functions-with-argument-ordering-similar-to-Julia-Base)
------------------------------------------------------------------------------------------------------------------------------
As a general rule, the Base library uses the following order of arguments to functions, as applicable:
1. **Function argument**. Putting a function argument first permits the use of [`do`](../../base/base/index#do) blocks for passing multiline anonymous functions.
2. **I/O stream**. Specifying the `IO` object first permits passing the function to functions such as [`sprint`](../../base/io-network/index#Base.sprint), e.g. `sprint(show, x)`.
3. **Input being mutated**. For example, in [`fill!(x, v)`](../../base/arrays/index#Base.fill!), `x` is the object being mutated and it appears before the value to be inserted into `x`.
4. **Type**. Passing a type typically means that the output will have the given type. In [`parse(Int, "1")`](../../base/numbers/index#Base.parse), the type comes before the string to parse. There are many such examples where the type appears first, but it's useful to note that in [`read(io, String)`](../../base/io-network/index#Base.read), the `IO` argument appears before the type, which is in keeping with the order outlined here.
5. **Input not being mutated**. In `fill!(x, v)`, `v` is *not* being mutated and it comes after `x`.
6. **Key**. For associative collections, this is the key of the key-value pair(s). For other indexed collections, this is the index.
7. **Value**. For associative collections, this is the value of the key-value pair(s). In cases like [`fill!(x, v)`](../../base/arrays/index#Base.fill!), this is `v`.
8. **Everything else**. Any other arguments.
9. **Varargs**. This refers to arguments that can be listed indefinitely at the end of a function call. For example, in `Matrix{T}(undef, dims)`, the dimensions can be given as a [`Tuple`](../../base/base/index#Core.Tuple), e.g. `Matrix{T}(undef, (1,2))`, or as [`Vararg`](../../base/base/index#Core.Vararg)s, e.g. `Matrix{T}(undef, 1, 2)`.
10. **Keyword arguments**. In Julia keyword arguments have to come last anyway in function definitions; they're listed here for the sake of completeness.
The vast majority of functions will not take every kind of argument listed above; the numbers merely denote the precedence that should be used for any applicable arguments to a function.
There are of course a few exceptions. For example, in [`convert`](../../base/base/index#Base.convert), the type should always come first. In [`setindex!`](../../base/collections/index#Base.setindex!), the value comes before the indices so that the indices can be provided as varargs.
When designing APIs, adhering to this general order as much as possible is likely to give users of your functions a more consistent experience.
[Don't overuse try-catch](#Don't-overuse-try-catch)
----------------------------------------------------
It is better to avoid errors than to rely on catching them.
[Don't parenthesize conditions](#Don't-parenthesize-conditions)
----------------------------------------------------------------
Julia doesn't require parens around conditions in `if` and `while`. Write:
```
if a == b
```
instead of:
```
if (a == b)
```
[Don't overuse `...`](#Don't-overuse-...)
------------------------------------------
Splicing function arguments can be addictive. Instead of `[a..., b...]`, use simply `[a; b]`, which already concatenates arrays. [`collect(a)`](#) is better than `[a...]`, but since `a` is already iterable it is often even better to leave it alone, and not convert it to an array.
[Don't use unnecessary static parameters](#Don't-use-unnecessary-static-parameters)
------------------------------------------------------------------------------------
A function signature:
```
foo(x::T) where {T<:Real} = ...
```
should be written as:
```
foo(x::Real) = ...
```
instead, especially if `T` is not used in the function body. Even if `T` is used, it can be replaced with [`typeof(x)`](../../base/base/index#Core.typeof) if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.
Note also that container types, specifically may need type parameters in function calls. See the FAQ [Avoid fields with abstract containers](../performance-tips/index#Avoid-fields-with-abstract-containers) for more information.
[Avoid confusion about whether something is an instance or a type](#Avoid-confusion-about-whether-something-is-an-instance-or-a-type)
--------------------------------------------------------------------------------------------------------------------------------------
Sets of definitions like the following are confusing:
```
foo(::Type{MyType}) = ...
foo(::MyType) = foo(MyType)
```
Decide whether the concept in question will be written as `MyType` or `MyType()`, and stick to it.
The preferred style is to use instances by default, and only add methods involving `Type{MyType}` later if they become necessary to solve some problems.
If a type is effectively an enumeration, it should be defined as a single (ideally immutable struct or primitive) type, with the enumeration values being instances of it. Constructors and conversions can check whether values are valid. This design is preferred over making the enumeration an abstract type, with the "values" as subtypes.
[Don't overuse macros](#Don't-overuse-macros)
----------------------------------------------
Be aware of when a macro could really be a function instead.
Calling [`eval`](../../base/base/index#Base.MainInclude.eval) inside a macro is a particularly dangerous warning sign; it means the macro will only work when called at the top level. If such a macro is written as a function instead, it will naturally have access to the run-time values it needs.
[Don't expose unsafe operations at the interface level](#Don't-expose-unsafe-operations-at-the-interface-level)
----------------------------------------------------------------------------------------------------------------
If you have a type that uses a native pointer:
```
mutable struct NativeType
p::Ptr{UInt8}
...
end
```
don't write definitions like the following:
```
getindex(x::NativeType, i) = unsafe_load(x.p, i)
```
The problem is that users of this type can write `x[i]` without realizing that the operation is unsafe, and then be susceptible to memory bugs.
Such a function should either check the operation to ensure it is safe, or have `unsafe` somewhere in its name to alert callers.
[Don't overload methods of base container types](#Don't-overload-methods-of-base-container-types)
--------------------------------------------------------------------------------------------------
It is possible to write definitions like the following:
```
show(io::IO, v::Vector{MyType}) = ...
```
This would provide custom showing of vectors with a specific new element type. While tempting, this should be avoided. The trouble is that users will expect a well-known type like `Vector()` to behave in a certain way, and overly customizing its behavior can make it harder to work with.
[Avoid type piracy](#Avoid-type-piracy)
----------------------------------------
"Type piracy" refers to the practice of extending or redefining methods in Base or other packages on types that you have not defined. In extreme cases, you can crash Julia (e.g. if your method extension or redefinition causes invalid input to be passed to a `ccall`). Type piracy can complicate reasoning about code, and may introduce incompatibilities that are hard to predict and diagnose.
As an example, suppose you wanted to define multiplication on symbols in a module:
```
module A
import Base.*
*(x::Symbol, y::Symbol) = Symbol(x,y)
end
```
The problem is that now any other module that uses `Base.*` will also see this definition. Since `Symbol` is defined in Base and is used by other modules, this can change the behavior of unrelated code unexpectedly. There are several alternatives here, including using a different function name, or wrapping the `Symbol`s in another type that you define.
Sometimes, coupled packages may engage in type piracy to separate features from definitions, especially when the packages were designed by collaborating authors, and when the definitions are reusable. For example, one package might provide some types useful for working with colors; another package could define methods for those types that enable conversions between color spaces. Another example might be a package that acts as a thin wrapper for some C code, which another package might then pirate to implement a higher-level, Julia-friendly API.
[Be careful with type equality](#Be-careful-with-type-equality)
----------------------------------------------------------------
You generally want to use [`isa`](../../base/base/index#Core.isa) and [`<:`](#) for testing types, not `==`. Checking types for exact equality typically only makes sense when comparing to a known concrete type (e.g. `T == Float64`), or if you *really, really* know what you're doing.
[Do not write `x->f(x)`](#Do-not-write-x-f(x))
-----------------------------------------------
Since higher-order functions are often called with anonymous functions, it is easy to conclude that this is desirable or even necessary. But any function can be passed directly, without being "wrapped" in an anonymous function. Instead of writing `map(x->f(x), a)`, write [`map(f, a)`](../../base/collections/index#Base.map).
[Avoid using floats for numeric literals in generic code when possible](#Avoid-using-floats-for-numeric-literals-in-generic-code-when-possible)
------------------------------------------------------------------------------------------------------------------------------------------------
If you write generic code which handles numbers, and which can be expected to run with many different numeric type arguments, try using literals of a numeric type that will affect the arguments as little as possible through promotion.
For example,
```
julia> f(x) = 2.0 * x
f (generic function with 1 method)
julia> f(1//2)
1.0
julia> f(1/2)
1.0
julia> f(1)
2.0
```
while
```
julia> g(x) = 2 * x
g (generic function with 1 method)
julia> g(1//2)
1//1
julia> g(1/2)
1.0
julia> g(1)
2
```
As you can see, the second version, where we used an `Int` literal, preserved the type of the input argument, while the first didn't. This is because e.g. `promote_type(Int, Float64) == Float64`, and promotion happens with the multiplication. Similarly, [`Rational`](../../base/numbers/index#Base.Rational) literals are less type disruptive than [`Float64`](../../base/numbers/index#Core.Float64) literals, but more disruptive than `Int`s:
```
julia> h(x) = 2//1 * x
h (generic function with 1 method)
julia> h(1//2)
1//1
julia> h(1/2)
1.0
julia> h(1)
2//1
```
Thus, use `Int` literals when possible, with `Rational{Int}` for literal non-integer numbers, in order to make it easier to use your code.
julia Networking and Streams Networking and Streams
======================
Julia provides a rich interface to deal with streaming I/O objects such as terminals, pipes and TCP sockets. This interface, though asynchronous at the system level, is presented in a synchronous manner to the programmer and it is usually unnecessary to think about the underlying asynchronous operation. This is achieved by making heavy use of Julia cooperative threading ([coroutine](../control-flow/index#man-tasks)) functionality.
[Basic Stream I/O](#Basic-Stream-I/O)
--------------------------------------
All Julia streams expose at least a [`read`](../../base/io-network/index#Base.read) and a [`write`](../../base/io-network/index#Base.write) method, taking the stream as their first argument, e.g.:
```
julia> write(stdout, "Hello World"); # suppress return value 11 with ;
Hello World
julia> read(stdin, Char)
'\n': ASCII/Unicode U+000a (category Cc: Other, control)
```
Note that [`write`](../../base/io-network/index#Base.write) returns 11, the number of bytes (in `"Hello World"`) written to [`stdout`](../../base/io-network/index#Base.stdout), but this return value is suppressed with the `;`.
Here Enter was pressed again so that Julia would read the newline. Now, as you can see from this example, [`write`](../../base/io-network/index#Base.write) takes the data to write as its second argument, while [`read`](../../base/io-network/index#Base.read) takes the type of the data to be read as the second argument.
For example, to read a simple byte array, we could do:
```
julia> x = zeros(UInt8, 4)
4-element Array{UInt8,1}:
0x00
0x00
0x00
0x00
julia> read!(stdin, x)
abcd
4-element Array{UInt8,1}:
0x61
0x62
0x63
0x64
```
However, since this is slightly cumbersome, there are several convenience methods provided. For example, we could have written the above as:
```
julia> read(stdin, 4)
abcd
4-element Array{UInt8,1}:
0x61
0x62
0x63
0x64
```
or if we had wanted to read the entire line instead:
```
julia> readline(stdin)
abcd
"abcd"
```
Note that depending on your terminal settings, your TTY may be line buffered and might thus require an additional enter before the data is sent to Julia.
To read every line from [`stdin`](../../base/io-network/index#Base.stdin) you can use [`eachline`](../../base/io-network/index#Base.eachline):
```
for line in eachline(stdin)
print("Found $line")
end
```
or [`read`](../../base/io-network/index#Base.read) if you wanted to read by character instead:
```
while !eof(stdin)
x = read(stdin, Char)
println("Found: $x")
end
```
[Text I/O](#Text-I/O)
----------------------
Note that the [`write`](../../base/io-network/index#Base.write) method mentioned above operates on binary streams. In particular, values do not get converted to any canonical text representation but are written out as is:
```
julia> write(stdout, 0x61); # suppress return value 1 with ;
a
```
Note that `a` is written to [`stdout`](../../base/io-network/index#Base.stdout) by the [`write`](../../base/io-network/index#Base.write) function and that the returned value is `1` (since `0x61` is one byte).
For text I/O, use the [`print`](../../base/io-network/index#Base.print) or [`show`](#) methods, depending on your needs (see the documentation for these two methods for a detailed discussion of the difference between them):
```
julia> print(stdout, 0x61)
97
```
See [Custom pretty-printing](../types/index#man-custom-pretty-printing) for more information on how to implement display methods for custom types.
[IO Output Contextual Properties](#IO-Output-Contextual-Properties)
--------------------------------------------------------------------
Sometimes IO output can benefit from the ability to pass contextual information into show methods. The [`IOContext`](../../base/io-network/index#Base.IOContext) object provides this framework for associating arbitrary metadata with an IO object. For example, `:compact => true` adds a hinting parameter to the IO object that the invoked show method should print a shorter output (if applicable). See the [`IOContext`](../../base/io-network/index#Base.IOContext) documentation for a list of common properties.
[Working with Files](#Working-with-Files)
------------------------------------------
Like many other environments, Julia has an [`open`](../../base/io-network/index#Base.open) function, which takes a filename and returns an [`IOStream`](../../base/io-network/index#Base.IOStream) object that you can use to read and write things from the file. For example, if we have a file, `hello.txt`, whose contents are `Hello, World!`:
```
julia> f = open("hello.txt")
IOStream(<file hello.txt>)
julia> readlines(f)
1-element Array{String,1}:
"Hello, World!"
```
If you want to write to a file, you can open it with the write (`"w"`) flag:
```
julia> f = open("hello.txt","w")
IOStream(<file hello.txt>)
julia> write(f,"Hello again.")
12
```
If you examine the contents of `hello.txt` at this point, you will notice that it is empty; nothing has actually been written to disk yet. This is because the `IOStream` must be closed before the write is actually flushed to disk:
```
julia> close(f)
```
Examining `hello.txt` again will show its contents have been changed.
Opening a file, doing something to its contents, and closing it again is a very common pattern. To make this easier, there exists another invocation of [`open`](../../base/io-network/index#Base.open) which takes a function as its first argument and filename as its second, opens the file, calls the function with the file as an argument, and then closes it again. For example, given a function:
```
function read_and_capitalize(f::IOStream)
return uppercase(read(f, String))
end
```
You can call:
```
julia> open(read_and_capitalize, "hello.txt")
"HELLO AGAIN."
```
to open `hello.txt`, call `read_and_capitalize` on it, close `hello.txt` and return the capitalized contents.
To avoid even having to define a named function, you can use the `do` syntax, which creates an anonymous function on the fly:
```
julia> open("hello.txt") do f
uppercase(read(f, String))
end
"HELLO AGAIN."
```
[A simple TCP example](#A-simple-TCP-example)
----------------------------------------------
Let's jump right in with a simple example involving TCP sockets. This functionality is in a standard library package called `Sockets`. Let's first create a simple server:
```
julia> using Sockets
julia> errormonitor(@async begin
server = listen(2000)
while true
sock = accept(server)
println("Hello World\n")
end
end)
Task (runnable) @0x00007fd31dc11ae0
```
To those familiar with the Unix socket API, the method names will feel familiar, though their usage is somewhat simpler than the raw Unix socket API. The first call to [`listen`](#) will create a server waiting for incoming connections on the specified port (2000) in this case. The same function may also be used to create various other kinds of servers:
```
julia> listen(2000) # Listens on localhost:2000 (IPv4)
Sockets.TCPServer(active)
julia> listen(ip"127.0.0.1",2000) # Equivalent to the first
Sockets.TCPServer(active)
julia> listen(ip"::1",2000) # Listens on localhost:2000 (IPv6)
Sockets.TCPServer(active)
julia> listen(IPv4(0),2001) # Listens on port 2001 on all IPv4 interfaces
Sockets.TCPServer(active)
julia> listen(IPv6(0),2001) # Listens on port 2001 on all IPv6 interfaces
Sockets.TCPServer(active)
julia> listen("testsocket") # Listens on a UNIX domain socket
Sockets.PipeServer(active)
julia> listen("\\\\.\\pipe\\testsocket") # Listens on a Windows named pipe
Sockets.PipeServer(active)
```
Note that the return type of the last invocation is different. This is because this server does not listen on TCP, but rather on a named pipe (Windows) or UNIX domain socket. Also note that Windows named pipe format has to be a specific pattern such that the name prefix (`\\.\pipe\`) uniquely identifies the [file type](https://docs.microsoft.com/windows/desktop/ipc/pipe-names). The difference between TCP and named pipes or UNIX domain sockets is subtle and has to do with the [`accept`](../../stdlib/sockets/index#Sockets.accept) and [`connect`](#) methods. The [`accept`](../../stdlib/sockets/index#Sockets.accept) method retrieves a connection to the client that is connecting on the server we just created, while the [`connect`](#) function connects to a server using the specified method. The [`connect`](#) function takes the same arguments as [`listen`](#), so, assuming the environment (i.e. host, cwd, etc.) is the same you should be able to pass the same arguments to [`connect`](#) as you did to listen to establish the connection. So let's try that out (after having created the server above):
```
julia> connect(2000)
TCPSocket(open, 0 bytes waiting)
julia> Hello World
```
As expected we saw "Hello World" printed. So, let's actually analyze what happened behind the scenes. When we called [`connect`](#), we connect to the server we had just created. Meanwhile, the accept function returns a server-side connection to the newly created socket and prints "Hello World" to indicate that the connection was successful.
A great strength of Julia is that since the API is exposed synchronously even though the I/O is actually happening asynchronously, we didn't have to worry about callbacks or even making sure that the server gets to run. When we called [`connect`](#) the current task waited for the connection to be established and only continued executing after that was done. In this pause, the server task resumed execution (because a connection request was now available), accepted the connection, printed the message and waited for the next client. Reading and writing works in the same way. To see this, consider the following simple echo server:
```
julia> errormonitor(@async begin
server = listen(2001)
while true
sock = accept(server)
@async while isopen(sock)
write(sock, readline(sock, keep=true))
end
end
end)
Task (runnable) @0x00007fd31dc12e60
julia> clientside = connect(2001)
TCPSocket(RawFD(28) open, 0 bytes waiting)
julia> errormonitor(@async while isopen(clientside)
write(stdout, readline(clientside, keep=true))
end)
Task (runnable) @0x00007fd31dc11870
julia> println(clientside,"Hello World from the Echo Server")
Hello World from the Echo Server
```
As with other streams, use [`close`](../../base/io-network/index#Base.close) to disconnect the socket:
```
julia> close(clientside)
```
[Resolving IP Addresses](#Resolving-IP-Addresses)
--------------------------------------------------
One of the [`connect`](#) methods that does not follow the [`listen`](#) methods is `connect(host::String,port)`, which will attempt to connect to the host given by the `host` parameter on the port given by the `port` parameter. It allows you to do things like:
```
julia> connect("google.com", 80)
TCPSocket(RawFD(30) open, 0 bytes waiting)
```
At the base of this functionality is [`getaddrinfo`](../../stdlib/sockets/index#Sockets.getaddrinfo), which will do the appropriate address resolution:
```
julia> getaddrinfo("google.com")
ip"74.125.226.225"
```
[Asynchronous I/O](#Asynchronous-I/O)
--------------------------------------
All I/O operations exposed by [`Base.read`](../../base/io-network/index#Base.read) and [`Base.write`](../../base/io-network/index#Base.write) can be performed asynchronously through the use of [coroutines](../control-flow/index#man-tasks). You can create a new coroutine to read from or write to a stream using the [`@async`](../../base/parallel/index#Base.@async) macro:
```
julia> task = @async open("foo.txt", "w") do io
write(io, "Hello, World!")
end;
julia> wait(task)
julia> readlines("foo.txt")
1-element Array{String,1}:
"Hello, World!"
```
It's common to run into situations where you want to perform multiple asynchronous operations concurrently and wait until they've all completed. You can use the [`@sync`](../../base/parallel/index#Base.@sync) macro to cause your program to block until all of the coroutines it wraps around have exited:
```
julia> using Sockets
julia> @sync for hostname in ("google.com", "github.com", "julialang.org")
@async begin
conn = connect(hostname, 80)
write(conn, "GET / HTTP/1.1\r\nHost:$(hostname)\r\n\r\n")
readline(conn, keep=true)
println("Finished connection to $(hostname)")
end
end
Finished connection to google.com
Finished connection to julialang.org
Finished connection to github.com
```
[Multicast](#Multicast)
------------------------
Julia supports [multicast](https://datatracker.ietf.org/doc/html/rfc1112) over IPv4 and IPv6 using the User Datagram Protocol ([UDP](https://datatracker.ietf.org/doc/html/rfc768)) as transport.
Unlike the Transmission Control Protocol ([TCP](https://datatracker.ietf.org/doc/html/rfc793)), UDP makes almost no assumptions about the needs of the application. TCP provides flow control (it accelerates and decelerates to maximize throughput), reliability (lost or corrupt packets are automatically retransmitted), sequencing (packets are ordered by the operating system before they are given to the application), segment size, and session setup and teardown. UDP provides no such features.
A common use for UDP is in multicast applications. TCP is a stateful protocol for communication between exactly two devices. UDP can use special multicast addresses to allow simultaneous communication between many devices.
###
[Receiving IP Multicast Packets](#Receiving-IP-Multicast-Packets)
To transmit data over UDP multicast, simply `recv` on the socket, and the first packet received will be returned. Note that it may not be the first packet that you sent however!
```
using Sockets
group = ip"228.5.6.7"
socket = Sockets.UDPSocket()
bind(socket, ip"0.0.0.0", 6789)
join_multicast_group(socket, group)
println(String(recv(socket)))
leave_multicast_group(socket, group)
close(socket)
```
###
[Sending IP Multicast Packets](#Sending-IP-Multicast-Packets)
To transmit data over UDP multicast, simply `send` to the socket. Notice that it is not necessary for a sender to join the multicast group.
```
using Sockets
group = ip"228.5.6.7"
socket = Sockets.UDPSocket()
send(socket, group, 6789, "Hello over IPv4")
close(socket)
```
###
[IPv6 Example](#IPv6-Example)
This example gives the same functionality as the previous program, but uses IPv6 as the network-layer protocol.
Listener:
```
using Sockets
group = Sockets.IPv6("ff05::5:6:7")
socket = Sockets.UDPSocket()
bind(socket, Sockets.IPv6("::"), 6789)
join_multicast_group(socket, group)
println(String(recv(socket)))
leave_multicast_group(socket, group)
close(socket)
```
Sender:
```
using Sockets
group = Sockets.IPv6("ff05::5:6:7")
socket = Sockets.UDPSocket()
send(socket, group, 6789, "Hello over IPv6")
close(socket)
```
| programming_docs |
julia Complex and Rational Numbers Complex and Rational Numbers
============================
Julia includes predefined types for both complex and rational numbers, and supports all the standard [Mathematical Operations and Elementary Functions](../mathematical-operations/index#Mathematical-Operations-and-Elementary-Functions) on them. [Conversion and Promotion](../conversion-and-promotion/index#conversion-and-promotion) are defined so that operations on any combination of predefined numeric types, whether primitive or composite, behave as expected.
[Complex Numbers](#Complex-Numbers)
------------------------------------
The global constant [`im`](../../base/numbers/index#Base.im) is bound to the complex number *i*, representing the principal square root of -1. (Using mathematicians' `i` or engineers' `j` for this global constant was rejected since they are such popular index variable names.) Since Julia allows numeric literals to be [juxtaposed with identifiers as coefficients](../integers-and-floating-point-numbers/index#man-numeric-literal-coefficients), this binding suffices to provide convenient syntax for complex numbers, similar to the traditional mathematical notation:
```
julia> 1+2im
1 + 2im
```
You can perform all the standard arithmetic operations with complex numbers:
```
julia> (1 + 2im)*(2 - 3im)
8 + 1im
julia> (1 + 2im)/(1 - 2im)
-0.6 + 0.8im
julia> (1 + 2im) + (1 - 2im)
2 + 0im
julia> (-3 + 2im) - (5 - 1im)
-8 + 3im
julia> (-1 + 2im)^2
-3 - 4im
julia> (-1 + 2im)^2.5
2.729624464784009 - 6.9606644595719im
julia> (-1 + 2im)^(1 + 1im)
-0.27910381075826657 + 0.08708053414102428im
julia> 3(2 - 5im)
6 - 15im
julia> 3(2 - 5im)^2
-63 - 60im
julia> 3(2 - 5im)^-1.0
0.20689655172413796 + 0.5172413793103449im
```
The promotion mechanism ensures that combinations of operands of different types just work:
```
julia> 2(1 - 1im)
2 - 2im
julia> (2 + 3im) - 1
1 + 3im
julia> (1 + 2im) + 0.5
1.5 + 2.0im
julia> (2 + 3im) - 0.5im
2.0 + 2.5im
julia> 0.75(1 + 2im)
0.75 + 1.5im
julia> (2 + 3im) / 2
1.0 + 1.5im
julia> (1 - 3im) / (2 + 2im)
-0.5 - 1.0im
julia> 2im^2
-2 + 0im
julia> 1 + 3/4im
1.0 - 0.75im
```
Note that `3/4im == 3/(4*im) == -(3/4*im)`, since a literal coefficient binds more tightly than division.
Standard functions to manipulate complex values are provided:
```
julia> z = 1 + 2im
1 + 2im
julia> real(1 + 2im) # real part of z
1
julia> imag(1 + 2im) # imaginary part of z
2
julia> conj(1 + 2im) # complex conjugate of z
1 - 2im
julia> abs(1 + 2im) # absolute value of z
2.23606797749979
julia> abs2(1 + 2im) # squared absolute value
5
julia> angle(1 + 2im) # phase angle in radians
1.1071487177940904
```
As usual, the absolute value ([`abs`](../../base/math/index#Base.abs)) of a complex number is its distance from zero. [`abs2`](../../base/math/index#Base.abs2) gives the square of the absolute value, and is of particular use for complex numbers since it avoids taking a square root. [`angle`](../../base/math/index#Base.angle) returns the phase angle in radians (also known as the *argument* or *arg* function). The full gamut of other [Elementary Functions](../mathematical-operations/index#Elementary-Functions) is also defined for complex numbers:
```
julia> sqrt(1im)
0.7071067811865476 + 0.7071067811865475im
julia> sqrt(1 + 2im)
1.272019649514069 + 0.7861513777574233im
julia> cos(1 + 2im)
2.0327230070196656 - 3.0518977991517997im
julia> exp(1 + 2im)
-1.1312043837568135 + 2.4717266720048188im
julia> sinh(1 + 2im)
-0.4890562590412937 + 1.4031192506220405im
```
Note that mathematical functions typically return real values when applied to real numbers and complex values when applied to complex numbers. For example, [`sqrt`](#) behaves differently when applied to `-1` versus `-1 + 0im` even though `-1 == -1 + 0im`:
```
julia> sqrt(-1)
ERROR: DomainError with -1.0:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
julia> sqrt(-1 + 0im)
0.0 + 1.0im
```
The [literal numeric coefficient notation](../integers-and-floating-point-numbers/index#man-numeric-literal-coefficients) does not work when constructing a complex number from variables. Instead, the multiplication must be explicitly written out:
```
julia> a = 1; b = 2; a + b*im
1 + 2im
```
However, this is *not* recommended. Instead, use the more efficient [`complex`](#) function to construct a complex value directly from its real and imaginary parts:
```
julia> a = 1; b = 2; complex(a, b)
1 + 2im
```
This construction avoids the multiplication and addition operations.
[`Inf`](../../base/numbers/index#Base.Inf) and [`NaN`](../../base/numbers/index#Base.NaN) propagate through complex numbers in the real and imaginary parts of a complex number as described in the [Special floating-point values](../integers-and-floating-point-numbers/index#Special-floating-point-values) section:
```
julia> 1 + Inf*im
1.0 + Inf*im
julia> 1 + NaN*im
1.0 + NaN*im
```
[Rational Numbers](#Rational-Numbers)
--------------------------------------
Julia has a rational number type to represent exact ratios of integers. Rationals are constructed using the [`//`](../../base/math/index#Base.://) operator:
```
julia> 2//3
2//3
```
If the numerator and denominator of a rational have common factors, they are reduced to lowest terms such that the denominator is non-negative:
```
julia> 6//9
2//3
julia> -4//8
-1//2
julia> 5//-15
-1//3
julia> -4//-12
1//3
```
This normalized form for a ratio of integers is unique, so equality of rational values can be tested by checking for equality of the numerator and denominator. The standardized numerator and denominator of a rational value can be extracted using the [`numerator`](../../base/math/index#Base.numerator) and [`denominator`](../../base/math/index#Base.denominator) functions:
```
julia> numerator(2//3)
2
julia> denominator(2//3)
3
```
Direct comparison of the numerator and denominator is generally not necessary, since the standard arithmetic and comparison operations are defined for rational values:
```
julia> 2//3 == 6//9
true
julia> 2//3 == 9//27
false
julia> 3//7 < 1//2
true
julia> 3//4 > 2//3
true
julia> 2//4 + 1//6
2//3
julia> 5//12 - 1//4
1//6
julia> 5//8 * 3//12
5//32
julia> 6//5 / 10//7
21//25
```
Rationals can easily be converted to floating-point numbers:
```
julia> float(3//4)
0.75
```
Conversion from rational to floating-point respects the following identity for any integral values of `a` and `b`, with the exception of the case `a == 0` and `b == 0`:
```
julia> a = 1; b = 2;
julia> isequal(float(a//b), a/b)
true
```
Constructing infinite rational values is acceptable:
```
julia> 5//0
1//0
julia> x = -3//0
-1//0
julia> typeof(x)
Rational{Int64}
```
Trying to construct a [`NaN`](../../base/numbers/index#Base.NaN) rational value, however, is invalid:
```
julia> 0//0
ERROR: ArgumentError: invalid rational: zero(Int64)//zero(Int64)
Stacktrace:
[...]
```
As usual, the promotion system makes interactions with other numeric types effortless:
```
julia> 3//5 + 1
8//5
julia> 3//5 - 0.5
0.09999999999999998
julia> 2//7 * (1 + 2im)
2//7 + 4//7*im
julia> 2//7 * (1.5 + 2im)
0.42857142857142855 + 0.5714285714285714im
julia> 3//2 / (1 + 2im)
3//10 - 3//5*im
julia> 1//2 + 2im
1//2 + 2//1*im
julia> 1 + 2//3im
1//1 - 2//3*im
julia> 0.5 == 1//2
true
julia> 0.33 == 1//3
false
julia> 0.33 < 1//3
true
julia> 1//3 - 0.33
0.0033333333333332993
```
julia Interfaces Interfaces
==========
A lot of the power and extensibility in Julia comes from a collection of informal interfaces. By extending a few specific methods to work for a custom type, objects of that type not only receive those functionalities, but they are also able to be used in other methods that are written to generically build upon those behaviors.
[Iteration](#man-interface-iteration)
--------------------------------------
| Required methods | | Brief description |
| --- | --- | --- |
| `iterate(iter)` | | Returns either a tuple of the first item and initial state or [`nothing`](../../base/constants/index#Core.nothing) if empty |
| `iterate(iter, state)` | | Returns either a tuple of the next item and next state or `nothing` if no items remain |
| **Important optional methods** | **Default definition** | **Brief description** |
| `Base.IteratorSize(IterType)` | `Base.HasLength()` | One of `Base.HasLength()`, `Base.HasShape{N}()`, `Base.IsInfinite()`, or `Base.SizeUnknown()` as appropriate |
| `Base.IteratorEltype(IterType)` | `Base.HasEltype()` | Either `Base.EltypeUnknown()` or `Base.HasEltype()` as appropriate |
| `eltype(IterType)` | `Any` | The type of the first entry of the tuple returned by `iterate()` |
| `length(iter)` | (*undefined*) | The number of items, if known |
| `size(iter, [dim])` | (*undefined*) | The number of items in each dimension, if known |
| `Base.isdone(iter[, state])` | `missing` | Fast-path hint for iterator completion. Should be defined for mutable iterators, or else `isempty(iter)` will call `iterate(iter[, state])` and may mutate the iterator. |
| Value returned by `IteratorSize(IterType)` | Required Methods |
| --- | --- |
| `Base.HasLength()` | [`length(iter)`](#) |
| `Base.HasShape{N}()` | `length(iter)` and `size(iter, [dim])` |
| `Base.IsInfinite()` | (*none*) |
| `Base.SizeUnknown()` | (*none*) |
| Value returned by `IteratorEltype(IterType)` | Required Methods |
| --- | --- |
| `Base.HasEltype()` | `eltype(IterType)` |
| `Base.EltypeUnknown()` | (*none*) |
Sequential iteration is implemented by the [`iterate`](../../base/collections/index#Base.iterate) function. Instead of mutating objects as they are iterated over, Julia iterators may keep track of the iteration state externally from the object. The return value from iterate is always either a tuple of a value and a state, or `nothing` if no elements remain. The state object will be passed back to the iterate function on the next iteration and is generally considered an implementation detail private to the iterable object.
Any object that defines this function is iterable and can be used in the [many functions that rely upon iteration](../../base/collections/index#lib-collections-iteration). It can also be used directly in a [`for`](../../base/base/index#for) loop since the syntax:
```
for item in iter # or "for item = iter"
# body
end
```
is translated into:
```
next = iterate(iter)
while next !== nothing
(item, state) = next
# body
next = iterate(iter, state)
end
```
A simple example is an iterable sequence of square numbers with a defined length:
```
julia> struct Squares
count::Int
end
julia> Base.iterate(S::Squares, state=1) = state > S.count ? nothing : (state*state, state+1)
```
With only [`iterate`](../../base/collections/index#Base.iterate) definition, the `Squares` type is already pretty powerful. We can iterate over all the elements:
```
julia> for item in Squares(7)
println(item)
end
1
4
9
16
25
36
49
```
We can use many of the builtin methods that work with iterables, like [`in`](../../base/collections/index#Base.in), or [`mean`](../../stdlib/statistics/index#Statistics.mean) and [`std`](../../stdlib/statistics/index#Statistics.std) from the `Statistics` standard library module:
```
julia> 25 in Squares(10)
true
julia> using Statistics
julia> mean(Squares(100))
3383.5
julia> std(Squares(100))
3024.355854282583
```
There are a few more methods we can extend to give Julia more information about this iterable collection. We know that the elements in a `Squares` sequence will always be `Int`. By extending the [`eltype`](../../base/collections/index#Base.eltype) method, we can give that information to Julia and help it make more specialized code in the more complicated methods. We also know the number of elements in our sequence, so we can extend [`length`](../../base/collections/index#Base.length), too:
```
julia> Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type
julia> Base.length(S::Squares) = S.count
```
Now, when we ask Julia to [`collect`](#) all the elements into an array it can preallocate a `Vector{Int}` of the right size instead of naively [`push!`](../../base/collections/index#Base.push!)ing each element into a `Vector{Any}`:
```
julia> collect(Squares(4))
4-element Vector{Int64}:
1
4
9
16
```
While we can rely upon generic implementations, we can also extend specific methods where we know there is a simpler algorithm. For example, there's a formula to compute the sum of squares, so we can override the generic iterative version with a more performant solution:
```
julia> Base.sum(S::Squares) = (n = S.count; return n*(n+1)*(2n+1)÷6)
julia> sum(Squares(1803))
1955361914
```
This is a very common pattern throughout Julia Base: a small set of required methods define an informal interface that enable many fancier behaviors. In some cases, types will want to additionally specialize those extra behaviors when they know a more efficient algorithm can be used in their specific case.
It is also often useful to allow iteration over a collection in *reverse order* by iterating over [`Iterators.reverse(iterator)`](../../base/iterators/index#Base.Iterators.reverse). To actually support reverse-order iteration, however, an iterator type `T` needs to implement `iterate` for `Iterators.Reverse{T}`. (Given `r::Iterators.Reverse{T}`, the underling iterator of type `T` is `r.itr`.) In our `Squares` example, we would implement `Iterators.Reverse{Squares}` methods:
```
julia> Base.iterate(rS::Iterators.Reverse{Squares}, state=rS.itr.count) = state < 1 ? nothing : (state*state, state-1)
julia> collect(Iterators.reverse(Squares(4)))
4-element Vector{Int64}:
16
9
4
1
```
[Indexing](#Indexing)
----------------------
| Methods to implement | Brief description |
| --- | --- |
| `getindex(X, i)` | `X[i]`, indexed element access |
| `setindex!(X, v, i)` | `X[i] = v`, indexed assignment |
| `firstindex(X)` | The first index, used in `X[begin]` |
| `lastindex(X)` | The last index, used in `X[end]` |
For the `Squares` iterable above, we can easily compute the `i`th element of the sequence by squaring it. We can expose this as an indexing expression `S[i]`. To opt into this behavior, `Squares` simply needs to define [`getindex`](../../base/collections/index#Base.getindex):
```
julia> function Base.getindex(S::Squares, i::Int)
1 <= i <= S.count || throw(BoundsError(S, i))
return i*i
end
julia> Squares(100)[23]
529
```
Additionally, to support the syntax `S[begin]` and `S[end]`, we must define [`firstindex`](../../base/collections/index#Base.firstindex) and [`lastindex`](../../base/collections/index#Base.lastindex) to specify the first and last valid indices, respectively:
```
julia> Base.firstindex(S::Squares) = 1
julia> Base.lastindex(S::Squares) = length(S)
julia> Squares(23)[end]
529
```
For multi-dimensional `begin`/`end` indexing as in `a[3, begin, 7]`, for example, you should define `firstindex(a, dim)` and `lastindex(a, dim)` (which default to calling `first` and `last` on `axes(a, dim)`, respectively).
Note, though, that the above *only* defines [`getindex`](../../base/collections/index#Base.getindex) with one integer index. Indexing with anything other than an `Int` will throw a [`MethodError`](../../base/base/index#Core.MethodError) saying that there was no matching method. In order to support indexing with ranges or vectors of `Int`s, separate methods must be written:
```
julia> Base.getindex(S::Squares, i::Number) = S[convert(Int, i)]
julia> Base.getindex(S::Squares, I) = [S[i] for i in I]
julia> Squares(10)[[3,4.,5]]
3-element Vector{Int64}:
9
16
25
```
While this is starting to support more of the [indexing operations supported by some of the builtin types](../arrays/index#man-array-indexing), there's still quite a number of behaviors missing. This `Squares` sequence is starting to look more and more like a vector as we've added behaviors to it. Instead of defining all these behaviors ourselves, we can officially define it as a subtype of an [`AbstractArray`](../../base/arrays/index#Core.AbstractArray).
[Abstract Arrays](#man-interface-array)
----------------------------------------
| Methods to implement | | Brief description |
| --- | --- | --- |
| `size(A)` | | Returns a tuple containing the dimensions of `A` |
| `getindex(A, i::Int)` | | (if `IndexLinear`) Linear scalar indexing |
| `getindex(A, I::Vararg{Int, N})` | | (if `IndexCartesian`, where `N = ndims(A)`) N-dimensional scalar indexing |
| `setindex!(A, v, i::Int)` | | (if `IndexLinear`) Scalar indexed assignment |
| `setindex!(A, v, I::Vararg{Int, N})` | | (if `IndexCartesian`, where `N = ndims(A)`) N-dimensional scalar indexed assignment |
| **Optional methods** | **Default definition** | **Brief description** |
| `IndexStyle(::Type)` | `IndexCartesian()` | Returns either `IndexLinear()` or `IndexCartesian()`. See the description below. |
| `getindex(A, I...)` | defined in terms of scalar `getindex` | [Multidimensional and nonscalar indexing](../arrays/index#man-array-indexing) |
| `setindex!(A, X, I...)` | defined in terms of scalar `setindex!` | [Multidimensional and nonscalar indexed assignment](../arrays/index#man-array-indexing) |
| `iterate` | defined in terms of scalar `getindex` | Iteration |
| `length(A)` | `prod(size(A))` | Number of elements |
| `similar(A)` | `similar(A, eltype(A), size(A))` | Return a mutable array with the same shape and element type |
| `similar(A, ::Type{S})` | `similar(A, S, size(A))` | Return a mutable array with the same shape and the specified element type |
| `similar(A, dims::Dims)` | `similar(A, eltype(A), dims)` | Return a mutable array with the same element type and size *dims* |
| `similar(A, ::Type{S}, dims::Dims)` | `Array{S}(undef, dims)` | Return a mutable array with the specified element type and size |
| **Non-traditional indices** | **Default definition** | **Brief description** |
| `axes(A)` | `map(OneTo, size(A))` | Return a tuple of `AbstractUnitRange{<:Integer}` of valid indices |
| `similar(A, ::Type{S}, inds)` | `similar(A, S, Base.to_shape(inds))` | Return a mutable array with the specified indices `inds` (see below) |
| `similar(T::Union{Type,Function}, inds)` | `T(Base.to_shape(inds))` | Return an array similar to `T` with the specified indices `inds` (see below) |
If a type is defined as a subtype of `AbstractArray`, it inherits a very large set of rich behaviors including iteration and multidimensional indexing built on top of single-element access. See the [arrays manual page](../arrays/index#man-multi-dim-arrays) and the [Julia Base section](../../base/arrays/index#lib-arrays) for more supported methods.
A key part in defining an `AbstractArray` subtype is [`IndexStyle`](../../base/arrays/index#Base.IndexStyle). Since indexing is such an important part of an array and often occurs in hot loops, it's important to make both indexing and indexed assignment as efficient as possible. Array data structures are typically defined in one of two ways: either it most efficiently accesses its elements using just one index (linear indexing) or it intrinsically accesses the elements with indices specified for every dimension. These two modalities are identified by Julia as `IndexLinear()` and `IndexCartesian()`. Converting a linear index to multiple indexing subscripts is typically very expensive, so this provides a traits-based mechanism to enable efficient generic code for all array types.
This distinction determines which scalar indexing methods the type must define. `IndexLinear()` arrays are simple: just define `getindex(A::ArrayType, i::Int)`. When the array is subsequently indexed with a multidimensional set of indices, the fallback `getindex(A::AbstractArray, I...)()` efficiently converts the indices into one linear index and then calls the above method. `IndexCartesian()` arrays, on the other hand, require methods to be defined for each supported dimensionality with `ndims(A)` `Int` indices. For example, [`SparseMatrixCSC`](../../stdlib/sparsearrays/index#SparseArrays.SparseMatrixCSC) from the `SparseArrays` standard library module, only supports two dimensions, so it just defines `getindex(A::SparseMatrixCSC, i::Int, j::Int)`. The same holds for [`setindex!`](../../base/collections/index#Base.setindex!).
Returning to the sequence of squares from above, we could instead define it as a subtype of an `AbstractArray{Int, 1}`:
```
julia> struct SquaresVector <: AbstractArray{Int, 1}
count::Int
end
julia> Base.size(S::SquaresVector) = (S.count,)
julia> Base.IndexStyle(::Type{<:SquaresVector}) = IndexLinear()
julia> Base.getindex(S::SquaresVector, i::Int) = i*i
```
Note that it's very important to specify the two parameters of the `AbstractArray`; the first defines the [`eltype`](../../base/collections/index#Base.eltype), and the second defines the [`ndims`](../../base/arrays/index#Base.ndims). That supertype and those three methods are all it takes for `SquaresVector` to be an iterable, indexable, and completely functional array:
```
julia> s = SquaresVector(4)
4-element SquaresVector:
1
4
9
16
julia> s[s .> 8]
2-element Vector{Int64}:
9
16
julia> s + s
4-element Vector{Int64}:
2
8
18
32
julia> sin.(s)
4-element Vector{Float64}:
0.8414709848078965
-0.7568024953079282
0.4121184852417566
-0.2879033166650653
```
As a more complicated example, let's define our own toy N-dimensional sparse-like array type built on top of [`Dict`](../../base/collections/index#Base.Dict):
```
julia> struct SparseArray{T,N} <: AbstractArray{T,N}
data::Dict{NTuple{N,Int}, T}
dims::NTuple{N,Int}
end
julia> SparseArray(::Type{T}, dims::Int...) where {T} = SparseArray(T, dims);
julia> SparseArray(::Type{T}, dims::NTuple{N,Int}) where {T,N} = SparseArray{T,N}(Dict{NTuple{N,Int}, T}(), dims);
julia> Base.size(A::SparseArray) = A.dims
julia> Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where {T} = SparseArray(T, dims)
julia> Base.getindex(A::SparseArray{T,N}, I::Vararg{Int,N}) where {T,N} = get(A.data, I, zero(T))
julia> Base.setindex!(A::SparseArray{T,N}, v, I::Vararg{Int,N}) where {T,N} = (A.data[I] = v)
```
Notice that this is an `IndexCartesian` array, so we must manually define [`getindex`](../../base/collections/index#Base.getindex) and [`setindex!`](../../base/collections/index#Base.setindex!) at the dimensionality of the array. Unlike the `SquaresVector`, we are able to define [`setindex!`](../../base/collections/index#Base.setindex!), and so we can mutate the array:
```
julia> A = SparseArray(Float64, 3, 3)
3×3 SparseArray{Float64, 2}:
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
julia> fill!(A, 2)
3×3 SparseArray{Float64, 2}:
2.0 2.0 2.0
2.0 2.0 2.0
2.0 2.0 2.0
julia> A[:] = 1:length(A); A
3×3 SparseArray{Float64, 2}:
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0
```
The result of indexing an `AbstractArray` can itself be an array (for instance when indexing by an `AbstractRange`). The `AbstractArray` fallback methods use [`similar`](../../base/arrays/index#Base.similar) to allocate an `Array` of the appropriate size and element type, which is filled in using the basic indexing method described above. However, when implementing an array wrapper you often want the result to be wrapped as well:
```
julia> A[1:2,:]
2×3 SparseArray{Float64, 2}:
1.0 4.0 7.0
2.0 5.0 8.0
```
In this example it is accomplished by defining `Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where T` to create the appropriate wrapped array. (Note that while `similar` supports 1- and 2-argument forms, in most case you only need to specialize the 3-argument form.) For this to work it's important that `SparseArray` is mutable (supports `setindex!`). Defining `similar`, `getindex` and `setindex!` for `SparseArray` also makes it possible to [`copy`](../../base/base/index#Base.copy) the array:
```
julia> copy(A)
3×3 SparseArray{Float64, 2}:
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0
```
In addition to all the iterable and indexable methods from above, these types can also interact with each other and use most of the methods defined in Julia Base for `AbstractArrays`:
```
julia> A[SquaresVector(3)]
3-element SparseArray{Float64, 1}:
1.0
4.0
9.0
julia> sum(A)
45.0
```
If you are defining an array type that allows non-traditional indexing (indices that start at something other than 1), you should specialize [`axes`](#). You should also specialize [`similar`](../../base/arrays/index#Base.similar) so that the `dims` argument (ordinarily a `Dims` size-tuple) can accept `AbstractUnitRange` objects, perhaps range-types `Ind` of your own design. For more information, see [Arrays with custom indices](https://docs.julialang.org/en/v1.8/devdocs/offset-arrays/#man-custom-indices).
[Strided Arrays](#man-interface-strided-arrays)
------------------------------------------------
| Methods to implement | | Brief description |
| --- | --- | --- |
| `strides(A)` | | Return the distance in memory (in number of elements) between adjacent elements in each dimension as a tuple. If `A` is an `AbstractArray{T,0}`, this should return an empty tuple. |
| `Base.unsafe_convert(::Type{Ptr{T}}, A)` | | Return the native address of an array. |
| `Base.elsize(::Type{<:A})` | | Return the stride between consecutive elements in the array. |
| **Optional methods** | **Default definition** | **Brief description** |
| `stride(A, i::Int)` | `strides(A)[i]` | Return the distance in memory (in number of elements) between adjacent elements in dimension k. |
A strided array is a subtype of `AbstractArray` whose entries are stored in memory with fixed strides. Provided the element type of the array is compatible with BLAS, a strided array can utilize BLAS and LAPACK routines for more efficient linear algebra routines. A typical example of a user-defined strided array is one that wraps a standard `Array` with additional structure.
Warning: do not implement these methods if the underlying storage is not actually strided, as it may lead to incorrect results or segmentation faults.
Here are some examples to demonstrate which type of arrays are strided and which are not:
```
1:5 # not strided (there is no storage associated with this array.)
Vector(1:5) # is strided with strides (1,)
A = [1 5; 2 6; 3 7; 4 8] # is strided with strides (1,4)
V = view(A, 1:2, :) # is strided with strides (1,4)
V = view(A, 1:2:3, 1:2) # is strided with strides (2,4)
V = view(A, [1,2,4], :) # is not strided, as the spacing between rows is not fixed.
```
[Customizing broadcasting](#man-interfaces-broadcasting)
---------------------------------------------------------
| Methods to implement | Brief description |
| --- | --- |
| `Base.BroadcastStyle(::Type{SrcType}) = SrcStyle()` | Broadcasting behavior of `SrcType` |
| `Base.similar(bc::Broadcasted{DestStyle}, ::Type{ElType})` | Allocation of output container |
| **Optional methods** | |
| `Base.BroadcastStyle(::Style1, ::Style2) = Style12()` | Precedence rules for mixing styles |
| `Base.axes(x)` | Declaration of the indices of `x`, as per [`axes(x)`](#). |
| `Base.broadcastable(x)` | Convert `x` to an object that has `axes` and supports indexing |
| **Bypassing default machinery** | |
| `Base.copy(bc::Broadcasted{DestStyle})` | Custom implementation of `broadcast` |
| `Base.copyto!(dest, bc::Broadcasted{DestStyle})` | Custom implementation of `broadcast!`, specializing on `DestStyle` |
| `Base.copyto!(dest::DestType, bc::Broadcasted{Nothing})` | Custom implementation of `broadcast!`, specializing on `DestType` |
| `Base.Broadcast.broadcasted(f, args...)` | Override the default lazy behavior within a fused expression |
| `Base.Broadcast.instantiate(bc::Broadcasted{DestStyle})` | Override the computation of the lazy broadcast's axes |
[Broadcasting](../arrays/index#Broadcasting) is triggered by an explicit call to `broadcast` or `broadcast!`, or implicitly by "dot" operations like `A .+ b` or `f.(x, y)`. Any object that has [`axes`](#) and supports indexing can participate as an argument in broadcasting, and by default the result is stored in an `Array`. This basic framework is extensible in three major ways:
* Ensuring that all arguments support broadcast
* Selecting an appropriate output array for the given set of arguments
* Selecting an efficient implementation for the given set of arguments
Not all types support `axes` and indexing, but many are convenient to allow in broadcast. The [`Base.broadcastable`](../../base/arrays/index#Base.Broadcast.broadcastable) function is called on each argument to broadcast, allowing it to return something different that supports `axes` and indexing. By default, this is the identity function for all `AbstractArray`s and `Number`s — they already support `axes` and indexing. For a handful of other types (including but not limited to types themselves, functions, special singletons like [`missing`](../../base/base/index#Base.missing) and [`nothing`](../../base/constants/index#Core.nothing), and dates), `Base.broadcastable` returns the argument wrapped in a `Ref` to act as a 0-dimensional "scalar" for the purposes of broadcasting. Custom types can similarly specialize `Base.broadcastable` to define their shape, but they should follow the convention that `collect(Base.broadcastable(x)) == collect(x)`. A notable exception is `AbstractString`; strings are special-cased to behave as scalars for the purposes of broadcast even though they are iterable collections of their characters (see [Strings](https://docs.julialang.org/en/v1.8/devdocs/ast/#Strings) for more).
The next two steps (selecting the output array and implementation) are dependent upon determining a single answer for a given set of arguments. Broadcast must take all the varied types of its arguments and collapse them down to just one output array and one implementation. Broadcast calls this single answer a "style". Every broadcastable object each has its own preferred style, and a promotion-like system is used to combine these styles into a single answer — the "destination style".
###
[Broadcast Styles](#Broadcast-Styles)
`Base.BroadcastStyle` is the abstract type from which all broadcast styles are derived. When used as a function it has two possible forms, unary (single-argument) and binary. The unary variant states that you intend to implement specific broadcasting behavior and/or output type, and do not wish to rely on the default fallback [`Broadcast.DefaultArrayStyle`](../../base/arrays/index#Base.Broadcast.DefaultArrayStyle).
To override these defaults, you can define a custom `BroadcastStyle` for your object:
```
struct MyStyle <: Broadcast.BroadcastStyle end
Base.BroadcastStyle(::Type{<:MyType}) = MyStyle()
```
In some cases it might be convenient not to have to define `MyStyle`, in which case you can leverage one of the general broadcast wrappers:
* `Base.BroadcastStyle(::Type{<:MyType}) = Broadcast.Style{MyType}()` can be used for arbitrary types.
* `Base.BroadcastStyle(::Type{<:MyType}) = Broadcast.ArrayStyle{MyType}()` is preferred if `MyType` is an `AbstractArray`.
* For `AbstractArrays` that only support a certain dimensionality, create a subtype of `Broadcast.AbstractArrayStyle{N}` (see below).
When your broadcast operation involves several arguments, individual argument styles get combined to determine a single `DestStyle` that controls the type of the output container. For more details, see [below](#writing-binary-broadcasting-rules).
###
[Selecting an appropriate output array](#Selecting-an-appropriate-output-array)
The broadcast style is computed for every broadcasting operation to allow for dispatch and specialization. The actual allocation of the result array is handled by `similar`, using the Broadcasted object as its first argument.
```
Base.similar(bc::Broadcasted{DestStyle}, ::Type{ElType})
```
The fallback definition is
```
similar(bc::Broadcasted{DefaultArrayStyle{N}}, ::Type{ElType}) where {N,ElType} =
similar(Array{ElType}, axes(bc))
```
However, if needed you can specialize on any or all of these arguments. The final argument `bc` is a lazy representation of a (potentially fused) broadcast operation, a `Broadcasted` object. For these purposes, the most important fields of the wrapper are `f` and `args`, describing the function and argument list, respectively. Note that the argument list can — and often does — include other nested `Broadcasted` wrappers.
For a complete example, let's say you have created a type, `ArrayAndChar`, that stores an array and a single character:
```
struct ArrayAndChar{T,N} <: AbstractArray{T,N}
data::Array{T,N}
char::Char
end
Base.size(A::ArrayAndChar) = size(A.data)
Base.getindex(A::ArrayAndChar{T,N}, inds::Vararg{Int,N}) where {T,N} = A.data[inds...]
Base.setindex!(A::ArrayAndChar{T,N}, val, inds::Vararg{Int,N}) where {T,N} = A.data[inds...] = val
Base.showarg(io::IO, A::ArrayAndChar, toplevel) = print(io, typeof(A), " with char '", A.char, "'")
```
You might want broadcasting to preserve the `char` "metadata". First we define
```
Base.BroadcastStyle(::Type{<:ArrayAndChar}) = Broadcast.ArrayStyle{ArrayAndChar}()
```
This means we must also define a corresponding `similar` method:
```
function Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{ArrayAndChar}}, ::Type{ElType}) where ElType
# Scan the inputs for the ArrayAndChar:
A = find_aac(bc)
# Use the char field of A to create the output
ArrayAndChar(similar(Array{ElType}, axes(bc)), A.char)
end
"`A = find_aac(As)` returns the first ArrayAndChar among the arguments."
find_aac(bc::Base.Broadcast.Broadcasted) = find_aac(bc.args)
find_aac(args::Tuple) = find_aac(find_aac(args[1]), Base.tail(args))
find_aac(x) = x
find_aac(::Tuple{}) = nothing
find_aac(a::ArrayAndChar, rest) = a
find_aac(::Any, rest) = find_aac(rest)
```
From these definitions, one obtains the following behavior:
```
julia> a = ArrayAndChar([1 2; 3 4], 'x')
2×2 ArrayAndChar{Int64, 2} with char 'x':
1 2
3 4
julia> a .+ 1
2×2 ArrayAndChar{Int64, 2} with char 'x':
2 3
4 5
julia> a .+ [5,10]
2×2 ArrayAndChar{Int64, 2} with char 'x':
6 7
13 14
```
###
[Extending broadcast with custom implementations](#extending-in-place-broadcast)
In general, a broadcast operation is represented by a lazy `Broadcasted` container that holds onto the function to be applied alongside its arguments. Those arguments may themselves be more nested `Broadcasted` containers, forming a large expression tree to be evaluated. A nested tree of `Broadcasted` containers is directly constructed by the implicit dot syntax; `5 .+ 2.*x` is transiently represented by `Broadcasted(+, 5, Broadcasted(*, 2, x))`, for example. This is invisible to users as it is immediately realized through a call to `copy`, but it is this container that provides the basis for broadcast's extensibility for authors of custom types. The built-in broadcast machinery will then determine the result type and size based upon the arguments, allocate it, and then finally copy the realization of the `Broadcasted` object into it with a default `copyto!(::AbstractArray, ::Broadcasted)` method. The built-in fallback `broadcast` and `broadcast!` methods similarly construct a transient `Broadcasted` representation of the operation so they can follow the same codepath. This allows custom array implementations to provide their own `copyto!` specialization to customize and optimize broadcasting. This is again determined by the computed broadcast style. This is such an important part of the operation that it is stored as the first type parameter of the `Broadcasted` type, allowing for dispatch and specialization.
For some types, the machinery to "fuse" operations across nested levels of broadcasting is not available or could be done more efficiently incrementally. In such cases, you may need or want to evaluate `x .* (x .+ 1)` as if it had been written `broadcast(*, x, broadcast(+, x, 1))`, where the inner operation is evaluated before tackling the outer operation. This sort of eager operation is directly supported by a bit of indirection; instead of directly constructing `Broadcasted` objects, Julia lowers the fused expression `x .* (x .+ 1)` to `Broadcast.broadcasted(*, x, Broadcast.broadcasted(+, x, 1))`. Now, by default, `broadcasted` just calls the `Broadcasted` constructor to create the lazy representation of the fused expression tree, but you can choose to override it for a particular combination of function and arguments.
As an example, the builtin `AbstractRange` objects use this machinery to optimize pieces of broadcasted expressions that can be eagerly evaluated purely in terms of the start, step, and length (or stop) instead of computing every single element. Just like all the other machinery, `broadcasted` also computes and exposes the combined broadcast style of its arguments, so instead of specializing on `broadcasted(f, args...)`, you can specialize on `broadcasted(::DestStyle, f, args...)` for any combination of style, function, and arguments.
For example, the following definition supports the negation of ranges:
```
broadcasted(::DefaultArrayStyle{1}, ::typeof(-), r::OrdinalRange) = range(-first(r), step=-step(r), length=length(r))
```
###
[Extending in-place broadcasting](#extending-in-place-broadcast-2)
In-place broadcasting can be supported by defining the appropriate `copyto!(dest, bc::Broadcasted)` method. Because you might want to specialize either on `dest` or the specific subtype of `bc`, to avoid ambiguities between packages we recommend the following convention.
If you wish to specialize on a particular style `DestStyle`, define a method for
```
copyto!(dest, bc::Broadcasted{DestStyle})
```
Optionally, with this form you can also specialize on the type of `dest`.
If instead you want to specialize on the destination type `DestType` without specializing on `DestStyle`, then you should define a method with the following signature:
```
copyto!(dest::DestType, bc::Broadcasted{Nothing})
```
This leverages a fallback implementation of `copyto!` that converts the wrapper into a `Broadcasted{Nothing}`. Consequently, specializing on `DestType` has lower precedence than methods that specialize on `DestStyle`.
Similarly, you can completely override out-of-place broadcasting with a `copy(::Broadcasted)` method.
####
[Working with `Broadcasted` objects](#Working-with-Broadcasted-objects)
In order to implement such a `copy` or `copyto!`, method, of course, you must work with the `Broadcasted` wrapper to compute each element. There are two main ways of doing so:
* `Broadcast.flatten` recomputes the potentially nested operation into a single function and flat list of arguments. You are responsible for implementing the broadcasting shape rules yourself, but this may be helpful in limited situations.
* Iterating over the `CartesianIndices` of the `axes(::Broadcasted)` and using indexing with the resulting `CartesianIndex` object to compute the result.
###
[Writing binary broadcasting rules](#writing-binary-broadcasting-rules)
The precedence rules are defined by binary `BroadcastStyle` calls:
```
Base.BroadcastStyle(::Style1, ::Style2) = Style12()
```
where `Style12` is the `BroadcastStyle` you want to choose for outputs involving arguments of `Style1` and `Style2`. For example,
```
Base.BroadcastStyle(::Broadcast.Style{Tuple}, ::Broadcast.AbstractArrayStyle{0}) = Broadcast.Style{Tuple}()
```
indicates that `Tuple` "wins" over zero-dimensional arrays (the output container will be a tuple). It is worth noting that you do not need to (and should not) define both argument orders of this call; defining one is sufficient no matter what order the user supplies the arguments in.
For `AbstractArray` types, defining a `BroadcastStyle` supersedes the fallback choice, [`Broadcast.DefaultArrayStyle`](../../base/arrays/index#Base.Broadcast.DefaultArrayStyle). `DefaultArrayStyle` and the abstract supertype, `AbstractArrayStyle`, store the dimensionality as a type parameter to support specialized array types that have fixed dimensionality requirements.
`DefaultArrayStyle` "loses" to any other `AbstractArrayStyle` that has been defined because of the following methods:
```
BroadcastStyle(a::AbstractArrayStyle{Any}, ::DefaultArrayStyle) = a
BroadcastStyle(a::AbstractArrayStyle{N}, ::DefaultArrayStyle{N}) where N = a
BroadcastStyle(a::AbstractArrayStyle{M}, ::DefaultArrayStyle{N}) where {M,N} =
typeof(a)(Val(max(M, N)))
```
You do not need to write binary `BroadcastStyle` rules unless you want to establish precedence for two or more non-`DefaultArrayStyle` types.
If your array type does have fixed dimensionality requirements, then you should subtype `AbstractArrayStyle`. For example, the sparse array code has the following definitions:
```
struct SparseVecStyle <: Broadcast.AbstractArrayStyle{1} end
struct SparseMatStyle <: Broadcast.AbstractArrayStyle{2} end
Base.BroadcastStyle(::Type{<:SparseVector}) = SparseVecStyle()
Base.BroadcastStyle(::Type{<:SparseMatrixCSC}) = SparseMatStyle()
```
Whenever you subtype `AbstractArrayStyle`, you also need to define rules for combining dimensionalities, by creating a constructor for your style that takes a `Val(N)` argument. For example:
```
SparseVecStyle(::Val{0}) = SparseVecStyle()
SparseVecStyle(::Val{1}) = SparseVecStyle()
SparseVecStyle(::Val{2}) = SparseMatStyle()
SparseVecStyle(::Val{N}) where N = Broadcast.DefaultArrayStyle{N}()
```
These rules indicate that the combination of a `SparseVecStyle` with 0- or 1-dimensional arrays yields another `SparseVecStyle`, that its combination with a 2-dimensional array yields a `SparseMatStyle`, and anything of higher dimensionality falls back to the dense arbitrary-dimensional framework. These rules allow broadcasting to keep the sparse representation for operations that result in one or two dimensional outputs, but produce an `Array` for any other dimensionality.
| programming_docs |
julia Dynamic Linker Dynamic Linker
==============
###
`Base.Libc.Libdl.dlopen`Function
```
dlopen(libfile::AbstractString [, flags::Integer]; throw_error:Bool = true)
```
Load a shared library, returning an opaque handle.
The extension given by the constant `dlext` (`.so`, `.dll`, or `.dylib`) can be omitted from the `libfile` string, as it is automatically appended if needed. If `libfile` is not an absolute path name, then the paths in the array `DL_LOAD_PATH` are searched for `libfile`, followed by the system load path.
The optional flags argument is a bitwise-or of zero or more of `RTLD_LOCAL`, `RTLD_GLOBAL`, `RTLD_LAZY`, `RTLD_NOW`, `RTLD_NODELETE`, `RTLD_NOLOAD`, `RTLD_DEEPBIND`, and `RTLD_FIRST`. These are converted to the corresponding flags of the POSIX (and/or GNU libc and/or MacOS) dlopen command, if possible, or are ignored if the specified functionality is not available on the current platform. The default flags are platform specific. On MacOS the default `dlopen` flags are `RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL` while on other platforms the defaults are `RTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL`. An important usage of these flags is to specify non default behavior for when the dynamic library loader binds library references to exported symbols and if the bound references are put into process local or global scope. For instance `RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL` allows the library's symbols to be available for usage in other shared libraries, addressing situations where there are dependencies between shared libraries.
If the library cannot be found, this method throws an error, unless the keyword argument `throw_error` is set to `false`, in which case this method returns `nothing`.
From Julia 1.6 on, this method replaces paths starting with `@executable_path/` with the path to the Julia executable, allowing for relocatable relative-path loads. In Julia 1.5 and earlier, this only worked on macOS.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L79-L110)###
`Base.Libc.Libdl.dlopen_e`Function
```
dlopen_e(libfile::AbstractString [, flags::Integer])
```
Similar to [`dlopen`](#Base.Libc.Libdl.dlopen), except returns `C_NULL` instead of raising errors. This method is now deprecated in favor of `dlopen(libfile::AbstractString [, flags::Integer]; throw_error=false)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L151-L156)###
`Base.Libc.Libdl.RTLD_NOW`Constant
```
RTLD_DEEPBIND
RTLD_FIRST
RTLD_GLOBAL
RTLD_LAZY
RTLD_LOCAL
RTLD_NODELETE
RTLD_NOLOAD
RTLD_NOW
```
Enum constant for [`dlopen`](#Base.Libc.Libdl.dlopen). See your platform man page for details, if applicable.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L33-L45)###
`Base.Libc.Libdl.dlsym`Function
```
dlsym(handle, sym; throw_error::Bool = true)
```
Look up a symbol from a shared library handle, return callable function pointer on success.
If the symbol cannot be found, this method throws an error, unless the keyword argument `throw_error` is set to `false`, in which case this method returns `nothing`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L48-L55)###
`Base.Libc.Libdl.dlsym_e`Function
```
dlsym_e(handle, sym)
```
Look up a symbol from a shared library handle, silently return `C_NULL` on lookup failure. This method is now deprecated in favor of `dlsym(handle, sym; throw_error=false)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L69-L74)###
`Base.Libc.Libdl.dlclose`Function
```
dlclose(handle)
```
Close shared library referenced by handle.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L159-L163)
```
dlclose(::Nothing)
```
For the very common pattern usage pattern of
```
try
hdl = dlopen(library_name)
... do something
finally
dlclose(hdl)
end
```
We define a `dlclose()` method that accepts a parameter of type `Nothing`, so that user code does not have to change its behavior for the case that `library_name` was not found.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L168-L183)###
`Base.Libc.Libdl.dlext`Constant
```
dlext
```
File extension for dynamic libraries (e.g. dll, dylib, so) on the current platform.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L255-L259)###
`Base.Libc.Libdl.dllist`Function
```
dllist()
```
Return the paths of dynamic libraries currently loaded in a `Vector{String}`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L286-L290)###
`Base.Libc.Libdl.dlpath`Function
```
dlpath(handle::Ptr{Cvoid})
```
Given a library `handle` from `dlopen`, return the full path.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L217-L221)
```
dlpath(libname::Union{AbstractString, Symbol})
```
Get the full path of the library `libname`.
**Example**
```
julia> dlpath("libjulia")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L229-L238)###
`Base.Libc.Libdl.find_library`Function
```
find_library(names, locations)
```
Searches for the first library in `names` in the paths in the `locations` list, `DL_LOAD_PATH`, or system library paths (in that order) which can successfully be dlopen'd. On success, the return value will be one of the names (potentially prefixed by one of the paths in locations). This string can be assigned to a `global const` and used as the library name in future `ccall`'s. On failure, it returns the empty string.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L187-L195)###
`Base.DL_LOAD_PATH`Constant
```
DL_LOAD_PATH
```
When calling [`dlopen`](#Base.Libc.Libdl.dlopen), the paths in this list will be searched first, in order, before searching the system locations for a valid library handle.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libdl.jl#L14-L19)
julia Statistics Statistics
==========
The Statistics standard library module contains basic statistics functionality.
###
`Statistics.std`Function
```
std(itr; corrected::Bool=true, mean=nothing[, dims])
```
Compute the sample standard deviation of collection `itr`.
The algorithm returns an estimator of the generative distribution's standard deviation under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sqrt(sum((itr .- mean(itr)).^2) / (length(itr) - 1))`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` with `n` the number of elements in `itr`.
If `itr` is an `AbstractArray`, `dims` can be provided to compute the standard deviation over dimensions, and `means` may contain means for each dimension of `itr`.
A pre-computed `mean` may be provided. When `dims` is specified, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed).
If array contains `NaN` or [`missing`](../../base/base/index#Base.missing) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the standard deviation of non-missing values.
###
`Statistics.stdm`Function
```
stdm(itr, mean; corrected::Bool=true[, dims])
```
Compute the sample standard deviation of collection `itr`, with known mean(s) `mean`.
The algorithm returns an estimator of the generative distribution's standard deviation under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sqrt(sum((itr .- mean(itr)).^2) / (length(itr) - 1))`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` with `n` the number of elements in `itr`.
If `itr` is an `AbstractArray`, `dims` can be provided to compute the standard deviation over dimensions. In that case, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed).
If array contains `NaN` or [`missing`](../../base/base/index#Base.missing) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the standard deviation of non-missing values.
###
`Statistics.var`Function
```
var(itr; corrected::Bool=true, mean=nothing[, dims])
```
Compute the sample variance of collection `itr`.
The algorithm returns an estimator of the generative distribution's variance under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sum((itr .- mean(itr)).^2) / (length(itr) - 1))`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n` is the number of elements in `itr`.
If `itr` is an `AbstractArray`, `dims` can be provided to compute the variance over dimensions.
A pre-computed `mean` may be provided. When `dims` is specified, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed).
If array contains `NaN` or [`missing`](../../base/base/index#Base.missing) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the variance of non-missing values.
###
`Statistics.varm`Function
```
varm(itr, mean; dims, corrected::Bool=true)
```
Compute the sample variance of collection `itr`, with known mean(s) `mean`.
The algorithm returns an estimator of the generative distribution's variance under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sum((itr .- mean(itr)).^2) / (length(itr) - 1)`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` with `n` the number of elements in `itr`.
If `itr` is an `AbstractArray`, `dims` can be provided to compute the variance over dimensions. In that case, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed).
If array contains `NaN` or [`missing`](../../base/base/index#Base.missing) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the variance of non-missing values.
###
`Statistics.cor`Function
```
cor(x::AbstractVector)
```
Return the number one.
```
cor(X::AbstractMatrix; dims::Int=1)
```
Compute the Pearson correlation matrix of the matrix `X` along the dimension `dims`.
```
cor(x::AbstractVector, y::AbstractVector)
```
Compute the Pearson correlation between the vectors `x` and `y`.
```
cor(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims=1)
```
Compute the Pearson correlation between the vectors or matrices `X` and `Y` along the dimension `dims`.
###
`Statistics.cov`Function
```
cov(x::AbstractVector; corrected::Bool=true)
```
Compute the variance of the vector `x`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = length(x)`.
```
cov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true)
```
Compute the covariance matrix of the matrix `X` along the dimension `dims`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = size(X, dims)`.
```
cov(x::AbstractVector, y::AbstractVector; corrected::Bool=true)
```
Compute the covariance between the vectors `x` and `y`. If `corrected` is `true` (the default), computes $\frac{1}{n-1}\sum\_{i=1}^n (x\_i-\bar x) (y\_i-\bar y)^\*$ where $\*$ denotes the complex conjugate and `n = length(x) = length(y)`. If `corrected` is `false`, computes $\frac{1}{n}\sum\_{i=1}^n (x\_i-\bar x) (y\_i-\bar y)^\*$.
```
cov(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims::Int=1, corrected::Bool=true)
```
Compute the covariance between the vectors or matrices `X` and `Y` along the dimension `dims`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = size(X, dims) = size(Y, dims)`.
###
`Statistics.mean!`Function
```
mean!(r, v)
```
Compute the mean of `v` over the singleton dimensions of `r`, and write results to `r`.
**Examples**
```
julia> using Statistics
julia> v = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> mean!([1., 1.], v)
2-element Vector{Float64}:
1.5
3.5
julia> mean!([1. 1.], v)
1×2 Matrix{Float64}:
2.0 3.0
```
###
`Statistics.mean`Function
```
mean(itr)
```
Compute the mean of all elements in a collection.
If `itr` contains `NaN` or [`missing`](../../base/base/index#Base.missing) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the mean of non-missing values.
**Examples**
```
julia> using Statistics
julia> mean(1:20)
10.5
julia> mean([1, missing, 3])
missing
julia> mean(skipmissing([1, missing, 3]))
2.0
```
```
mean(f::Function, itr)
```
Apply the function `f` to each element of collection `itr` and take the mean.
```
julia> using Statistics
julia> mean(√, [1, 2, 3])
1.3820881233139908
julia> mean([√1, √2, √3])
1.3820881233139908
```
```
mean(f::Function, A::AbstractArray; dims)
```
Apply the function `f` to each element of array `A` and take the mean over dimensions `dims`.
This method requires at least Julia 1.3.
```
julia> using Statistics
julia> mean(√, [1, 2, 3])
1.3820881233139908
julia> mean([√1, √2, √3])
1.3820881233139908
julia> mean(√, [1 2 3; 4 5 6], dims=2)
2×1 Matrix{Float64}:
1.3820881233139908
2.2285192400943226
```
```
mean(A::AbstractArray; dims)
```
Compute the mean of an array over the given dimensions.
`mean` for empty arrays requires at least Julia 1.1.
**Examples**
```
julia> using Statistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> mean(A, dims=1)
1×2 Matrix{Float64}:
2.0 3.0
julia> mean(A, dims=2)
2×1 Matrix{Float64}:
1.5
3.5
```
###
`Statistics.median!`Function
```
median!(v)
```
Like [`median`](#Statistics.median), but may overwrite the input vector.
###
`Statistics.median`Function
```
median(itr)
```
Compute the median of all elements in a collection. For an even number of elements no exact median element exists, so the result is equivalent to calculating mean of two median elements.
If `itr` contains `NaN` or [`missing`](../../base/base/index#Base.missing) values, the result is also `NaN` or `missing` (`missing` takes precedence if `itr` contains both). Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the median of non-missing values.
**Examples**
```
julia> using Statistics
julia> median([1, 2, 3])
2.0
julia> median([1, 2, 3, 4])
2.5
julia> median([1, 2, missing, 4])
missing
julia> median(skipmissing([1, 2, missing, 4]))
2.0
```
```
median(A::AbstractArray; dims)
```
Compute the median of an array along the given dimensions.
**Examples**
```
julia> using Statistics
julia> median([1 2; 3 4], dims=1)
1×2 Matrix{Float64}:
2.0 3.0
```
###
`Statistics.middle`Function
```
middle(x)
```
Compute the middle of a scalar value, which is equivalent to `x` itself, but of the type of `middle(x, x)` for consistency.
```
middle(x, y)
```
Compute the middle of two numbers `x` and `y`, which is equivalent in both value and type to computing their mean (`(x + y) / 2`).
```
middle(range)
```
Compute the middle of a range, which consists of computing the mean of its extrema. Since a range is sorted, the mean is performed with the first and last element.
```
julia> using Statistics
julia> middle(1:10)
5.5
```
```
middle(a)
```
Compute the middle of an array `a`, which consists of finding its extrema and then computing their mean.
```
julia> using Statistics
julia> a = [1,2,3.6,10.9]
4-element Vector{Float64}:
1.0
2.0
3.6
10.9
julia> middle(a)
5.95
```
###
`Statistics.quantile!`Function
```
quantile!([q::AbstractArray, ] v::AbstractVector, p; sorted=false, alpha::Real=1.0, beta::Real=alpha)
```
Compute the quantile(s) of a vector `v` at a specified probability or vector or tuple of probabilities `p` on the interval [0,1]. If `p` is a vector, an optional output array `q` may also be specified. (If not provided, a new output array is created.) The keyword argument `sorted` indicates whether `v` can be assumed to be sorted; if `false` (the default), then the elements of `v` will be partially sorted in-place.
By default (`alpha = beta = 1`), quantiles are computed via linear interpolation between the points `((k-1)/(n-1), v[k])`, for `k = 1:n` where `n = length(v)`. This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R and NumPy default.
The keyword arguments `alpha` and `beta` correspond to the same parameters in Hyndman and Fan, setting them to different values allows to calculate quantiles with any of the methods 4-9 defined in this paper:
* Def. 4: `alpha=0`, `beta=1`
* Def. 5: `alpha=0.5`, `beta=0.5`
* Def. 6: `alpha=0`, `beta=0` (Excel `PERCENTILE.EXC`, Python default, Stata `altdef`)
* Def. 7: `alpha=1`, `beta=1` (Julia, R and NumPy default, Excel `PERCENTILE` and `PERCENTILE.INC`, Python `'inclusive'`)
* Def. 8: `alpha=1/3`, `beta=1/3`
* Def. 9: `alpha=3/8`, `beta=3/8`
An `ArgumentError` is thrown if `v` contains `NaN` or [`missing`](../../base/base/index#Base.missing) values.
**References**
* Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", *The American Statistician*, Vol. 50, No. 4, pp. 361-365
* [Quantile on Wikipedia](https://en.m.wikipedia.org/wiki/Quantile) details the different quantile definitions
**Examples**
```
julia> using Statistics
julia> x = [3, 2, 1];
julia> quantile!(x, 0.5)
2.0
julia> x
3-element Vector{Int64}:
1
2
3
julia> y = zeros(3);
julia> quantile!(y, x, [0.1, 0.5, 0.9]) === y
true
julia> y
3-element Vector{Float64}:
1.2000000000000002
2.0
2.8000000000000003
```
###
`Statistics.quantile`Function
```
quantile(itr, p; sorted=false, alpha::Real=1.0, beta::Real=alpha)
```
Compute the quantile(s) of a collection `itr` at a specified probability or vector or tuple of probabilities `p` on the interval [0,1]. The keyword argument `sorted` indicates whether `itr` can be assumed to be sorted.
Samples quantile are defined by `Q(p) = (1-γ)*x[j] + γ*x[j+1]`, where $x[j]$ is the j-th order statistic, and `γ` is a function of `j = floor(n*p + m)`, `m = alpha + p*(1 - alpha - beta)` and `g = n*p + m - j`.
By default (`alpha = beta = 1`), quantiles are computed via linear interpolation between the points `((k-1)/(n-1), v[k])`, for `k = 1:n` where `n = length(itr)`. This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R and NumPy default.
The keyword arguments `alpha` and `beta` correspond to the same parameters in Hyndman and Fan, setting them to different values allows to calculate quantiles with any of the methods 4-9 defined in this paper:
* Def. 4: `alpha=0`, `beta=1`
* Def. 5: `alpha=0.5`, `beta=0.5`
* Def. 6: `alpha=0`, `beta=0` (Excel `PERCENTILE.EXC`, Python default, Stata `altdef`)
* Def. 7: `alpha=1`, `beta=1` (Julia, R and NumPy default, Excel `PERCENTILE` and `PERCENTILE.INC`, Python `'inclusive'`)
* Def. 8: `alpha=1/3`, `beta=1/3`
* Def. 9: `alpha=3/8`, `beta=3/8`
An `ArgumentError` is thrown if `v` contains `NaN` or [`missing`](../../base/base/index#Base.missing) values. Use the [`skipmissing`](../../base/base/index#Base.skipmissing) function to omit `missing` entries and compute the quantiles of non-missing values.
**References**
* Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", *The American Statistician*, Vol. 50, No. 4, pp. 361-365
* [Quantile on Wikipedia](https://en.m.wikipedia.org/wiki/Quantile) details the different quantile definitions
**Examples**
```
julia> using Statistics
julia> quantile(0:20, 0.5)
10.0
julia> quantile(0:20, [0.1, 0.5, 0.9])
3-element Vector{Float64}:
2.0
10.0
18.000000000000004
julia> quantile(skipmissing([1, 10, missing]), 0.5)
5.5
```
| programming_docs |
julia ArgTools ArgTools
========
[Argument Handling](#Argument-Handling)
----------------------------------------
###
`ArgTools.ArgRead`Type
```
ArgRead = Union{AbstractString, AbstractCmd, IO}
```
The `ArgRead` types is a union of the types that the `arg_read` function knows how to convert into readable IO handles. See [`arg_read`](#ArgTools.arg_read) for details.
###
`ArgTools.ArgWrite`Type
```
ArgWrite = Union{AbstractString, AbstractCmd, IO}
```
The `ArgWrite` types is a union of the types that the `arg_write` function knows how to convert into writeable IO handles, except for `Nothing` which `arg_write` handles by generating a temporary file. See [`arg_write`](#ArgTools.arg_write) for details.
###
`ArgTools.arg_read`Function
```
arg_read(f::Function, arg::ArgRead) -> f(arg_io)
```
The `arg_read` function accepts an argument `arg` that can be any of these:
* `AbstractString`: a file path to be opened for reading
* `AbstractCmd`: a command to be run, reading from its standard output
* `IO`: an open IO handle to be read from
Whether the body returns normally or throws an error, a path which is opened will be closed before returning from `arg_read` and an `IO` handle will be flushed but not closed before returning from `arg_read`.
Note: when opening a file, ArgTools will pass `lock = false` to the file `open(...)` call. Therefore, the object returned by this function should not be used from multiple threads. This restriction may be relaxed in the future, which would not break any working code.
###
`ArgTools.arg_write`Function
```
arg_write(f::Function, arg::ArgWrite) -> arg
arg_write(f::Function, arg::Nothing) -> tempname()
```
The `arg_read` function accepts an argument `arg` that can be any of these:
* `AbstractString`: a file path to be opened for writing
* `AbstractCmd`: a command to be run, writing to its standard input
* `IO`: an open IO handle to be written to
* `Nothing`: a temporary path should be written to
If the body returns normally, a path that is opened will be closed upon completion; an IO handle argument is left open but flushed before return. If the argument is `nothing` then a temporary path is opened for writing and closed open completion and the path is returned from `arg_write`. In all other cases, `arg` itself is returned. This is a useful pattern since you can consistently return whatever was written, whether an argument was passed or not.
If there is an error during the evaluation of the body, a path that is opened by `arg_write` for writing will be deleted, whether it's passed in as a string or a temporary path generated when `arg` is `nothing`.
Note: when opening a file, ArgTools will pass `lock = false` to the file `open(...)` call. Therefore, the object returned by this function should not be used from multiple threads. This restriction may be relaxed in the future, which would not break any working code.
###
`ArgTools.arg_isdir`Function
```
arg_isdir(f::Function, arg::AbstractString) -> f(arg)
```
The `arg_isdir` function takes `arg` which must be the path to an existing directory (an error is raised otherwise) and passes that path to `f` finally returning the result of `f(arg)`. This is definitely the least useful tool offered by `ArgTools` and mostly exists for symmetry with `arg_mkdir` and to give consistent error messages.
###
`ArgTools.arg_mkdir`Function
```
arg_mkdir(f::Function, arg::AbstractString) -> arg
arg_mkdir(f::Function, arg::Nothing) -> mktempdir()
```
The `arg_mkdir` function takes `arg` which must either be one of:
* a path to an already existing empty directory,
* a non-existent path which can be created as a directory, or
* `nothing` in which case a temporary directory is created.
In all cases the path to the directory is returned. If an error occurs during `f(arg)`, the directory is returned to its original state: if it already existed but was empty, it will be emptied; if it did not exist it will be deleted.
[Function Testing](#Function-Testing)
--------------------------------------
###
`ArgTools.arg_readers`Function
```
arg_readers(arg :: AbstractString, [ type = ArgRead ]) do arg::Function
## pre-test setup ##
@arg_test arg begin
arg :: ArgRead
## test using `arg` ##
end
## post-test cleanup ##
end
```
The `arg_readers` function takes a path to be read and a single-argument do block, which is invoked once for each test reader type that `arg_read` can handle. If the optional `type` argument is given then the do block is only invoked for readers that produce arguments of that type.
The `arg` passed to the do block is not the argument value itself, because some of test argument types need to be initialized and finalized for each test case. Consider an open file handle argument: once you've used it for one test, you can't use it again; you need to close it and open the file again for the next test. This function `arg` can be converted into an `ArgRead` instance using `@arg_test arg begin ... end`.
###
`ArgTools.arg_writers`Function
```
arg_writers([ type = ArgWrite ]) do path::String, arg::Function
## pre-test setup ##
@arg_test arg begin
arg :: ArgWrite
## test using `arg` ##
end
## post-test cleanup ##
end
```
The `arg_writers` function takes a do block, which is invoked once for each test writer type that `arg_write` can handle with a temporary (non-existent) `path` and `arg` which can be converted into various writable argument types which write to `path`. If the optional `type` argument is given then the do block is only invoked for writers that produce arguments of that type.
The `arg` passed to the do block is not the argument value itself, because some of test argument types need to be initialized and finalized for each test case. Consider an open file handle argument: once you've used it for one test, you can't use it again; you need to close it and open the file again for the next test. This function `arg` can be converted into an `ArgWrite` instance using `@arg_test arg begin ... end`.
There is also an `arg_writers` method that takes a path name like `arg_readers`:
```
arg_writers(path::AbstractString, [ type = ArgWrite ]) do arg::Function
## pre-test setup ##
@arg_test arg begin
# here `arg :: ArgWrite`
## test using `arg` ##
end
## post-test cleanup ##
end
```
This method is useful if you need to specify `path` instead of using path name generated by `tempname()`. Since `path` is passed from outside of `arg_writers`, the path is not an argument to the do block in this form.
###
`ArgTools.@arg_test`Macro
```
@arg_test arg1 arg2 ... body
```
The `@arg_test` macro is used to convert `arg` functions provided by `arg_readers` and `arg_writers` into actual argument values. When you write `@arg_test arg body` it is equivalent to `arg(arg -> body)`.
julia CRC32c CRC32c
======
###
`CRC32c.crc32c`Function
```
crc32c(data, crc::UInt32=0x00000000)
```
Compute the CRC-32c checksum of the given `data`, which can be an `Array{UInt8}`, a contiguous subarray thereof, or a `String`. Optionally, you can pass a starting `crc` integer to be mixed in with the checksum. The `crc` parameter can be used to compute a checksum on data divided into chunks: performing `crc32c(data2, crc32c(data1))` is equivalent to the checksum of `[data1; data2]`. (Technically, a little-endian checksum is computed.)
There is also a method `crc32c(io, nb, crc)` to checksum `nb` bytes from a stream `io`, or `crc32c(io, crc)` to checksum all the remaining bytes. Hence you can do [`open(crc32c, filename)`](../../base/io-network/index#Base.open) to checksum an entire file, or `crc32c(seekstart(buf))` to checksum an [`IOBuffer`](../../base/io-network/index#Base.IOBuffer) without calling [`take!`](#).
For a `String`, note that the result is specific to the UTF-8 encoding (a different checksum would be obtained from a different Unicode encoding). To checksum an `a::Array` of some other bitstype, you can do `crc32c(reinterpret(UInt8,a))`, but note that the result may be endian-dependent.
###
`CRC32c.crc32c`Method
```
crc32c(io::IO, [nb::Integer,] crc::UInt32=0x00000000)
```
Read up to `nb` bytes from `io` and return the CRC-32c checksum, optionally mixed with a starting `crc` integer. If `nb` is not supplied, then `io` will be read until the end of the stream.
julia TOML TOML
====
TOML.jl is a Julia standard library for parsing and writing [TOML v1.0](https://toml.io/en/) files.
[Parsing TOML data](#Parsing-TOML-data)
----------------------------------------
```
julia> using TOML
julia> data = """
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
""";
julia> TOML.parse(data)
Dict{String, Any} with 1 entry:
"database" => Dict{String, Any}("server"=>"192.168.1.1", "ports"=>[8001, 8001…
```
To parse a file, use [`TOML.parsefile`](#TOML.parsefile). If the file has a syntax error, an exception is thrown:
```
julia> using TOML
julia> TOML.parse("""
value = 0.0.0
""")
ERROR: TOML Parser error:
none:1:16 error: failed to parse value
value = 0.0.0
^
[...]
```
There are other versions of the parse functions ([`TOML.tryparse`](#TOML.tryparse) and [`TOML.tryparsefile`]) that instead of throwing exceptions on parser error returns a [`TOML.ParserError`](#TOML.ParserError) with information:
```
julia> using TOML
julia> err = TOML.tryparse("""
value = 0.0.0
""");
julia> err.type
ErrGenericValueError::ErrorType = 14
julia> err.line
1
julia> err.column
16
```
[Exporting data to TOML file](#Exporting-data-to-TOML-file)
------------------------------------------------------------
The [`TOML.print`](#TOML.print) function is used to print (or serialize) data into TOML format.
```
julia> using TOML
julia> data = Dict(
"names" => ["Julia", "Julio"],
"age" => [10, 20],
);
julia> TOML.print(data)
names = ["Julia", "Julio"]
age = [10, 20]
julia> fname = tempname();
julia> open(fname, "w") do io
TOML.print(io, data)
end
julia> TOML.parsefile(fname)
Dict{String, Any} with 2 entries:
"names" => ["Julia", "Julio"]
"age" => [10, 20]
```
Keys can be sorted according to some value
```
julia> using TOML
julia> TOML.print(Dict(
"abc" => 1,
"ab" => 2,
"abcd" => 3,
); sorted=true, by=length)
ab = 2
abc = 1
abcd = 3
```
For custom structs, pass a function that converts the struct to a supported type
```
julia> using TOML
julia> struct MyStruct
a::Int
b::String
end
julia> TOML.print(Dict("foo" => MyStruct(5, "bar"))) do x
x isa MyStruct && return [x.a, x.b]
error("unhandled type $(typeof(x))")
end
foo = [5, "bar"]
```
[References](#References)
--------------------------
###
`TOML.parse`Function
```
parse(x::Union{AbstractString, IO})
parse(p::Parser, x::Union{AbstractString, IO})
```
Parse the string or stream `x`, and return the resulting table (dictionary). Throw a [`ParserError`](#TOML.ParserError) upon failure.
See also [`TOML.tryparse`](#TOML.tryparse).
###
`TOML.parsefile`Function
```
parsefile(f::AbstractString)
parsefile(p::Parser, f::AbstractString)
```
Parse file `f` and return the resulting table (dictionary). Throw a [`ParserError`](#TOML.ParserError) upon failure.
See also [`TOML.tryparsefile`](#TOML.tryparsefile).
###
`TOML.tryparse`Function
```
tryparse(x::Union{AbstractString, IO})
tryparse(p::Parser, x::Union{AbstractString, IO})
```
Parse the string or stream `x`, and return the resulting table (dictionary). Return a [`ParserError`](#TOML.ParserError) upon failure.
See also [`TOML.parse`](#TOML.parse).
###
`TOML.tryparsefile`Function
```
tryparsefile(f::AbstractString)
tryparsefile(p::Parser, f::AbstractString)
```
Parse file `f` and return the resulting table (dictionary). Return a [`ParserError`](#TOML.ParserError) upon failure.
See also [`TOML.parsefile`](#TOML.parsefile).
###
`TOML.print`Function
```
print([to_toml::Function], io::IO [=stdout], data::AbstractDict; sorted=false, by=identity)
```
Write `data` as TOML syntax to the stream `io`. If the keyword argument `sorted` is set to `true`, sort tables according to the function given by the keyword argument `by`.
The following data types are supported: `AbstractDict`, `Integer`, `AbstractFloat`, `Bool`, `Dates.DateTime`, `Dates.Time`, `Dates.Date`. Note that the integers and floats need to be convertible to `Float64` and `Int64` respectively. For other data types, pass the function `to_toml` that takes the data types and returns a value of a supported type.
###
`TOML.Parser`Type
```
Parser()
```
Constructor for a TOML `Parser`. Note that in most cases one does not need to explicitly create a `Parser` but instead one directly use use [`TOML.parsefile`](#TOML.parsefile) or [`TOML.parse`](#TOML.parse). Using an explicit parser will however reuse some internal data structures which can be beneficial for performance if a larger number of small files are parsed.
###
`TOML.ParserError`Type
```
ParserError
```
Type that is returned from [`tryparse`](#TOML.tryparse) and [`tryparsefile`](#TOML.tryparsefile) when parsing fails. It contains (among others) the following fields:
* `pos`, the position in the string when the error happened
* `table`, the result that so far was successfully parsed
* `type`, an error type, different for different types of errors
julia Artifacts Artifacts
=========
Starting with Julia 1.6, the artifacts support has moved from `Pkg.jl` to Julia itself. Until proper documentation can be added here, you can learn more about artifacts in the `Pkg.jl` manual at <https://julialang.github.io/Pkg.jl/v1/artifacts/>.
Julia's artifacts API requires at least Julia 1.6. In Julia versions 1.3 to 1.5, you can use `Pkg.Artifacts` instead.
###
`Artifacts.artifact_meta`Function
```
artifact_meta(name::String, artifacts_toml::String;
platform::AbstractPlatform = HostPlatform(),
pkg_uuid::Union{Base.UUID,Nothing}=nothing)
```
Get metadata about a given artifact (identified by name) stored within the given `(Julia)Artifacts.toml` file. If the artifact is platform-specific, use `platform` to choose the most appropriate mapping. If none is found, return `nothing`.
This function requires at least Julia 1.3.
###
`Artifacts.artifact_hash`Function
```
artifact_hash(name::String, artifacts_toml::String;
platform::AbstractPlatform = HostPlatform())
```
Thin wrapper around `artifact_meta()` to return the hash of the specified, platform- collapsed artifact. Returns `nothing` if no mapping can be found.
This function requires at least Julia 1.3.
###
`Artifacts.find_artifacts_toml`Function
```
find_artifacts_toml(path::String)
```
Given the path to a `.jl` file, (such as the one returned by `__source__.file` in a macro context), find the `(Julia)Artifacts.toml` that is contained within the containing project (if it exists), otherwise return `nothing`.
This function requires at least Julia 1.3.
###
`Artifacts.@artifact_str`Macro
```
macro artifact_str(name)
```
Return the on-disk path to an artifact. Automatically looks the artifact up by name in the project's `(Julia)Artifacts.toml` file. Throws an error on if the requested artifact is not present. If run in the REPL, searches for the toml file starting in the current directory, see `find_artifacts_toml()` for more.
If the artifact is marked "lazy" and the package has `using LazyArtifacts` defined, the artifact will be downloaded on-demand with `Pkg` the first time this macro tries to compute the path. The files will then be left installed locally for later.
If `name` contains a forward or backward slash, all elements after the first slash will be taken to be path names indexing into the artifact, allowing for an easy one-liner to access a single file/directory within an artifact. Example:
```
ffmpeg_path = @artifact"FFMPEG/bin/ffmpeg"
```
This macro requires at least Julia 1.3.
Slash-indexing requires at least Julia 1.6.
julia Dates Dates
=====
The `Dates` module provides two types for working with dates: [`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime), representing day and millisecond precision, respectively; both are subtypes of the abstract [`TimeType`](#Dates.TimeType). The motivation for distinct types is simple: some operations are much simpler, both in terms of code and mental reasoning, when the complexities of greater precision don't have to be dealt with. For example, since the [`Date`](#Dates.Date) type only resolves to the precision of a single date (i.e. no hours, minutes, or seconds), normal considerations for time zones, daylight savings/summer time, and leap seconds are unnecessary and avoided.
Both [`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) are basically immutable [`Int64`](../../base/numbers/index#Core.Int64) wrappers. The single `instant` field of either type is actually a `UTInstant{P}` type, which represents a continuously increasing machine timeline based on the UT second [[1]](#footnote-1). The [`DateTime`](#Dates.DateTime) type is not aware of time zones (*naive*, in Python parlance), analogous to a *LocalDateTime* in Java 8. Additional time zone functionality can be added through the [TimeZones.jl package](https://github.com/JuliaTime/TimeZones.jl/), which compiles the [IANA time zone database](http://www.iana.org/time-zones). Both [`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) are based on the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard, which follows the proleptic Gregorian calendar. One note is that the ISO 8601 standard is particular about BC/BCE dates. In general, the last day of the BC/BCE era, 1-12-31 BC/BCE, was followed by 1-1-1 AD/CE, thus no year zero exists. The ISO standard, however, states that 1 BC/BCE is year zero, so `0000-12-31` is the day before `0001-01-01`, and year `-0001` (yes, negative one for the year) is 2 BC/BCE, year `-0002` is 3 BC/BCE, etc.
[Constructors](#Constructors)
------------------------------
[`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) types can be constructed by integer or [`Period`](#Dates.Period) types, by parsing, or through adjusters (more on those later):
```
julia> DateTime(2013)
2013-01-01T00:00:00
julia> DateTime(2013,7)
2013-07-01T00:00:00
julia> DateTime(2013,7,1)
2013-07-01T00:00:00
julia> DateTime(2013,7,1,12)
2013-07-01T12:00:00
julia> DateTime(2013,7,1,12,30)
2013-07-01T12:30:00
julia> DateTime(2013,7,1,12,30,59)
2013-07-01T12:30:59
julia> DateTime(2013,7,1,12,30,59,1)
2013-07-01T12:30:59.001
julia> Date(2013)
2013-01-01
julia> Date(2013,7)
2013-07-01
julia> Date(2013,7,1)
2013-07-01
julia> Date(Dates.Year(2013),Dates.Month(7),Dates.Day(1))
2013-07-01
julia> Date(Dates.Month(7),Dates.Year(2013))
2013-07-01
```
[`Date`](#Dates.Date) or [`DateTime`](#Dates.DateTime) parsing is accomplished by the use of format strings. Format strings work by the notion of defining *delimited* or *fixed-width* "slots" that contain a period to parse and passing the text to parse and format string to a [`Date`](#Dates.Date) or [`DateTime`](#Dates.DateTime) constructor, of the form `Date("2015-01-01",dateformat"y-m-d")` or `DateTime("20150101",dateformat"yyyymmdd")`.
Delimited slots are marked by specifying the delimiter the parser should expect between two subsequent periods; so `"y-m-d"` lets the parser know that between the first and second slots in a date string like `"2014-07-16"`, it should find the `-` character. The `y`, `m`, and `d` characters let the parser know which periods to parse in each slot.
As in the case of constructors above such as `Date(2013)`, delimited `DateFormat`s allow for missing parts of dates and times so long as the preceding parts are given. The other parts are given the usual default values. For example, `Date("1981-03", dateformat"y-m-d")` returns `1981-03-01`, whilst `Date("31/12", dateformat"d/m/y")` gives `0001-12-31`. (Note that the default year is 1 AD/CE.) Consequently, an empty string will always return `0001-01-01` for `Date`s, and `0001-01-01T00:00:00.000` for `DateTime`s.
Fixed-width slots are specified by repeating the period character the number of times corresponding to the width with no delimiter between characters. So `dateformat"yyyymmdd"` would correspond to a date string like `"20140716"`. The parser distinguishes a fixed-width slot by the absence of a delimiter, noting the transition `"yyyymm"` from one period character to the next.
Support for text-form month parsing is also supported through the `u` and `U` characters, for abbreviated and full-length month names, respectively. By default, only English month names are supported, so `u` corresponds to "Jan", "Feb", "Mar", etc. And `U` corresponds to "January", "February", "March", etc. Similar to other name=>value mapping functions [`dayname`](#Dates.dayname) and [`monthname`](#Dates.monthname), custom locales can be loaded by passing in the `locale=>Dict{String,Int}` mapping to the `MONTHTOVALUEABBR` and `MONTHTOVALUE` dicts for abbreviated and full-name month names, respectively.
The above examples used the `dateformat""` string macro. This macro creates a `DateFormat` object once when the macro is expanded and uses the same `DateFormat` object even if a code snippet is run multiple times.
```
julia> for i = 1:10^5
Date("2015-01-01", dateformat"y-m-d")
end
```
Or you can create the DateFormat object explicitly:
```
julia> df = DateFormat("y-m-d");
julia> dt = Date("2015-01-01",df)
2015-01-01
julia> dt2 = Date("2015-01-02",df)
2015-01-02
```
Alternatively, use broadcasting:
```
julia> years = ["2015", "2016"];
julia> Date.(years, DateFormat("yyyy"))
2-element Vector{Date}:
2015-01-01
2016-01-01
```
For convenience, you may pass the format string directly (e.g., `Date("2015-01-01","y-m-d")`), although this form incurs performance costs if you are parsing the same format repeatedly, as it internally creates a new `DateFormat` object each time.
As well as via the constructors, a `Date` or `DateTime` can be constructed from strings using the [`parse`](../../base/numbers/index#Base.parse) and [`tryparse`](../../base/numbers/index#Base.tryparse) functions, but with an optional third argument of type `DateFormat` specifying the format; for example, `parse(Date, "06.23.2013", dateformat"m.d.y")`, or `tryparse(DateTime, "1999-12-31T23:59:59")` which uses the default format. The notable difference between the functions is that with [`tryparse`](../../base/numbers/index#Base.tryparse), an error is not thrown if the string is in an invalid format; instead `nothing` is returned. Note however that as with the constructors above, empty date and time parts assume default values and consequently an empty string (`""`) is valid for *any* `DateFormat`, giving for example a `Date` of `0001-01-01`. Code relying on `parse` or `tryparse` for `Date` and `DateTime` parsing should therefore also check whether parsed strings are empty before using the result.
A full suite of parsing and formatting tests and examples is available in [`stdlib/Dates/test/io.jl`](https://github.com/JuliaLang/julia/blob/master/stdlib/Dates/test/io.jl).
[Durations/Comparisons](#Durations/Comparisons)
------------------------------------------------
Finding the length of time between two [`Date`](#Dates.Date) or [`DateTime`](#Dates.DateTime) is straightforward given their underlying representation as `UTInstant{Day}` and `UTInstant{Millisecond}`, respectively. The difference between [`Date`](#Dates.Date) is returned in the number of [`Day`](#Dates.Day-Tuple%7BTimeType%7D), and [`DateTime`](#Dates.DateTime) in the number of [`Millisecond`](#Dates.Millisecond-Tuple%7BDateTime%7D). Similarly, comparing [`TimeType`](#Dates.TimeType) is a simple matter of comparing the underlying machine instants (which in turn compares the internal [`Int64`](../../base/numbers/index#Core.Int64) values).
```
julia> dt = Date(2012,2,29)
2012-02-29
julia> dt2 = Date(2000,2,1)
2000-02-01
julia> dump(dt)
Date
instant: Dates.UTInstant{Day}
periods: Day
value: Int64 734562
julia> dump(dt2)
Date
instant: Dates.UTInstant{Day}
periods: Day
value: Int64 730151
julia> dt > dt2
true
julia> dt != dt2
true
julia> dt + dt2
ERROR: MethodError: no method matching +(::Date, ::Date)
[...]
julia> dt * dt2
ERROR: MethodError: no method matching *(::Date, ::Date)
[...]
julia> dt / dt2
ERROR: MethodError: no method matching /(::Date, ::Date)
julia> dt - dt2
4411 days
julia> dt2 - dt
-4411 days
julia> dt = DateTime(2012,2,29)
2012-02-29T00:00:00
julia> dt2 = DateTime(2000,2,1)
2000-02-01T00:00:00
julia> dt - dt2
381110400000 milliseconds
```
[Accessor Functions](#Accessor-Functions)
------------------------------------------
Because the [`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) types are stored as single [`Int64`](../../base/numbers/index#Core.Int64) values, date parts or fields can be retrieved through accessor functions. The lowercase accessors return the field as an integer:
```
julia> t = Date(2014, 1, 31)
2014-01-31
julia> Dates.year(t)
2014
julia> Dates.month(t)
1
julia> Dates.week(t)
5
julia> Dates.day(t)
31
```
While propercase return the same value in the corresponding [`Period`](#Dates.Period) type:
```
julia> Dates.Year(t)
2014 years
julia> Dates.Day(t)
31 days
```
Compound methods are provided because it is more efficient to access multiple fields at the same time than individually:
```
julia> Dates.yearmonth(t)
(2014, 1)
julia> Dates.monthday(t)
(1, 31)
julia> Dates.yearmonthday(t)
(2014, 1, 31)
```
One may also access the underlying `UTInstant` or integer value:
```
julia> dump(t)
Date
instant: Dates.UTInstant{Day}
periods: Day
value: Int64 735264
julia> t.instant
Dates.UTInstant{Day}(Day(735264))
julia> Dates.value(t)
735264
```
[Query Functions](#Query-Functions)
------------------------------------
Query functions provide calendrical information about a [`TimeType`](#Dates.TimeType). They include information about the day of the week:
```
julia> t = Date(2014, 1, 31)
2014-01-31
julia> Dates.dayofweek(t)
5
julia> Dates.dayname(t)
"Friday"
julia> Dates.dayofweekofmonth(t) # 5th Friday of January
5
```
Month of the year:
```
julia> Dates.monthname(t)
"January"
julia> Dates.daysinmonth(t)
31
```
As well as information about the [`TimeType`](#Dates.TimeType)'s year and quarter:
```
julia> Dates.isleapyear(t)
false
julia> Dates.dayofyear(t)
31
julia> Dates.quarterofyear(t)
1
julia> Dates.dayofquarter(t)
31
```
The [`dayname`](#Dates.dayname) and [`monthname`](#Dates.monthname) methods can also take an optional `locale` keyword that can be used to return the name of the day or month of the year for other languages/locales. There are also versions of these functions returning the abbreviated names, namely [`dayabbr`](#Dates.dayabbr) and [`monthabbr`](#Dates.monthabbr). First the mapping is loaded into the `LOCALES` variable:
```
julia> french_months = ["janvier", "février", "mars", "avril", "mai", "juin",
"juillet", "août", "septembre", "octobre", "novembre", "décembre"];
julia> french_monts_abbrev = ["janv","févr","mars","avril","mai","juin",
"juil","août","sept","oct","nov","déc"];
julia> french_days = ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"];
julia> Dates.LOCALES["french"] = Dates.DateLocale(french_months, french_monts_abbrev, french_days, [""]);
```
The above mentioned functions can then be used to perform the queries:
```
julia> Dates.dayname(t;locale="french")
"vendredi"
julia> Dates.monthname(t;locale="french")
"janvier"
julia> Dates.monthabbr(t;locale="french")
"janv"
```
Since the abbreviated versions of the days are not loaded, trying to use the function `dayabbr` will error.
```
julia> Dates.dayabbr(t;locale="french")
ERROR: BoundsError: attempt to access 1-element Vector{String} at index [5]
Stacktrace:
[...]
```
[TimeType-Period Arithmetic](#TimeType-Period-Arithmetic)
----------------------------------------------------------
It's good practice when using any language/date framework to be familiar with how date-period arithmetic is handled as there are some [tricky issues](https://codeblog.jonskeet.uk/2010/12/01/the-joys-of-date-time-arithmetic/) to deal with (though much less so for day-precision types).
The `Dates` module approach tries to follow the simple principle of trying to change as little as possible when doing [`Period`](#Dates.Period) arithmetic. This approach is also often known as *calendrical* arithmetic or what you would probably guess if someone were to ask you the same calculation in a conversation. Why all the fuss about this? Let's take a classic example: add 1 month to January 31st, 2014. What's the answer? Javascript will say [March 3](https://markhneedham.com/blog/2009/01/07/javascript-add-a-month-to-a-date/) (assumes 31 days). PHP says [March 2](https://stackoverflow.com/questions/5760262/php-adding-months-to-a-date-while-not-exceeding-the-last-day-of-the-month) (assumes 30 days). The fact is, there is no right answer. In the `Dates` module, it gives the result of February 28th. How does it figure that out? Consider the classic 7-7-7 gambling game in casinos.
Now just imagine that instead of 7-7-7, the slots are Year-Month-Day, or in our example, 2014-01-31. When you ask to add 1 month to this date, the month slot is incremented, so now we have 2014-02-31. Then the day number is checked if it is greater than the last valid day of the new month; if it is (as in the case above), the day number is adjusted down to the last valid day (28). What are the ramifications with this approach? Go ahead and add another month to our date, `2014-02-28 + Month(1) == 2014-03-28`. What? Were you expecting the last day of March? Nope, sorry, remember the 7-7-7 slots. As few slots as possible are going to change, so we first increment the month slot by 1, 2014-03-28, and boom, we're done because that's a valid date. On the other hand, if we were to add 2 months to our original date, 2014-01-31, then we end up with 2014-03-31, as expected. The other ramification of this approach is a loss in associativity when a specific ordering is forced (i.e. adding things in different orders results in different outcomes). For example:
```
julia> (Date(2014,1,29)+Dates.Day(1)) + Dates.Month(1)
2014-02-28
julia> (Date(2014,1,29)+Dates.Month(1)) + Dates.Day(1)
2014-03-01
```
What's going on there? In the first line, we're adding 1 day to January 29th, which results in 2014-01-30; then we add 1 month, so we get 2014-02-30, which then adjusts down to 2014-02-28. In the second example, we add 1 month *first*, where we get 2014-02-29, which adjusts down to 2014-02-28, and *then* add 1 day, which results in 2014-03-01. One design principle that helps in this case is that, in the presence of multiple Periods, the operations will be ordered by the Periods' *types*, not their value or positional order; this means `Year` will always be added first, then `Month`, then `Week`, etc. Hence the following *does* result in associativity and Just Works:
```
julia> Date(2014,1,29) + Dates.Day(1) + Dates.Month(1)
2014-03-01
julia> Date(2014,1,29) + Dates.Month(1) + Dates.Day(1)
2014-03-01
```
Tricky? Perhaps. What is an innocent `Dates` user to do? The bottom line is to be aware that explicitly forcing a certain associativity, when dealing with months, may lead to some unexpected results, but otherwise, everything should work as expected. Thankfully, that's pretty much the extent of the odd cases in date-period arithmetic when dealing with time in UT (avoiding the "joys" of dealing with daylight savings, leap seconds, etc.).
As a bonus, all period arithmetic objects work directly with ranges:
```
julia> dr = Date(2014,1,29):Day(1):Date(2014,2,3)
Date("2014-01-29"):Day(1):Date("2014-02-03")
julia> collect(dr)
6-element Vector{Date}:
2014-01-29
2014-01-30
2014-01-31
2014-02-01
2014-02-02
2014-02-03
julia> dr = Date(2014,1,29):Dates.Month(1):Date(2014,07,29)
Date("2014-01-29"):Month(1):Date("2014-07-29")
julia> collect(dr)
7-element Vector{Date}:
2014-01-29
2014-02-28
2014-03-29
2014-04-29
2014-05-29
2014-06-29
2014-07-29
```
[Adjuster Functions](#Adjuster-Functions)
------------------------------------------
As convenient as date-period arithmetic is, often the kinds of calculations needed on dates take on a *calendrical* or *temporal* nature rather than a fixed number of periods. Holidays are a perfect example; most follow rules such as "Memorial Day = Last Monday of May", or "Thanksgiving = 4th Thursday of November". These kinds of temporal expressions deal with rules relative to the calendar, like first or last of the month, next Tuesday, or the first and third Wednesdays, etc.
The `Dates` module provides the *adjuster* API through several convenient methods that aid in simply and succinctly expressing temporal rules. The first group of adjuster methods deal with the first and last of weeks, months, quarters, and years. They each take a single [`TimeType`](#Dates.TimeType) as input and return or *adjust to* the first or last of the desired period relative to the input.
```
julia> Dates.firstdayofweek(Date(2014,7,16)) # Adjusts the input to the Monday of the input's week
2014-07-14
julia> Dates.lastdayofmonth(Date(2014,7,16)) # Adjusts to the last day of the input's month
2014-07-31
julia> Dates.lastdayofquarter(Date(2014,7,16)) # Adjusts to the last day of the input's quarter
2014-09-30
```
The next two higher-order methods, [`tonext`](#Dates.tonext-Tuple%7BTimeType,%20Int64%7D), and [`toprev`](#Dates.toprev-Tuple%7BTimeType,%20Int64%7D), generalize working with temporal expressions by taking a `DateFunction` as first argument, along with a starting [`TimeType`](#Dates.TimeType). A `DateFunction` is just a function, usually anonymous, that takes a single [`TimeType`](#Dates.TimeType) as input and returns a [`Bool`](../../base/numbers/index#Core.Bool), `true` indicating a satisfied adjustment criterion. For example:
```
julia> istuesday = x->Dates.dayofweek(x) == Dates.Tuesday; # Returns true if the day of the week of x is Tuesday
julia> Dates.tonext(istuesday, Date(2014,7,13)) # 2014-07-13 is a Sunday
2014-07-15
julia> Dates.tonext(Date(2014,7,13), Dates.Tuesday) # Convenience method provided for day of the week adjustments
2014-07-15
```
This is useful with the do-block syntax for more complex temporal expressions:
```
julia> Dates.tonext(Date(2014,7,13)) do x
# Return true on the 4th Thursday of November (Thanksgiving)
Dates.dayofweek(x) == Dates.Thursday &&
Dates.dayofweekofmonth(x) == 4 &&
Dates.month(x) == Dates.November
end
2014-11-27
```
The [`Base.filter`](../../base/collections/index#Base.filter) method can be used to obtain all valid dates/moments in a specified range:
```
# Pittsburgh street cleaning; Every 2nd Tuesday from April to November
# Date range from January 1st, 2014 to January 1st, 2015
julia> dr = Dates.Date(2014):Day(1):Dates.Date(2015);
julia> filter(dr) do x
Dates.dayofweek(x) == Dates.Tue &&
Dates.April <= Dates.month(x) <= Dates.Nov &&
Dates.dayofweekofmonth(x) == 2
end
8-element Vector{Date}:
2014-04-08
2014-05-13
2014-06-10
2014-07-08
2014-08-12
2014-09-09
2014-10-14
2014-11-11
```
Additional examples and tests are available in [`stdlib/Dates/test/adjusters.jl`](https://github.com/JuliaLang/julia/blob/master/stdlib/Dates/test/adjusters.jl).
[Period Types](#Period-Types)
------------------------------
Periods are a human view of discrete, sometimes irregular durations of time. Consider 1 month; it could represent, in days, a value of 28, 29, 30, or 31 depending on the year and month context. Or a year could represent 365 or 366 days in the case of a leap year. [`Period`](#Dates.Period) types are simple [`Int64`](../../base/numbers/index#Core.Int64) wrappers and are constructed by wrapping any `Int64` convertible type, i.e. `Year(1)` or `Month(3.0)`. Arithmetic between [`Period`](#Dates.Period) of the same type behave like integers, and limited `Period-Real` arithmetic is available. You can extract the underlying integer with [`Dates.value`](#Dates.value).
```
julia> y1 = Dates.Year(1)
1 year
julia> y2 = Dates.Year(2)
2 years
julia> y3 = Dates.Year(10)
10 years
julia> y1 + y2
3 years
julia> div(y3,y2)
5
julia> y3 - y2
8 years
julia> y3 % y2
0 years
julia> div(y3,3) # mirrors integer division
3 years
julia> Dates.value(Dates.Millisecond(10))
10
```
Representing periods or durations that are not integer multiples of the basic types can be achieved with the [`Dates.CompoundPeriod`](#Dates.CompoundPeriod) type. Compound periods may be constructed manually from simple [`Period`](#Dates.Period) types. Additionally, the [`canonicalize`](#Dates.canonicalize) function can be used to break down a period into a [`Dates.CompoundPeriod`](#Dates.CompoundPeriod). This is particularly useful to convert a duration, e.g., a difference of two `DateTime`, into a more convenient representation.
```
julia> cp = Dates.CompoundPeriod(Day(1),Minute(1))
1 day, 1 minute
julia> t1 = DateTime(2018,8,8,16,58,00)
2018-08-08T16:58:00
julia> t2 = DateTime(2021,6,23,10,00,00)
2021-06-23T10:00:00
julia> canonicalize(t2-t1) # creates a CompoundPeriod
149 weeks, 6 days, 17 hours, 2 minutes
```
[Rounding](#Rounding)
----------------------
[`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with [`floor`](../../base/math/index#Base.floor), [`ceil`](../../base/math/index#Base.ceil), or [`round`](#):
```
julia> floor(Date(1985, 8, 16), Dates.Month)
1985-08-01
julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
2013-02-13T00:45:00
julia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day)
2016-08-07T00:00:00
```
Unlike the numeric [`round`](#) method, which breaks ties toward the even number by default, the [`TimeType`](#Dates.TimeType)[`round`](#) method uses the `RoundNearestTiesUp` rounding mode. (It's difficult to guess what breaking ties to nearest "even" [`TimeType`](#Dates.TimeType) would entail.) Further details on the available `RoundingMode` s can be found in the [API reference](#stdlib-dates-api).
Rounding should generally behave as expected, but there are a few cases in which the expected behaviour is not obvious.
###
[Rounding Epoch](#Rounding-Epoch)
In many cases, the resolution specified for rounding (e.g., `Dates.Second(30)`) divides evenly into the next largest period (in this case, `Dates.Minute(1)`). But rounding behaviour in cases in which this is not true may lead to confusion. What is the expected result of rounding a [`DateTime`](#Dates.DateTime) to the nearest 10 hours?
```
julia> round(DateTime(2016, 7, 17, 11, 55), Dates.Hour(10))
2016-07-17T12:00:00
```
That may seem confusing, given that the hour (12) is not divisible by 10. The reason that `2016-07-17T12:00:00` was chosen is that it is 17,676,660 hours after `0000-01-01T00:00:00`, and 17,676,660 is divisible by 10.
As Julia [`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) values are represented according to the ISO 8601 standard, `0000-01-01T00:00:00` was chosen as base (or "rounding epoch") from which to begin the count of days (and milliseconds) used in rounding calculations. (Note that this differs slightly from Julia's internal representation of [`Date`](#Dates.Date) s using Rata Die notation; but since the ISO 8601 standard is most visible to the end user, `0000-01-01T00:00:00` was chosen as the rounding epoch instead of the `0000-12-31T00:00:00` used internally to minimize confusion.)
The only exception to the use of `0000-01-01T00:00:00` as the rounding epoch is when rounding to weeks. Rounding to the nearest week will always return a Monday (the first day of the week as specified by ISO 8601). For this reason, we use `0000-01-03T00:00:00` (the first day of the first week of year 0000, as defined by ISO 8601) as the base when rounding to a number of weeks.
Here is a related case in which the expected behaviour is not necessarily obvious: What happens when we round to the nearest `P(2)`, where `P` is a [`Period`](#Dates.Period) type? In some cases (specifically, when `P <: Dates.TimePeriod`) the answer is clear:
```
julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Hour(2))
2016-07-17T08:00:00
julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Minute(2))
2016-07-17T08:56:00
```
This seems obvious, because two of each of these periods still divides evenly into the next larger order period. But in the case of two months (which still divides evenly into one year), the answer may be surprising:
```
julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Month(2))
2016-07-01T00:00:00
```
Why round to the first day in July, even though it is month 7 (an odd number)? The key is that months are 1-indexed (the first month is assigned 1), unlike hours, minutes, seconds, and milliseconds (the first of which are assigned 0).
This means that rounding a [`DateTime`](#Dates.DateTime) to an even multiple of seconds, minutes, hours, or years (because the ISO 8601 specification includes a year zero) will result in a [`DateTime`](#Dates.DateTime) with an even value in that field, while rounding a [`DateTime`](#Dates.DateTime) to an even multiple of months will result in the months field having an odd value. Because both months and years may contain an irregular number of days, whether rounding to an even number of days will result in an even value in the days field is uncertain.
See the [API reference](#stdlib-dates-api) for additional information on methods exported from the `Dates` module.
[API reference](#stdlib-dates-api)
===================================
[Dates and Time Types](#Dates-and-Time-Types)
----------------------------------------------
###
`Dates.Period`Type
```
Period
Year
Quarter
Month
Week
Day
Hour
Minute
Second
Millisecond
Microsecond
Nanosecond
```
`Period` types represent discrete, human representations of time.
###
`Dates.CompoundPeriod`Type
```
CompoundPeriod
```
A `CompoundPeriod` is useful for expressing time periods that are not a fixed multiple of smaller periods. For example, "a year and a day" is not a fixed number of days, but can be expressed using a `CompoundPeriod`. In fact, a `CompoundPeriod` is automatically generated by addition of different period types, e.g. `Year(1) + Day(1)` produces a `CompoundPeriod` result.
###
`Dates.Instant`Type
```
Instant
```
`Instant` types represent integer-based, machine representations of time as continuous timelines starting from an epoch.
###
`Dates.UTInstant`Type
```
UTInstant{T}
```
The `UTInstant` represents a machine timeline based on UT time (1 day = one revolution of the earth). The `T` is a `Period` parameter that indicates the resolution or precision of the instant.
###
`Dates.TimeType`Type
```
TimeType
```
`TimeType` types wrap `Instant` machine instances to provide human representations of the machine instant. `Time`, `DateTime` and `Date` are subtypes of `TimeType`.
###
`Dates.DateTime`Type
```
DateTime
```
`DateTime` wraps a `UTInstant{Millisecond}` and interprets it according to the proleptic Gregorian calendar.
###
`Dates.Date`Type
```
Date
```
`Date` wraps a `UTInstant{Day}` and interprets it according to the proleptic Gregorian calendar.
###
`Dates.Time`Type
```
Time
```
`Time` wraps a `Nanosecond` and represents a specific moment in a 24-hour day.
###
`Dates.TimeZone`Type
```
TimeZone
```
Geographic zone generally based on longitude determining what the time is at a certain location. Some time zones observe daylight savings (eg EST -> EDT). For implementations and more support, see the [`TimeZones.jl`](https://github.com/JuliaTime/TimeZones.jl) package
###
`Dates.UTC`Type
```
UTC
```
`UTC`, or Coordinated Universal Time, is the [`TimeZone`](#Dates.TimeZone) from which all others are measured. It is associated with the time at 0° longitude. It is not adjusted for daylight savings.
[Dates Functions](#Dates-Functions)
------------------------------------
###
`Dates.DateTime`Method
```
DateTime(y, [m, d, h, mi, s, ms]) -> DateTime
```
Construct a `DateTime` type by parts. Arguments must be convertible to [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.DateTime`Method
```
DateTime(periods::Period...) -> DateTime
```
Construct a `DateTime` type by `Period` type parts. Arguments may be in any order. DateTime parts not provided will default to the value of `Dates.default(period)`.
###
`Dates.DateTime`Method
```
DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), limit=10000) -> DateTime
```
Create a `DateTime` through the adjuster API. The starting point will be constructed from the provided `y, m, d...` arguments, and will be adjusted until `f::Function` returns `true`. The step size in adjusting can be provided manually through the `step` keyword. `limit` provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that `f::Function` is never satisfied).
**Examples**
```
julia> DateTime(dt -> Dates.second(dt) == 40, 2010, 10, 20, 10; step = Dates.Second(1))
2010-10-20T10:00:40
julia> DateTime(dt -> Dates.hour(dt) == 20, 2010, 10, 20, 10; step = Dates.Hour(1), limit = 5)
ERROR: ArgumentError: Adjustment limit reached: 5 iterations
Stacktrace:
[...]
```
###
`Dates.DateTime`Method
```
DateTime(dt::Date) -> DateTime
```
Convert a `Date` to a `DateTime`. The hour, minute, second, and millisecond parts of the new `DateTime` are assumed to be zero.
###
`Dates.DateTime`Method
```
DateTime(dt::AbstractString, format::AbstractString; locale="english") -> DateTime
```
Construct a `DateTime` by parsing the `dt` date time string following the pattern given in the `format` string (see [`DateFormat`](#Dates.DateFormat) for syntax).
This method creates a `DateFormat` object each time it is called. It is recommended that you create a [`DateFormat`](#Dates.DateFormat) object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.
**Example**
```
julia> DateTime("2020-01-01", "yyyy-mm-dd")
2020-01-01T00:00:00
julia> a = ("2020-01-01", "2020-01-02");
julia> [DateTime(d, dateformat"yyyy-mm-dd") for d ∈ a] # preferred
2-element Vector{DateTime}:
2020-01-01T00:00:00
2020-01-02T00:00:00
```
###
`Dates.format`Method
```
format(dt::TimeType, format::AbstractString; locale="english") -> AbstractString
```
Construct a string by using a `TimeType` object and applying the provided `format`. The following character codes can be used to construct the `format` string:
| Code | Examples | Comment |
| --- | --- | --- |
| `y` | 6 | Numeric year with a fixed width |
| `Y` | 1996 | Numeric year with a minimum width |
| `m` | 1, 12 | Numeric month with a minimum width |
| `u` | Jan | Month name shortened to 3-chars according to the `locale` |
| `U` | January | Full month name according to the `locale` keyword |
| `d` | 1, 31 | Day of the month with a minimum width |
| `H` | 0, 23 | Hour (24-hour clock) with a minimum width |
| `M` | 0, 59 | Minute with a minimum width |
| `S` | 0, 59 | Second with a minimum width |
| `s` | 000, 500 | Millisecond with a minimum width of 3 |
| `e` | Mon, Tue | Abbreviated days of the week |
| `E` | Monday | Full day of week name |
The number of sequential code characters indicate the width of the code. A format of `yyyy-mm` specifies that the code `y` should have a width of four while `m` a width of two. Codes that yield numeric digits have an associated mode: fixed-width or minimum-width. The fixed-width mode left-pads the value with zeros when it is shorter than the specified width and truncates the value when longer. Minimum-width mode works the same as fixed-width except that it does not truncate values longer than the width.
When creating a `format` you can use any non-code characters as a separator. For example to generate the string "1996-01-15T00:00:00" you could use `format`: "yyyy-mm-ddTHH:MM:SS". Note that if you need to use a code character as a literal you can use the escape character backslash. The string "1996y01m" can be produced with the format "yyyy\ymm\m".
###
`Dates.DateFormat`Type
```
DateFormat(format::AbstractString, locale="english") -> DateFormat
```
Construct a date formatting object that can be used for parsing date strings or formatting a date object as a string. The following character codes can be used to construct the `format` string:
| Code | Matches | Comment |
| --- | --- | --- |
| `y` | 1996, 96 | Returns year of 1996, 0096 |
| `Y` | 1996, 96 | Returns year of 1996, 0096. Equivalent to `y` |
| `m` | 1, 01 | Matches 1 or 2-digit months |
| `u` | Jan | Matches abbreviated months according to the `locale` keyword |
| `U` | January | Matches full month names according to the `locale` keyword |
| `d` | 1, 01 | Matches 1 or 2-digit days |
| `H` | 00 | Matches hours (24-hour clock) |
| `I` | 00 | For outputting hours with 12-hour clock |
| `M` | 00 | Matches minutes |
| `S` | 00 | Matches seconds |
| `s` | .500 | Matches milliseconds |
| `e` | Mon, Tues | Matches abbreviated days of the week |
| `E` | Monday | Matches full name days of the week |
| `p` | AM | Matches AM/PM (case-insensitive) |
| `yyyymmdd` | 19960101 | Matches fixed-width year, month, and day |
Characters not listed above are normally treated as delimiters between date and time slots. For example a `dt` string of "1996-01-15T00:00:00.0" would have a `format` string like "y-m-dTH:M:S.s". If you need to use a code character as a delimiter you can escape it using backslash. The date "1995y01m" would have the format "y\ym\m".
Note that 12:00AM corresponds 00:00 (midnight), and 12:00PM corresponds to 12:00 (noon). When parsing a time with a `p` specifier, any hour (either `H` or `I`) is interpreted as as a 12-hour clock, so the `I` code is mainly useful for output.
Creating a DateFormat object is expensive. Whenever possible, create it once and use it many times or try the [`dateformat""`](#Dates.@dateformat_str) string macro. Using this macro creates the DateFormat object once at macro expansion time and reuses it later. There are also several [pre-defined formatters](#Common-Date-Formatters), listed later.
See [`DateTime`](#Dates.DateTime) and [`format`](#Dates.format-Tuple%7BTimeType,%20AbstractString%7D) for how to use a DateFormat object to parse and write Date strings respectively.
###
`Dates.@dateformat_str`Macro
```
dateformat"Y-m-d H:M:S"
```
Create a [`DateFormat`](#Dates.DateFormat) object. Similar to `DateFormat("Y-m-d H:M:S")` but creates the DateFormat object once during macro expansion.
See [`DateFormat`](#Dates.DateFormat) for details about format specifiers.
###
`Dates.DateTime`Method
```
DateTime(dt::AbstractString, df::DateFormat=ISODateTimeFormat) -> DateTime
```
Construct a `DateTime` by parsing the `dt` date time string following the pattern given in the [`DateFormat`](#Dates.DateFormat) object, or dateformat"yyyy-mm-ddTHH:MM:SS.s" if omitted.
Similar to `DateTime(::AbstractString, ::AbstractString)` but more efficient when repeatedly parsing similarly formatted date time strings with a pre-created `DateFormat` object.
###
`Dates.Date`Method
```
Date(y, [m, d]) -> Date
```
Construct a `Date` type by parts. Arguments must be convertible to [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Date`Method
```
Date(period::Period...) -> Date
```
Construct a `Date` type by `Period` type parts. Arguments may be in any order. `Date` parts not provided will default to the value of `Dates.default(period)`.
###
`Dates.Date`Method
```
Date(f::Function, y[, m, d]; step=Day(1), limit=10000) -> Date
```
Create a `Date` through the adjuster API. The starting point will be constructed from the provided `y, m, d` arguments, and will be adjusted until `f::Function` returns `true`. The step size in adjusting can be provided manually through the `step` keyword. `limit` provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (given that `f::Function` is never satisfied).
**Examples**
```
julia> Date(date -> Dates.week(date) == 20, 2010, 01, 01)
2010-05-17
julia> Date(date -> Dates.year(date) == 2010, 2000, 01, 01)
2010-01-01
julia> Date(date -> Dates.month(date) == 10, 2000, 01, 01; limit = 5)
ERROR: ArgumentError: Adjustment limit reached: 5 iterations
Stacktrace:
[...]
```
###
`Dates.Date`Method
```
Date(dt::DateTime) -> Date
```
Convert a `DateTime` to a `Date`. The hour, minute, second, and millisecond parts of the `DateTime` are truncated, so only the year, month and day parts are used in construction.
###
`Dates.Date`Method
```
Date(d::AbstractString, format::AbstractString; locale="english") -> Date
```
Construct a `Date` by parsing the `d` date string following the pattern given in the `format` string (see [`DateFormat`](#Dates.DateFormat) for syntax).
This method creates a `DateFormat` object each time it is called. It is recommended that you create a [`DateFormat`](#Dates.DateFormat) object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.
**Example**
```
julia> Date("2020-01-01", "yyyy-mm-dd")
2020-01-01
julia> a = ("2020-01-01", "2020-01-02");
julia> [Date(d, dateformat"yyyy-mm-dd") for d ∈ a] # preferred
2-element Vector{Date}:
2020-01-01
2020-01-02
```
###
`Dates.Date`Method
```
Date(d::AbstractString, df::DateFormat=ISODateFormat) -> Date
```
Construct a `Date` by parsing the `d` date string following the pattern given in the [`DateFormat`](#Dates.DateFormat) object, or dateformat"yyyy-mm-dd" if omitted.
Similar to `Date(::AbstractString, ::AbstractString)` but more efficient when repeatedly parsing similarly formatted date strings with a pre-created `DateFormat` object.
###
`Dates.Time`Method
```
Time(h, [mi, s, ms, us, ns]) -> Time
```
Construct a `Time` type by parts. Arguments must be convertible to [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Time`Method
```
Time(period::TimePeriod...) -> Time
```
Construct a `Time` type by `Period` type parts. Arguments may be in any order. `Time` parts not provided will default to the value of `Dates.default(period)`.
###
`Dates.Time`Method
```
Time(f::Function, h, mi=0; step::Period=Second(1), limit::Int=10000)
Time(f::Function, h, mi, s; step::Period=Millisecond(1), limit::Int=10000)
Time(f::Function, h, mi, s, ms; step::Period=Microsecond(1), limit::Int=10000)
Time(f::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), limit::Int=10000)
```
Create a `Time` through the adjuster API. The starting point will be constructed from the provided `h, mi, s, ms, us` arguments, and will be adjusted until `f::Function` returns `true`. The step size in adjusting can be provided manually through the `step` keyword. `limit` provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that `f::Function` is never satisfied). Note that the default step will adjust to allow for greater precision for the given arguments; i.e. if hour, minute, and second arguments are provided, the default step will be `Millisecond(1)` instead of `Second(1)`.
**Examples**
```
julia> Dates.Time(t -> Dates.minute(t) == 30, 20)
20:30:00
julia> Dates.Time(t -> Dates.minute(t) == 0, 20)
20:00:00
julia> Dates.Time(t -> Dates.hour(t) == 10, 3; limit = 5)
ERROR: ArgumentError: Adjustment limit reached: 5 iterations
Stacktrace:
[...]
```
###
`Dates.Time`Method
```
Time(dt::DateTime) -> Time
```
Convert a `DateTime` to a `Time`. The hour, minute, second, and millisecond parts of the `DateTime` are used to create the new `Time`. Microsecond and nanoseconds are zero by default.
###
`Dates.Time`Method
```
Time(t::AbstractString, format::AbstractString; locale="english") -> Time
```
Construct a `Time` by parsing the `t` time string following the pattern given in the `format` string (see [`DateFormat`](#Dates.DateFormat) for syntax).
This method creates a `DateFormat` object each time it is called. It is recommended that you create a [`DateFormat`](#Dates.DateFormat) object instead and use that as the second argument to avoid performance loss when using the same format repeatedly.
**Example**
```
julia> Time("12:34pm", "HH:MMp")
12:34:00
julia> a = ("12:34pm", "2:34am");
julia> [Time(d, dateformat"HH:MMp") for d ∈ a] # preferred
2-element Vector{Time}:
12:34:00
02:34:00
```
###
`Dates.Time`Method
```
Time(t::AbstractString, df::DateFormat=ISOTimeFormat) -> Time
```
Construct a `Time` by parsing the `t` date time string following the pattern given in the [`DateFormat`](#Dates.DateFormat) object, or dateformat"HH:MM:SS.s" if omitted.
Similar to `Time(::AbstractString, ::AbstractString)` but more efficient when repeatedly parsing similarly formatted time strings with a pre-created `DateFormat` object.
###
`Dates.now`Method
```
now() -> DateTime
```
Return a `DateTime` corresponding to the user's system time including the system timezone locale.
###
`Dates.now`Method
```
now(::Type{UTC}) -> DateTime
```
Return a `DateTime` corresponding to the user's system time as UTC/GMT.
###
`Base.eps`Method
```
eps(::Type{DateTime}) -> Millisecond
eps(::Type{Date}) -> Day
eps(::Type{Time}) -> Nanosecond
eps(::TimeType) -> Period
```
Return the smallest unit value supported by the `TimeType`.
**Examples**
```
julia> eps(DateTime)
1 millisecond
julia> eps(Date)
1 day
julia> eps(Time)
1 nanosecond
```
###
[Accessor Functions](#Accessor-Functions-2)
###
`Dates.year`Function
```
year(dt::TimeType) -> Int64
```
The year of a `Date` or `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.month`Function
```
month(dt::TimeType) -> Int64
```
The month of a `Date` or `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.week`Function
```
week(dt::TimeType) -> Int64
```
Return the [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) of a `Date` or `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64). Note that the first week of a year is the week that contains the first Thursday of the year, which can result in dates prior to January 4th being in the last week of the previous year. For example, `week(Date(2005, 1, 1))` is the 53rd week of 2004.
**Examples**
```
julia> Dates.week(Date(1989, 6, 22))
25
julia> Dates.week(Date(2005, 1, 1))
53
julia> Dates.week(Date(2004, 12, 31))
53
```
###
`Dates.day`Function
```
day(dt::TimeType) -> Int64
```
The day of month of a `Date` or `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.hour`Function
```
hour(dt::DateTime) -> Int64
```
The hour of day of a `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
```
hour(t::Time) -> Int64
```
The hour of a `Time` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.minute`Function
```
minute(dt::DateTime) -> Int64
```
The minute of a `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
```
minute(t::Time) -> Int64
```
The minute of a `Time` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.second`Function
```
second(dt::DateTime) -> Int64
```
The second of a `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
```
second(t::Time) -> Int64
```
The second of a `Time` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.millisecond`Function
```
millisecond(dt::DateTime) -> Int64
```
The millisecond of a `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
```
millisecond(t::Time) -> Int64
```
The millisecond of a `Time` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.microsecond`Function
```
microsecond(t::Time) -> Int64
```
The microsecond of a `Time` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.nanosecond`Function
```
nanosecond(t::Time) -> Int64
```
The nanosecond of a `Time` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Year`Method
```
Year(v)
```
Construct a `Year` object with the given `v` value. Input must be losslessly convertible to an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Month`Method
```
Month(v)
```
Construct a `Month` object with the given `v` value. Input must be losslessly convertible to an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Week`Method
```
Week(v)
```
Construct a `Week` object with the given `v` value. Input must be losslessly convertible to an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Day`Method
```
Day(v)
```
Construct a `Day` object with the given `v` value. Input must be losslessly convertible to an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.Hour`Method
```
Hour(dt::DateTime) -> Hour
```
The hour part of a DateTime as a `Hour`.
###
`Dates.Minute`Method
```
Minute(dt::DateTime) -> Minute
```
The minute part of a DateTime as a `Minute`.
###
`Dates.Second`Method
```
Second(dt::DateTime) -> Second
```
The second part of a DateTime as a `Second`.
###
`Dates.Millisecond`Method
```
Millisecond(dt::DateTime) -> Millisecond
```
The millisecond part of a DateTime as a `Millisecond`.
###
`Dates.Microsecond`Method
```
Microsecond(dt::Time) -> Microsecond
```
The microsecond part of a Time as a `Microsecond`.
###
`Dates.Nanosecond`Method
```
Nanosecond(dt::Time) -> Nanosecond
```
The nanosecond part of a Time as a `Nanosecond`.
###
`Dates.yearmonth`Function
```
yearmonth(dt::TimeType) -> (Int64, Int64)
```
Simultaneously return the year and month parts of a `Date` or `DateTime`.
###
`Dates.monthday`Function
```
monthday(dt::TimeType) -> (Int64, Int64)
```
Simultaneously return the month and day parts of a `Date` or `DateTime`.
###
`Dates.yearmonthday`Function
```
yearmonthday(dt::TimeType) -> (Int64, Int64, Int64)
```
Simultaneously return the year, month and day parts of a `Date` or `DateTime`.
###
[Query Functions](#Query-Functions-2)
###
`Dates.dayname`Function
```
dayname(dt::TimeType; locale="english") -> String
dayname(day::Integer; locale="english") -> String
```
Return the full day name corresponding to the day of the week of the `Date` or `DateTime` in the given `locale`. Also accepts `Integer`.
**Examples**
```
julia> Dates.dayname(Date("2000-01-01"))
"Saturday"
julia> Dates.dayname(4)
"Thursday"
```
###
`Dates.dayabbr`Function
```
dayabbr(dt::TimeType; locale="english") -> String
dayabbr(day::Integer; locale="english") -> String
```
Return the abbreviated name corresponding to the day of the week of the `Date` or `DateTime` in the given `locale`. Also accepts `Integer`.
**Examples**
```
julia> Dates.dayabbr(Date("2000-01-01"))
"Sat"
julia> Dates.dayabbr(3)
"Wed"
```
###
`Dates.dayofweek`Function
```
dayofweek(dt::TimeType) -> Int64
```
Return the day of the week as an [`Int64`](../../base/numbers/index#Core.Int64) with `1 = Monday, 2 = Tuesday, etc.`.
**Examples**
```
julia> Dates.dayofweek(Date("2000-01-01"))
6
```
###
`Dates.dayofmonth`Function
```
dayofmonth(dt::TimeType) -> Int64
```
The day of month of a `Date` or `DateTime` as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.dayofweekofmonth`Function
```
dayofweekofmonth(dt::TimeType) -> Int
```
For the day of week of `dt`, return which number it is in `dt`'s month. So if the day of the week of `dt` is Monday, then `1 = First Monday of the month, 2 = Second Monday of the month, etc.` In the range 1:5.
**Examples**
```
julia> Dates.dayofweekofmonth(Date("2000-02-01"))
1
julia> Dates.dayofweekofmonth(Date("2000-02-08"))
2
julia> Dates.dayofweekofmonth(Date("2000-02-15"))
3
```
###
`Dates.daysofweekinmonth`Function
```
daysofweekinmonth(dt::TimeType) -> Int
```
For the day of week of `dt`, return the total number of that day of the week in `dt`'s month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by including `dayofweekofmonth(dt) == daysofweekinmonth(dt)` in the adjuster function.
**Examples**
```
julia> Dates.daysofweekinmonth(Date("2005-01-01"))
5
julia> Dates.daysofweekinmonth(Date("2005-01-04"))
4
```
###
`Dates.monthname`Function
```
monthname(dt::TimeType; locale="english") -> String
monthname(month::Integer, locale="english") -> String
```
Return the full name of the month of the `Date` or `DateTime` or `Integer` in the given `locale`.
**Examples**
```
julia> Dates.monthname(Date("2005-01-04"))
"January"
julia> Dates.monthname(2)
"February"
```
###
`Dates.monthabbr`Function
```
monthabbr(dt::TimeType; locale="english") -> String
monthabbr(month::Integer, locale="english") -> String
```
Return the abbreviated month name of the `Date` or `DateTime` or `Integer` in the given `locale`.
**Examples**
```
julia> Dates.monthabbr(Date("2005-01-04"))
"Jan"
julia> monthabbr(2)
"Feb"
```
###
`Dates.daysinmonth`Function
```
daysinmonth(dt::TimeType) -> Int
```
Return the number of days in the month of `dt`. Value will be 28, 29, 30, or 31.
**Examples**
```
julia> Dates.daysinmonth(Date("2000-01"))
31
julia> Dates.daysinmonth(Date("2001-02"))
28
julia> Dates.daysinmonth(Date("2000-02"))
29
```
###
`Dates.isleapyear`Function
```
isleapyear(dt::TimeType) -> Bool
```
Return `true` if the year of `dt` is a leap year.
**Examples**
```
julia> Dates.isleapyear(Date("2004"))
true
julia> Dates.isleapyear(Date("2005"))
false
```
###
`Dates.dayofyear`Function
```
dayofyear(dt::TimeType) -> Int
```
Return the day of the year for `dt` with January 1st being day 1.
###
`Dates.daysinyear`Function
```
daysinyear(dt::TimeType) -> Int
```
Return 366 if the year of `dt` is a leap year, otherwise return 365.
**Examples**
```
julia> Dates.daysinyear(1999)
365
julia> Dates.daysinyear(2000)
366
```
###
`Dates.quarterofyear`Function
```
quarterofyear(dt::TimeType) -> Int
```
Return the quarter that `dt` resides in. Range of value is 1:4.
###
`Dates.dayofquarter`Function
```
dayofquarter(dt::TimeType) -> Int
```
Return the day of the current quarter of `dt`. Range of value is 1:92.
###
[Adjuster Functions](#Adjuster-Functions-2)
###
`Base.trunc`Method
```
trunc(dt::TimeType, ::Type{Period}) -> TimeType
```
Truncates the value of `dt` according to the provided `Period` type.
**Examples**
```
julia> trunc(Dates.DateTime("1996-01-01T12:30:00"), Dates.Day)
1996-01-01T00:00:00
```
###
`Dates.firstdayofweek`Function
```
firstdayofweek(dt::TimeType) -> TimeType
```
Adjusts `dt` to the Monday of its week.
**Examples**
```
julia> Dates.firstdayofweek(DateTime("1996-01-05T12:30:00"))
1996-01-01T00:00:00
```
###
`Dates.lastdayofweek`Function
```
lastdayofweek(dt::TimeType) -> TimeType
```
Adjusts `dt` to the Sunday of its week.
**Examples**
```
julia> Dates.lastdayofweek(DateTime("1996-01-05T12:30:00"))
1996-01-07T00:00:00
```
###
`Dates.firstdayofmonth`Function
```
firstdayofmonth(dt::TimeType) -> TimeType
```
Adjusts `dt` to the first day of its month.
**Examples**
```
julia> Dates.firstdayofmonth(DateTime("1996-05-20"))
1996-05-01T00:00:00
```
###
`Dates.lastdayofmonth`Function
```
lastdayofmonth(dt::TimeType) -> TimeType
```
Adjusts `dt` to the last day of its month.
**Examples**
```
julia> Dates.lastdayofmonth(DateTime("1996-05-20"))
1996-05-31T00:00:00
```
###
`Dates.firstdayofyear`Function
```
firstdayofyear(dt::TimeType) -> TimeType
```
Adjusts `dt` to the first day of its year.
**Examples**
```
julia> Dates.firstdayofyear(DateTime("1996-05-20"))
1996-01-01T00:00:00
```
###
`Dates.lastdayofyear`Function
```
lastdayofyear(dt::TimeType) -> TimeType
```
Adjusts `dt` to the last day of its year.
**Examples**
```
julia> Dates.lastdayofyear(DateTime("1996-05-20"))
1996-12-31T00:00:00
```
###
`Dates.firstdayofquarter`Function
```
firstdayofquarter(dt::TimeType) -> TimeType
```
Adjusts `dt` to the first day of its quarter.
**Examples**
```
julia> Dates.firstdayofquarter(DateTime("1996-05-20"))
1996-04-01T00:00:00
julia> Dates.firstdayofquarter(DateTime("1996-08-20"))
1996-07-01T00:00:00
```
###
`Dates.lastdayofquarter`Function
```
lastdayofquarter(dt::TimeType) -> TimeType
```
Adjusts `dt` to the last day of its quarter.
**Examples**
```
julia> Dates.lastdayofquarter(DateTime("1996-05-20"))
1996-06-30T00:00:00
julia> Dates.lastdayofquarter(DateTime("1996-08-20"))
1996-09-30T00:00:00
```
###
`Dates.tonext`Method
```
tonext(dt::TimeType, dow::Int; same::Bool=false) -> TimeType
```
Adjusts `dt` to the next day of week corresponding to `dow` with `1 = Monday, 2 = Tuesday, etc`. Setting `same=true` allows the current `dt` to be considered as the next `dow`, allowing for no adjustment to occur.
###
`Dates.toprev`Method
```
toprev(dt::TimeType, dow::Int; same::Bool=false) -> TimeType
```
Adjusts `dt` to the previous day of week corresponding to `dow` with `1 = Monday, 2 = Tuesday, etc`. Setting `same=true` allows the current `dt` to be considered as the previous `dow`, allowing for no adjustment to occur.
###
`Dates.tofirst`Function
```
tofirst(dt::TimeType, dow::Int; of=Month) -> TimeType
```
Adjusts `dt` to the first `dow` of its month. Alternatively, `of=Year` will adjust to the first `dow` of the year.
###
`Dates.tolast`Function
```
tolast(dt::TimeType, dow::Int; of=Month) -> TimeType
```
Adjusts `dt` to the last `dow` of its month. Alternatively, `of=Year` will adjust to the last `dow` of the year.
###
`Dates.tonext`Method
```
tonext(func::Function, dt::TimeType; step=Day(1), limit=10000, same=false) -> TimeType
```
Adjusts `dt` by iterating at most `limit` iterations by `step` increments until `func` returns `true`. `func` must take a single `TimeType` argument and return a [`Bool`](../../base/numbers/index#Core.Bool). `same` allows `dt` to be considered in satisfying `func`.
###
`Dates.toprev`Method
```
toprev(func::Function, dt::TimeType; step=Day(-1), limit=10000, same=false) -> TimeType
```
Adjusts `dt` by iterating at most `limit` iterations by `step` increments until `func` returns `true`. `func` must take a single `TimeType` argument and return a [`Bool`](../../base/numbers/index#Core.Bool). `same` allows `dt` to be considered in satisfying `func`.
###
[Periods](#Periods)
###
`Dates.Period`Method
```
Year(v)
Quarter(v)
Month(v)
Week(v)
Day(v)
Hour(v)
Minute(v)
Second(v)
Millisecond(v)
Microsecond(v)
Nanosecond(v)
```
Construct a `Period` type with the given `v` value. Input must be losslessly convertible to an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.CompoundPeriod`Method
```
CompoundPeriod(periods) -> CompoundPeriod
```
Construct a `CompoundPeriod` from a `Vector` of `Period`s. All `Period`s of the same type will be added together.
**Examples**
```
julia> Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13))
25 hours
julia> Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1))
-1 hour, 1 minute
julia> Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2))
1 month, -2 weeks
julia> Dates.CompoundPeriod(Dates.Minute(50000))
50000 minutes
```
###
`Dates.canonicalize`Function
```
canonicalize(::CompoundPeriod) -> CompoundPeriod
```
Reduces the `CompoundPeriod` into its canonical form by applying the following rules:
* Any `Period` large enough be partially representable by a coarser `Period` will be broken into multiple `Period`s (eg. `Hour(30)` becomes `Day(1) + Hour(6)`)
* `Period`s with opposite signs will be combined when possible (eg. `Hour(1) - Day(1)` becomes `-Hour(23)`)
**Examples**
```
julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13)))
1 day, 1 hour
julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1)))
-59 minutes
julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2)))
1 month, -2 weeks
julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Minute(50000)))
4 weeks, 6 days, 17 hours, 20 minutes
```
###
`Dates.value`Function
```
Dates.value(x::Period) -> Int64
```
For a given period, return the value associated with that period. For example, `value(Millisecond(10))` returns 10 as an integer.
###
`Dates.default`Function
```
default(p::Period) -> Period
```
Returns a sensible "default" value for the input Period by returning `T(1)` for Year, Month, and Day, and `T(0)` for Hour, Minute, Second, and Millisecond.
###
`Dates.periods`Function
```
Dates.periods(::CompoundPeriod) -> Vector{Period}
```
Return the `Vector` of `Period`s that comprise the given `CompoundPeriod`.
This function requires Julia 1.7 or later.
###
[Rounding Functions](#Rounding-Functions)
`Date` and `DateTime` values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with `floor`, `ceil`, or `round`.
###
`Base.floor`Method
```
floor(dt::TimeType, p::Period) -> TimeType
```
Return the nearest `Date` or `DateTime` less than or equal to `dt` at resolution `p`.
For convenience, `p` may be a type instead of a value: `floor(dt, Dates.Hour)` is a shortcut for `floor(dt, Dates.Hour(1))`.
```
julia> floor(Date(1985, 8, 16), Dates.Month)
1985-08-01
julia> floor(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
2013-02-13T00:30:00
julia> floor(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
2016-08-06T00:00:00
```
###
`Base.ceil`Method
```
ceil(dt::TimeType, p::Period) -> TimeType
```
Return the nearest `Date` or `DateTime` greater than or equal to `dt` at resolution `p`.
For convenience, `p` may be a type instead of a value: `ceil(dt, Dates.Hour)` is a shortcut for `ceil(dt, Dates.Hour(1))`.
```
julia> ceil(Date(1985, 8, 16), Dates.Month)
1985-09-01
julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
2013-02-13T00:45:00
julia> ceil(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
2016-08-07T00:00:00
```
###
`Base.round`Method
```
round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType
```
Return the `Date` or `DateTime` nearest to `dt` at resolution `p`. By default (`RoundNearestTiesUp`), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up.
For convenience, `p` may be a type instead of a value: `round(dt, Dates.Hour)` is a shortcut for `round(dt, Dates.Hour(1))`.
```
julia> round(Date(1985, 8, 16), Dates.Month)
1985-08-01
julia> round(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
2013-02-13T00:30:00
julia> round(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
2016-08-07T00:00:00
```
Valid rounding modes for `round(::TimeType, ::Period, ::RoundingMode)` are `RoundNearestTiesUp` (default), `RoundDown` (`floor`), and `RoundUp` (`ceil`).
Most `Period` values can also be rounded to a specified resolution:
###
`Base.floor`Method
```
floor(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T
```
Round `x` down to the nearest multiple of `precision`. If `x` and `precision` are different subtypes of `Period`, the return value will have the same type as `precision`.
For convenience, `precision` may be a type instead of a value: `floor(x, Dates.Hour)` is a shortcut for `floor(x, Dates.Hour(1))`.
```
julia> floor(Dates.Day(16), Dates.Week)
2 weeks
julia> floor(Dates.Minute(44), Dates.Minute(15))
30 minutes
julia> floor(Dates.Hour(36), Dates.Day)
1 day
```
Rounding to a `precision` of `Month`s or `Year`s is not supported, as these `Period`s are of inconsistent length.
###
`Base.ceil`Method
```
ceil(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T
```
Round `x` up to the nearest multiple of `precision`. If `x` and `precision` are different subtypes of `Period`, the return value will have the same type as `precision`.
For convenience, `precision` may be a type instead of a value: `ceil(x, Dates.Hour)` is a shortcut for `ceil(x, Dates.Hour(1))`.
```
julia> ceil(Dates.Day(16), Dates.Week)
3 weeks
julia> ceil(Dates.Minute(44), Dates.Minute(15))
45 minutes
julia> ceil(Dates.Hour(36), Dates.Day)
2 days
```
Rounding to a `precision` of `Month`s or `Year`s is not supported, as these `Period`s are of inconsistent length.
###
`Base.round`Method
```
round(x::Period, precision::T, [r::RoundingMode]) where T <: Union{TimePeriod, Week, Day} -> T
```
Round `x` to the nearest multiple of `precision`. If `x` and `precision` are different subtypes of `Period`, the return value will have the same type as `precision`. By default (`RoundNearestTiesUp`), ties (e.g., rounding 90 minutes to the nearest hour) will be rounded up.
For convenience, `precision` may be a type instead of a value: `round(x, Dates.Hour)` is a shortcut for `round(x, Dates.Hour(1))`.
```
julia> round(Dates.Day(16), Dates.Week)
2 weeks
julia> round(Dates.Minute(44), Dates.Minute(15))
45 minutes
julia> round(Dates.Hour(36), Dates.Day)
2 days
```
Valid rounding modes for `round(::Period, ::T, ::RoundingMode)` are `RoundNearestTiesUp` (default), `RoundDown` (`floor`), and `RoundUp` (`ceil`).
Rounding to a `precision` of `Month`s or `Year`s is not supported, as these `Period`s are of inconsistent length.
The following functions are not exported:
###
`Dates.floorceil`Function
```
floorceil(dt::TimeType, p::Period) -> (TimeType, TimeType)
```
Simultaneously return the `floor` and `ceil` of a `Date` or `DateTime` at resolution `p`. More efficient than calling both `floor` and `ceil` individually.
```
floorceil(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> (T, T)
```
Simultaneously return the `floor` and `ceil` of `Period` at resolution `p`. More efficient than calling both `floor` and `ceil` individually.
###
`Dates.epochdays2date`Function
```
epochdays2date(days) -> Date
```
Take the number of days since the rounding epoch (`0000-01-01T00:00:00`) and return the corresponding `Date`.
###
`Dates.epochms2datetime`Function
```
epochms2datetime(milliseconds) -> DateTime
```
Take the number of milliseconds since the rounding epoch (`0000-01-01T00:00:00`) and return the corresponding `DateTime`.
###
`Dates.date2epochdays`Function
```
date2epochdays(dt::Date) -> Int64
```
Take the given `Date` and return the number of days since the rounding epoch (`0000-01-01T00:00:00`) as an [`Int64`](../../base/numbers/index#Core.Int64).
###
`Dates.datetime2epochms`Function
```
datetime2epochms(dt::DateTime) -> Int64
```
Take the given `DateTime` and return the number of milliseconds since the rounding epoch (`0000-01-01T00:00:00`) as an [`Int64`](../../base/numbers/index#Core.Int64).
###
[Conversion Functions](#Conversion-Functions)
###
`Dates.today`Function
```
today() -> Date
```
Return the date portion of `now()`.
###
`Dates.unix2datetime`Function
```
unix2datetime(x) -> DateTime
```
Take the number of seconds since unix epoch `1970-01-01T00:00:00` and convert to the corresponding `DateTime`.
###
`Dates.datetime2unix`Function
```
datetime2unix(dt::DateTime) -> Float64
```
Take the given `DateTime` and return the number of seconds since the unix epoch `1970-01-01T00:00:00` as a [`Float64`](../../base/numbers/index#Core.Float64).
###
`Dates.julian2datetime`Function
```
julian2datetime(julian_days) -> DateTime
```
Take the number of Julian calendar days since epoch `-4713-11-24T12:00:00` and return the corresponding `DateTime`.
###
`Dates.datetime2julian`Function
```
datetime2julian(dt::DateTime) -> Float64
```
Take the given `DateTime` and return the number of Julian calendar days since the julian epoch `-4713-11-24T12:00:00` as a [`Float64`](../../base/numbers/index#Core.Float64).
###
`Dates.rata2datetime`Function
```
rata2datetime(days) -> DateTime
```
Take the number of Rata Die days since epoch `0000-12-31T00:00:00` and return the corresponding `DateTime`.
###
`Dates.datetime2rata`Function
```
datetime2rata(dt::TimeType) -> Int64
```
Return the number of Rata Die days since epoch from the given `Date` or `DateTime`.
###
[Constants](#Constants)
Days of the Week:
| Variable | Abbr. | Value (Int) |
| --- | --- | --- |
| `Monday` | `Mon` | 1 |
| `Tuesday` | `Tue` | 2 |
| `Wednesday` | `Wed` | 3 |
| `Thursday` | `Thu` | 4 |
| `Friday` | `Fri` | 5 |
| `Saturday` | `Sat` | 6 |
| `Sunday` | `Sun` | 7 |
Months of the Year:
| Variable | Abbr. | Value (Int) |
| --- | --- | --- |
| `January` | `Jan` | 1 |
| `February` | `Feb` | 2 |
| `March` | `Mar` | 3 |
| `April` | `Apr` | 4 |
| `May` | `May` | 5 |
| `June` | `Jun` | 6 |
| `July` | `Jul` | 7 |
| `August` | `Aug` | 8 |
| `September` | `Sep` | 9 |
| `October` | `Oct` | 10 |
| `November` | `Nov` | 11 |
| `December` | `Dec` | 12 |
####
[Common Date Formatters](#Common-Date-Formatters)
###
`Dates.ISODateTimeFormat`Constant
```
Dates.ISODateTimeFormat
```
Describes the ISO8601 formatting for a date and time. This is the default value for `Dates.format` of a `DateTime`.
**Example**
```
julia> Dates.format(DateTime(2018, 8, 8, 12, 0, 43, 1), ISODateTimeFormat)
"2018-08-08T12:00:43.001"
```
###
`Dates.ISODateFormat`Constant
```
Dates.ISODateFormat
```
Describes the ISO8601 formatting for a date. This is the default value for `Dates.format` of a `Date`.
**Example**
```
julia> Dates.format(Date(2018, 8, 8), ISODateFormat)
"2018-08-08"
```
###
`Dates.ISOTimeFormat`Constant
```
Dates.ISOTimeFormat
```
Describes the ISO8601 formatting for a time. This is the default value for `Dates.format` of a `Time`.
**Example**
```
julia> Dates.format(Time(12, 0, 43, 1), ISOTimeFormat)
"12:00:43.001"
```
###
`Dates.RFC1123Format`Constant
```
Dates.RFC1123Format
```
Describes the RFC1123 formatting for a date and time.
**Example**
```
julia> Dates.format(DateTime(2018, 8, 8, 12, 0, 43, 1), RFC1123Format)
"Wed, 08 Aug 2018 12:00:43"
```
* [1](#citeref-1)The notion of the UT second is actually quite fundamental. There are basically two different notions of time generally accepted, one based on the physical rotation of the earth (one full rotation = 1 day), the other based on the SI second (a fixed, constant value). These are radically different! Think about it, a "UT second", as defined relative to the rotation of the earth, may have a different absolute length depending on the day! Anyway, the fact that [`Date`](#Dates.Date) and [`DateTime`](#Dates.DateTime) are based on UT seconds is a simplifying, yet honest assumption so that things like leap seconds and all their complexity can be avoided. This basis of time is formally called [UT](https://en.wikipedia.org/wiki/Universal_Time) or UT1. Basing types on the UT second basically means that every minute has 60 seconds and every day has 24 hours and leads to more natural calculations when working with calendar dates.
| programming_docs |
julia Sockets Sockets
=======
###
`Sockets.Sockets`Module
Support for sockets. Provides [`IPAddr`](#Sockets.IPAddr) and subtypes, [`TCPSocket`](#Sockets.TCPSocket), and [`UDPSocket`](#Sockets.UDPSocket).
###
`Sockets.connect`Method
```
connect([host], port::Integer) -> TCPSocket
```
Connect to the host `host` on port `port`.
###
`Sockets.connect`Method
```
connect(path::AbstractString) -> PipeEndpoint
```
Connect to the named pipe / UNIX domain socket at `path`.
Path length on Unix is limited to somewhere between 92 and 108 bytes (cf. `man unix`).
###
`Sockets.listen`Method
```
listen([addr, ]port::Integer; backlog::Integer=BACKLOG_DEFAULT) -> TCPServer
```
Listen on port on the address specified by `addr`. By default this listens on `localhost` only. To listen on all interfaces pass `IPv4(0)` or `IPv6(0)` as appropriate. `backlog` determines how many connections can be pending (not having called [`accept`](#Sockets.accept)) before the server will begin to reject them. The default value of `backlog` is 511.
###
`Sockets.listen`Method
```
listen(path::AbstractString) -> PipeServer
```
Create and listen on a named pipe / UNIX domain socket.
Path length on Unix is limited to somewhere between 92 and 108 bytes (cf. `man unix`).
###
`Sockets.getaddrinfo`Function
```
getaddrinfo(host::AbstractString, IPAddr=IPv4) -> IPAddr
```
Gets the first IP address of the `host` of the specified `IPAddr` type. Uses the operating system's underlying getaddrinfo implementation, which may do a DNS lookup.
###
`Sockets.getipaddr`Function
```
getipaddr() -> IPAddr
```
Get an IP address of the local machine, preferring IPv4 over IPv6. Throws if no addresses are available.
```
getipaddr(addr_type::Type{T}) where T<:IPAddr -> T
```
Get an IP address of the local machine of the specified type. Throws if no addresses of the specified type are available.
This function is a backwards-compatibility wrapper around [`getipaddrs`](#Sockets.getipaddrs). New applications should use [`getipaddrs`](#Sockets.getipaddrs) instead.
**Examples**
```
julia> getipaddr()
ip"192.168.1.28"
julia> getipaddr(IPv6)
ip"fe80::9731:35af:e1c5:6e49"
```
See also [`getipaddrs`](#Sockets.getipaddrs).
###
`Sockets.getipaddrs`Function
```
getipaddrs(addr_type::Type{T}=IPAddr; loopback::Bool=false) where T<:IPAddr -> Vector{T}
```
Get the IP addresses of the local machine.
Setting the optional `addr_type` parameter to `IPv4` or `IPv6` causes only addresses of that type to be returned.
The `loopback` keyword argument dictates whether loopback addresses (e.g. `ip"127.0.0.1"`, `ip"::1"`) are included.
This function is available as of Julia 1.2.
**Examples**
```
julia> getipaddrs()
5-element Array{IPAddr,1}:
ip"198.51.100.17"
ip"203.0.113.2"
ip"2001:db8:8:4:445e:5fff:fe5d:5500"
ip"2001:db8:8:4:c164:402e:7e3c:3668"
ip"fe80::445e:5fff:fe5d:5500"
julia> getipaddrs(IPv6)
3-element Array{IPv6,1}:
ip"2001:db8:8:4:445e:5fff:fe5d:5500"
ip"2001:db8:8:4:c164:402e:7e3c:3668"
ip"fe80::445e:5fff:fe5d:5500"
```
See also [`islinklocaladdr`](#Sockets.islinklocaladdr).
###
`Sockets.islinklocaladdr`Function
```
islinklocaladdr(addr::IPAddr)
```
Tests if an IP address is a link-local address. Link-local addresses are not guaranteed to be unique beyond their network segment, therefore routers do not forward them. Link-local addresses are from the address blocks `169.254.0.0/16` or `fe80::/10`.
**Example**
```
filter(!islinklocaladdr, getipaddrs())
```
###
`Sockets.getalladdrinfo`Function
```
getalladdrinfo(host::AbstractString) -> Vector{IPAddr}
```
Gets all of the IP addresses of the `host`. Uses the operating system's underlying `getaddrinfo` implementation, which may do a DNS lookup.
**Example**
```
julia> getalladdrinfo("google.com")
2-element Array{IPAddr,1}:
ip"172.217.6.174"
ip"2607:f8b0:4000:804::200e"
```
###
`Sockets.DNSError`Type
```
DNSError
```
The type of exception thrown when an error occurs in DNS lookup. The `host` field indicates the host URL string. The `code` field indicates the error code based on libuv.
###
`Sockets.getnameinfo`Function
```
getnameinfo(host::IPAddr) -> String
```
Performs a reverse-lookup for IP address to return a hostname and service using the operating system's underlying `getnameinfo` implementation.
**Examples**
```
julia> getnameinfo(Sockets.IPv4("8.8.8.8"))
"google-public-dns-a.google.com"
```
###
`Sockets.getsockname`Function
```
getsockname(sock::Union{TCPServer, TCPSocket}) -> (IPAddr, UInt16)
```
Get the IP address and port that the given socket is bound to.
###
`Sockets.getpeername`Function
```
getpeername(sock::TCPSocket) -> (IPAddr, UInt16)
```
Get the IP address and port of the remote endpoint that the given socket is connected to. Valid only for connected TCP sockets.
###
`Sockets.IPAddr`Type
```
IPAddr
```
Abstract supertype for IP addresses. [`IPv4`](#Sockets.IPv4) and [`IPv6`](#Sockets.IPv6) are subtypes of this.
###
`Sockets.IPv4`Type
```
IPv4(host::Integer) -> IPv4
```
Returns an IPv4 object from ip address `host` formatted as an [`Integer`](../../base/numbers/index#Core.Integer).
**Examples**
```
julia> IPv4(3223256218)
ip"192.30.252.154"
```
###
`Sockets.IPv6`Type
```
IPv6(host::Integer) -> IPv6
```
Returns an IPv6 object from ip address `host` formatted as an [`Integer`](../../base/numbers/index#Core.Integer).
**Examples**
```
julia> IPv6(3223256218)
ip"::c01e:fc9a"
```
###
`Sockets.@ip_str`Macro
```
@ip_str str -> IPAddr
```
Parse `str` as an IP address.
**Examples**
```
julia> ip"127.0.0.1"
ip"127.0.0.1"
julia> @ip_str "2001:db8:0:0:0:0:2:1"
ip"2001:db8::2:1"
```
###
`Sockets.TCPSocket`Type
```
TCPSocket(; delay=true)
```
Open a TCP socket using libuv. If `delay` is true, libuv delays creation of the socket's file descriptor till the first [`bind`](#Base.bind) call. `TCPSocket` has various fields to denote the state of the socket as well as its send/receive buffers.
###
`Sockets.UDPSocket`Type
```
UDPSocket()
```
Open a UDP socket using libuv. `UDPSocket` has various fields to denote the state of the socket.
###
`Sockets.accept`Function
```
accept(server[, client])
```
Accepts a connection on the given server and returns a connection to the client. An uninitialized client stream may be provided, in which case it will be used instead of creating a new stream.
###
`Sockets.listenany`Function
```
listenany([host::IPAddr,] port_hint) -> (UInt16, TCPServer)
```
Create a `TCPServer` on any port, using hint as a starting point. Returns a tuple of the actual port that the server was created on and the server itself.
###
`Base.bind`Function
```
bind(chnl::Channel, task::Task)
```
Associate the lifetime of `chnl` with a task. `Channel` `chnl` is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on `chnl`.
The `chnl` object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed `Channel` objects.
When a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.
**Examples**
```
julia> c = Channel(0);
julia> task = @async foreach(i->put!(c, i), 1:4);
julia> bind(c,task);
julia> for i in c
@show i
end;
i = 1
i = 2
i = 3
i = 4
julia> isopen(c)
false
```
```
julia> c = Channel(0);
julia> task = @async (put!(c, 1); error("foo"));
julia> bind(c, task);
julia> take!(c)
1
julia> put!(c, 1);
ERROR: TaskFailedException
Stacktrace:
[...]
nested task error: foo
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L201-L252)
```
bind(socket::Union{TCPServer, UDPSocket, TCPSocket}, host::IPAddr, port::Integer; ipv6only=false, reuseaddr=false, kws...)
```
Bind `socket` to the given `host:port`. Note that `0.0.0.0` will listen on all devices.
* The `ipv6only` parameter disables dual stack mode. If `ipv6only=true`, only an IPv6 stack is created.
* If `reuseaddr=true`, multiple threads or processes can bind to the same address without error if they all set `reuseaddr=true`, but only the last to bind will receive any traffic.
###
`Sockets.send`Function
```
send(socket::UDPSocket, host::IPAddr, port::Integer, msg)
```
Send `msg` over `socket` to `host:port`.
###
`Sockets.recv`Function
```
recv(socket::UDPSocket)
```
Read a UDP packet from the specified socket, and return the bytes received. This call blocks.
###
`Sockets.recvfrom`Function
```
recvfrom(socket::UDPSocket) -> (host_port, data)
```
Read a UDP packet from the specified socket, returning a tuple of `(host_port, data)`, where `host_port` will be an InetAddr{IPv4} or InetAddr{IPv6}, as appropriate.
Prior to Julia version 1.3, the first returned value was an address (`IPAddr`). In version 1.3 it was changed to an `InetAddr`.
###
`Sockets.setopt`Function
```
setopt(sock::UDPSocket; multicast_loop=nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing)
```
Set UDP socket options.
* `multicast_loop`: loopback for multicast packets (default: `true`).
* `multicast_ttl`: TTL for multicast packets (default: `nothing`).
* `enable_broadcast`: flag must be set to `true` if socket will be used for broadcast messages, or else the UDP system will return an access error (default: `false`).
* `ttl`: Time-to-live of packets sent on the socket (default: `nothing`).
###
`Sockets.nagle`Function
```
nagle(socket::Union{TCPServer, TCPSocket}, enable::Bool)
```
Enables or disables Nagle's algorithm on a given TCP server or socket.
This function requires Julia 1.3 or later.
###
`Sockets.quickack`Function
```
quickack(socket::Union{TCPServer, TCPSocket}, enable::Bool)
```
On Linux systems, the TCP\_QUICKACK is disabled or enabled on `socket`.
julia Unit Testing Unit Testing
============
[Testing Base Julia](#Testing-Base-Julia)
------------------------------------------
Julia is under rapid development and has an extensive test suite to verify functionality across multiple platforms. If you build Julia from source, you can run this test suite with `make test`. In a binary install, you can run the test suite using `Base.runtests()`.
###
`Base.runtests`Function
```
Base.runtests(tests=["all"]; ncores=ceil(Int, Sys.CPU_THREADS / 2),
exit_on_error=false, revise=false, [seed])
```
Run the Julia unit tests listed in `tests`, which can be either a string or an array of strings, using `ncores` processors. If `exit_on_error` is `false`, when one test fails, all remaining tests in other files will still be run; they are otherwise discarded, when `exit_on_error == true`. If `revise` is `true`, the `Revise` package is used to load any modifications to `Base` or to the standard libraries before running the tests. If a seed is provided via the keyword argument, it is used to seed the global RNG in the context where the tests are run; otherwise the seed is chosen randomly.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/util.jl#L574-L586)
[Basic Unit Tests](#Basic-Unit-Tests)
--------------------------------------
The `Test` module provides simple *unit testing* functionality. Unit testing is a way to see if your code is correct by checking that the results are what you expect. It can be helpful to ensure your code still works after you make changes, and can be used when developing as a way of specifying the behaviors your code should have when complete. You may also want to look at the documentation for [adding tests to your Julia Package](https://pkgdocs.julialang.org/dev/creating-packages/#Adding-tests-to-the-package).
Simple unit testing can be performed with the `@test` and `@test_throws` macros:
###
`Test.@test`Macro
```
@test ex
@test f(args...) key=val ...
@test ex broken=true
@test ex skip=true
```
Test that the expression `ex` evaluates to `true`. If executed inside a `@testset`, return a `Pass` `Result` if it does, a `Fail` `Result` if it is `false`, and an `Error` `Result` if it could not be evaluated. If executed outside a `@testset`, throw an exception instead of returning `Fail` or `Error`.
**Examples**
```
julia> @test true
Test Passed
julia> @test [1, 2] + [2, 1] == [3, 3]
Test Passed
```
The `@test f(args...) key=val...` form is equivalent to writing `@test f(args..., key=val...)` which can be useful when the expression is a call using infix syntax such as approximate comparisons:
```
julia> @test π ≈ 3.14 atol=0.01
Test Passed
```
This is equivalent to the uglier test `@test ≈(π, 3.14, atol=0.01)`. It is an error to supply more than one expression unless the first is a call expression and the rest are assignments (`k=v`).
You can use any key for the `key=val` arguments, except for `broken` and `skip`, which have special meanings in the context of `@test`:
* `broken=cond` indicates a test that should pass but currently consistently fails when `cond==true`. Tests that the expression `ex` evaluates to `false` or causes an exception. Returns a `Broken` `Result` if it does, or an `Error` `Result` if the expression evaluates to `true`. Regular `@test ex` is evaluated when `cond==false`.
* `skip=cond` marks a test that should not be executed but should be included in test summary reporting as `Broken`, when `cond==true`. This can be useful for tests that intermittently fail, or tests of not-yet-implemented functionality. Regular `@test ex` is evaluated when `cond==false`.
**Examples**
```
julia> @test 2 + 2 ≈ 6 atol=1 broken=true
Test Broken
Expression: ≈(2 + 2, 6, atol = 1)
julia> @test 2 + 2 ≈ 5 atol=1 broken=false
Test Passed
julia> @test 2 + 2 == 5 skip=true
Test Broken
Skipped: 2 + 2 == 5
julia> @test 2 + 2 == 4 skip=false
Test Passed
```
The `broken` and `skip` keyword arguments require at least Julia 1.7.
###
`Test.@test_throws`Macro
```
@test_throws exception expr
```
Tests that the expression `expr` throws `exception`. The exception may specify either a type, a string, regular expression, or list of strings occurring in the displayed error message, a matching function, or a value (which will be tested for equality by comparing fields). Note that `@test_throws` does not support a trailing keyword form.
The ability to specify anything other than a type or a value as `exception` requires Julia v1.8 or later.
**Examples**
```
julia> @test_throws BoundsError [1, 2, 3][4]
Test Passed
Thrown: BoundsError
julia> @test_throws DimensionMismatch [1, 2, 3] + [1, 2]
Test Passed
Thrown: DimensionMismatch
julia> @test_throws "Try sqrt(Complex" sqrt(-1)
Test Passed
Message: "DomainError with -1.0:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x))."
```
In the final example, instead of matching a single string it could alternatively have been performed with:
* `["Try", "Complex"]` (a list of strings)
* `r"Try sqrt\([Cc]omplex"` (a regular expression)
* `str -> occursin("complex", str)` (a matching function)
For example, suppose we want to check our new function `foo(x)` works as expected:
```
julia> using Test
julia> foo(x) = length(x)^2
foo (generic function with 1 method)
```
If the condition is true, a `Pass` is returned:
```
julia> @test foo("bar") == 9
Test Passed
julia> @test foo("fizz") >= 10
Test Passed
```
If the condition is false, then a `Fail` is returned and an exception is thrown:
```
julia> @test foo("f") == 20
Test Failed at none:1
Expression: foo("f") == 20
Evaluated: 1 == 20
ERROR: There was an error during testing
```
If the condition could not be evaluated because an exception was thrown, which occurs in this case because `length` is not defined for symbols, an `Error` object is returned and an exception is thrown:
```
julia> @test foo(:cat) == 1
Error During Test
Test threw an exception of type MethodError
Expression: foo(:cat) == 1
MethodError: no method matching length(::Symbol)
Closest candidates are:
length(::SimpleVector) at essentials.jl:256
length(::Base.MethodList) at reflection.jl:521
length(::MethodTable) at reflection.jl:597
...
Stacktrace:
[...]
ERROR: There was an error during testing
```
If we expect that evaluating an expression *should* throw an exception, then we can use `@test_throws` to check that this occurs:
```
julia> @test_throws MethodError foo(:cat)
Test Passed
Thrown: MethodError
```
[Working with Test Sets](#Working-with-Test-Sets)
--------------------------------------------------
Typically a large number of tests are used to make sure functions work correctly over a range of inputs. In the event a test fails, the default behavior is to throw an exception immediately. However, it is normally preferable to run the rest of the tests first to get a better picture of how many errors there are in the code being tested.
The `@testset` will create a local scope of its own when running the tests in it.
The `@testset` macro can be used to group tests into *sets*. All the tests in a test set will be run, and at the end of the test set a summary will be printed. If any of the tests failed, or could not be evaluated due to an error, the test set will then throw a `TestSetException`.
###
`Test.@testset`Macro
```
@testset [CustomTestSet] [option=val ...] ["description"] begin ... end
@testset [CustomTestSet] [option=val ...] ["description $v"] for v in (...) ... end
@testset [CustomTestSet] [option=val ...] ["description $v, $w"] for v in (...), w in (...) ... end
@testset [CustomTestSet] [option=val ...] ["description $v, $w"] foo()
```
Starts a new test set, or multiple test sets if a `for` loop is provided.
If no custom testset type is given it defaults to creating a `DefaultTestSet`. `DefaultTestSet` records all the results and, if there are any `Fail`s or `Error`s, throws an exception at the end of the top-level (non-nested) test set, along with a summary of the test results.
Any custom testset type (subtype of `AbstractTestSet`) can be given and it will also be used for any nested `@testset` invocations. The given options are only applied to the test set where they are given. The default test set type accepts two boolean options:
* `verbose`: if `true`, the result summary of the nested testsets is shown even
when they all pass (the default is `false`).
* `showtiming`: if `true`, the duration of each displayed testset is shown
(the default is `true`).
`@testset foo()` requires at least Julia 1.8.
The description string accepts interpolation from the loop indices. If no description is provided, one is constructed based on the variables. If a function call is provided, its name will be used. Explicit description strings override this behavior.
By default the `@testset` macro will return the testset object itself, though this behavior can be customized in other testset types. If a `for` loop is used then the macro collects and returns a list of the return values of the `finish` method, which by default will return a list of the testset objects used in each iteration.
Before the execution of the body of a `@testset`, there is an implicit call to `Random.seed!(seed)` where `seed` is the current seed of the global RNG. Moreover, after the execution of the body, the state of the global RNG is restored to what it was before the `@testset`. This is meant to ease reproducibility in case of failure, and to allow seamless re-arrangements of `@testset`s regardless of their side-effect on the global RNG state.
**Examples**
```
julia> @testset "trigonometric identities" begin
θ = 2/3*π
@test sin(-θ) ≈ -sin(θ)
@test cos(-θ) ≈ cos(θ)
@test sin(2θ) ≈ 2*sin(θ)*cos(θ)
@test cos(2θ) ≈ cos(θ)^2 - sin(θ)^2
end;
Test Summary: | Pass Total Time
trigonometric identities | 4 4 0.2s
```
###
`Test.TestSetException`Type
```
TestSetException
```
Thrown when a test set finishes and not all tests passed.
We can put our tests for the `foo(x)` function in a test set:
```
julia> @testset "Foo Tests" begin
@test foo("a") == 1
@test foo("ab") == 4
@test foo("abc") == 9
end;
Test Summary: | Pass Total Time
Foo Tests | 3 3 0.0s
```
Test sets can also be nested:
```
julia> @testset "Foo Tests" begin
@testset "Animals" begin
@test foo("cat") == 9
@test foo("dog") == foo("cat")
end
@testset "Arrays $i" for i in 1:3
@test foo(zeros(i)) == i^2
@test foo(fill(1.0, i)) == i^2
end
end;
Test Summary: | Pass Total Time
Foo Tests | 8 8 0.0s
```
As well as call functions:
```
julia> f(x) = @test isone(x)
f (generic function with 1 method)
julia> @testset f(1);
Test Summary: | Pass Total Time
f | 1 1 0.0s
```
This can be used to allow for factorization of test sets, making it easier to run individual test sets by running the associated functions instead. Note that in the case of functions, the test set will be given the name of the called function. In the event that a nested test set has no failures, as happened here, it will be hidden in the summary, unless the `verbose=true` option is passed:
```
julia> @testset verbose = true "Foo Tests" begin
@testset "Animals" begin
@test foo("cat") == 9
@test foo("dog") == foo("cat")
end
@testset "Arrays $i" for i in 1:3
@test foo(zeros(i)) == i^2
@test foo(fill(1.0, i)) == i^2
end
end;
Test Summary: | Pass Total Time
Foo Tests | 8 8 0.0s
Animals | 2 2 0.0s
Arrays 1 | 2 2 0.0s
Arrays 2 | 2 2 0.0s
Arrays 3 | 2 2 0.0s
```
If we do have a test failure, only the details for the failed test sets will be shown:
```
julia> @testset "Foo Tests" begin
@testset "Animals" begin
@testset "Felines" begin
@test foo("cat") == 9
end
@testset "Canines" begin
@test foo("dog") == 9
end
end
@testset "Arrays" begin
@test foo(zeros(2)) == 4
@test foo(fill(1.0, 4)) == 15
end
end
Arrays: Test Failed
Expression: foo(fill(1.0, 4)) == 15
Evaluated: 16 == 15
[...]
Test Summary: | Pass Fail Total Time
Foo Tests | 3 1 4 0.0s
Animals | 2 2 0.0s
Arrays | 1 1 2 0.0s
ERROR: Some tests did not pass: 3 passed, 1 failed, 0 errored, 0 broken.
```
[Testing Log Statements](#Testing-Log-Statements)
--------------------------------------------------
One can use the [`@test_logs`](#Test.@test_logs) macro to test log statements, or use a [`TestLogger`](#Test.TestLogger).
###
`Test.@test_logs`Macro
```
@test_logs [log_patterns...] [keywords] expression
```
Collect a list of log records generated by `expression` using `collect_test_logs`, check that they match the sequence `log_patterns`, and return the value of `expression`. The `keywords` provide some simple filtering of log records: the `min_level` keyword controls the minimum log level which will be collected for the test, the `match_mode` keyword defines how matching will be performed (the default `:all` checks that all logs and patterns match pairwise; use `:any` to check that the pattern matches at least once somewhere in the sequence.)
The most useful log pattern is a simple tuple of the form `(level,message)`. A different number of tuple elements may be used to match other log metadata, corresponding to the arguments to passed to `AbstractLogger` via the `handle_message` function: `(level,message,module,group,id,file,line)`. Elements which are present will be matched pairwise with the log record fields using `==` by default, with the special cases that `Symbol`s may be used for the standard log levels, and `Regex`s in the pattern will match string or Symbol fields using `occursin`.
**Examples**
Consider a function which logs a warning, and several debug messages:
```
function foo(n)
@info "Doing foo with n=$n"
for i=1:n
@debug "Iteration $i"
end
42
end
```
We can test the info message using
```
@test_logs (:info,"Doing foo with n=2") foo(2)
```
If we also wanted to test the debug messages, these need to be enabled with the `min_level` keyword:
```
using Logging
@test_logs (:info,"Doing foo with n=2") (:debug,"Iteration 1") (:debug,"Iteration 2") min_level=Logging.Debug foo(2)
```
If you want to test that some particular messages are generated while ignoring the rest, you can set the keyword `match_mode=:any`:
```
using Logging
@test_logs (:info,) (:debug,"Iteration 42") min_level=Logging.Debug match_mode=:any foo(100)
```
The macro may be chained with `@test` to also test the returned value:
```
@test (@test_logs (:info,"Doing foo with n=2") foo(2)) == 42
```
If you want to test for the absence of warnings, you can omit specifying log patterns and set the `min_level` accordingly:
```
# test that the expression logs no messages when the logger level is warn:
@test_logs min_level=Logging.Warn @info("Some information") # passes
@test_logs min_level=Logging.Warn @warn("Some information") # fails
```
If you want to test the absence of warnings (or error messages) in [`stderr`](../../base/io-network/index#Base.stderr) which are not generated by `@warn`, see [`@test_nowarn`](#Test.@test_nowarn).
###
`Test.TestLogger`Type
```
TestLogger(; min_level=Info, catch_exceptions=false)
```
Create a `TestLogger` which captures logged messages in its `logs::Vector{LogRecord}` field.
Set `min_level` to control the `LogLevel`, `catch_exceptions` for whether or not exceptions thrown as part of log event generation should be caught, and `respect_maxlog` for whether or not to follow the convention of logging messages with `maxlog=n` for some integer `n` at most `n` times.
See also: [`LogRecord`](#Test.LogRecord).
**Example**
```
julia> using Test, Logging
julia> f() = @info "Hi" number=5;
julia> test_logger = TestLogger();
julia> with_logger(test_logger) do
f()
@info "Bye!"
end
julia> @test test_logger.logs[1].message == "Hi"
Test Passed
julia> @test test_logger.logs[1].kwargs[:number] == 5
Test Passed
julia> @test test_logger.logs[2].message == "Bye!"
Test Passed
```
###
`Test.LogRecord`Type
```
LogRecord
```
Stores the results of a single log event. Fields:
* `level`: the [`LogLevel`](../logging/index#Logging.LogLevel) of the log message
* `message`: the textual content of the log message
* `_module`: the module of the log event
* `group`: the logging group (by default, the name of the file containing the log event)
* `id`: the ID of the log event
* `file`: the file containing the log event
* `line`: the line within the file of the log event
* `kwargs`: any keyword arguments passed to the log event
[Other Test Macros](#Other-Test-Macros)
----------------------------------------
As calculations on floating-point values can be imprecise, you can perform approximate equality checks using either `@test a ≈ b` (where `≈`, typed via tab completion of `\approx`, is the [`isapprox`](../../base/math/index#Base.isapprox) function) or use [`isapprox`](../../base/math/index#Base.isapprox) directly.
```
julia> @test 1 ≈ 0.999999999
Test Passed
julia> @test 1 ≈ 0.999999
Test Failed at none:1
Expression: 1 ≈ 0.999999
Evaluated: 1 ≈ 0.999999
ERROR: There was an error during testing
```
You can specify relative and absolute tolerances by setting the `rtol` and `atol` keyword arguments of `isapprox`, respectively, after the `≈` comparison:
```
julia> @test 1 ≈ 0.999999 rtol=1e-5
Test Passed
```
Note that this is not a specific feature of the `≈` but rather a general feature of the `@test` macro: `@test a <op> b key=val` is transformed by the macro into `@test op(a, b, key=val)`. It is, however, particularly useful for `≈` tests.
###
`Test.@inferred`Macro
```
@inferred [AllowedType] f(x)
```
Tests that the call expression `f(x)` returns a value of the same type inferred by the compiler. It is useful to check for type stability.
`f(x)` can be any call expression. Returns the result of `f(x)` if the types match, and an `Error` `Result` if it finds different types.
Optionally, `AllowedType` relaxes the test, by making it pass when either the type of `f(x)` matches the inferred type modulo `AllowedType`, or when the return type is a subtype of `AllowedType`. This is useful when testing type stability of functions returning a small union such as `Union{Nothing, T}` or `Union{Missing, T}`.
```
julia> f(a) = a > 1 ? 1 : 1.0
f (generic function with 1 method)
julia> typeof(f(2))
Int64
julia> @code_warntype f(2)
MethodInstance for f(::Int64)
from f(a) in Main at none:1
Arguments
#self#::Core.Const(f)
a::Int64
Body::UNION{FLOAT64, INT64}
1 ─ %1 = (a > 1)::Bool
└── goto #3 if not %1
2 ─ return 1
3 ─ return 1.0
julia> @inferred f(2)
ERROR: return type Int64 does not match inferred return type Union{Float64, Int64}
[...]
julia> @inferred max(1, 2)
2
julia> g(a) = a < 10 ? missing : 1.0
g (generic function with 1 method)
julia> @inferred g(20)
ERROR: return type Float64 does not match inferred return type Union{Missing, Float64}
[...]
julia> @inferred Missing g(20)
1.0
julia> h(a) = a < 10 ? missing : f(a)
h (generic function with 1 method)
julia> @inferred Missing h(20)
ERROR: return type Int64 does not match inferred return type Union{Missing, Float64, Int64}
[...]
```
###
`Test.@test_deprecated`Macro
```
@test_deprecated [pattern] expression
```
When `--depwarn=yes`, test that `expression` emits a deprecation warning and return the value of `expression`. The log message string will be matched against `pattern` which defaults to `r"deprecated"i`.
When `--depwarn=no`, simply return the result of executing `expression`. When `--depwarn=error`, check that an ErrorException is thrown.
**Examples**
```
# Deprecated in julia 0.7
@test_deprecated num2hex(1)
# The returned value can be tested by chaining with @test:
@test (@test_deprecated num2hex(1)) == "0000000000000001"
```
###
`Test.@test_warn`Macro
```
@test_warn msg expr
```
Test whether evaluating `expr` results in [`stderr`](../../base/io-network/index#Base.stderr) output that contains the `msg` string or matches the `msg` regular expression. If `msg` is a boolean function, tests whether `msg(output)` returns `true`. If `msg` is a tuple or array, checks that the error output contains/matches each item in `msg`. Returns the result of evaluating `expr`.
See also [`@test_nowarn`](#Test.@test_nowarn) to check for the absence of error output.
Note: Warnings generated by `@warn` cannot be tested with this macro. Use [`@test_logs`](#Test.@test_logs) instead.
###
`Test.@test_nowarn`Macro
```
@test_nowarn expr
```
Test whether evaluating `expr` results in empty [`stderr`](../../base/io-network/index#Base.stderr) output (no warnings or other messages). Returns the result of evaluating `expr`.
Note: The absence of warnings generated by `@warn` cannot be tested with this macro. Use [`@test_logs`](#Test.@test_logs) instead.
[Broken Tests](#Broken-Tests)
------------------------------
If a test fails consistently it can be changed to use the `@test_broken` macro. This will denote the test as `Broken` if the test continues to fail and alerts the user via an `Error` if the test succeeds.
###
`Test.@test_broken`Macro
```
@test_broken ex
@test_broken f(args...) key=val ...
```
Indicates a test that should pass but currently consistently fails. Tests that the expression `ex` evaluates to `false` or causes an exception. Returns a `Broken` `Result` if it does, or an `Error` `Result` if the expression evaluates to `true`. This is equivalent to [`@test ex broken=true`](#Test.@test).
The `@test_broken f(args...) key=val...` form works as for the `@test` macro.
**Examples**
```
julia> @test_broken 1 == 2
Test Broken
Expression: 1 == 2
julia> @test_broken 1 == 2 atol=0.1
Test Broken
Expression: ==(1, 2, atol = 0.1)
```
`@test_skip` is also available to skip a test without evaluation, but counting the skipped test in the test set reporting. The test will not run but gives a `Broken` `Result`.
###
`Test.@test_skip`Macro
```
@test_skip ex
@test_skip f(args...) key=val ...
```
Marks a test that should not be executed but should be included in test summary reporting as `Broken`. This can be useful for tests that intermittently fail, or tests of not-yet-implemented functionality. This is equivalent to [`@test ex skip=true`](#Test.@test).
The `@test_skip f(args...) key=val...` form works as for the `@test` macro.
**Examples**
```
julia> @test_skip 1 == 2
Test Broken
Skipped: 1 == 2
julia> @test_skip 1 == 2 atol=0.1
Test Broken
Skipped: ==(1, 2, atol = 0.1)
```
[Creating Custom `AbstractTestSet` Types](#Creating-Custom-AbstractTestSet-Types)
----------------------------------------------------------------------------------
Packages can create their own `AbstractTestSet` subtypes by implementing the `record` and `finish` methods. The subtype should have a one-argument constructor taking a description string, with any options passed in as keyword arguments.
###
`Test.record`Function
```
record(ts::AbstractTestSet, res::Result)
```
Record a result to a testset. This function is called by the `@testset` infrastructure each time a contained `@test` macro completes, and is given the test result (which could be an `Error`). This will also be called with an `Error` if an exception is thrown inside the test block but outside of a `@test` context.
###
`Test.finish`Function
```
finish(ts::AbstractTestSet)
```
Do any final processing necessary for the given testset. This is called by the `@testset` infrastructure after a test block executes.
Custom `AbstractTestSet` subtypes should call `record` on their parent (if there is one) to add themselves to the tree of test results. This might be implemented as:
```
if get_testset_depth() != 0
# Attach this test set to the parent test set
parent_ts = get_testset()
record(parent_ts, self)
return self
end
```
`Test` takes responsibility for maintaining a stack of nested testsets as they are executed, but any result accumulation is the responsibility of the `AbstractTestSet` subtype. You can access this stack with the `get_testset` and `get_testset_depth` methods. Note that these functions are not exported.
###
`Test.get_testset`Function
```
get_testset()
```
Retrieve the active test set from the task's local storage. If no test set is active, use the fallback default test set.
###
`Test.get_testset_depth`Function
```
get_testset_depth()
```
Returns the number of active test sets, not including the default test set
`Test` also makes sure that nested `@testset` invocations use the same `AbstractTestSet` subtype as their parent unless it is set explicitly. It does not propagate any properties of the testset. Option inheritance behavior can be implemented by packages using the stack infrastructure that `Test` provides.
Defining a basic `AbstractTestSet` subtype might look like:
```
import Test: Test, record, finish
using Test: AbstractTestSet, Result, Pass, Fail, Error
using Test: get_testset_depth, get_testset
struct CustomTestSet <: Test.AbstractTestSet
description::AbstractString
foo::Int
results::Vector
# constructor takes a description string and options keyword arguments
CustomTestSet(desc; foo=1) = new(desc, foo, [])
end
record(ts::CustomTestSet, child::AbstractTestSet) = push!(ts.results, child)
record(ts::CustomTestSet, res::Result) = push!(ts.results, res)
function finish(ts::CustomTestSet)
# just record if we're not the top-level parent
if get_testset_depth() > 0
record(get_testset(), ts)
end
ts
end
```
And using that testset looks like:
```
@testset CustomTestSet foo=4 "custom testset inner 2" begin
# this testset should inherit the type, but not the argument.
@testset "custom testset inner" begin
@test true
end
end
```
[Test utilities](#Test-utilities)
----------------------------------
###
`Test.GenericArray`Type
The `GenericArray` can be used to test generic array APIs that program to the `AbstractArray` interface, in order to ensure that functions can work with array types besides the standard `Array` type.
###
`Test.GenericDict`Type
The `GenericDict` can be used to test generic dict APIs that program to the `AbstractDict` interface, in order to ensure that functions can work with associative types besides the standard `Dict` type.
###
`Test.GenericOrder`Type
The `GenericOrder` can be used to test APIs for their support of generic ordered types.
###
`Test.GenericSet`Type
The `GenericSet` can be used to test generic set APIs that program to the `AbstractSet` interface, in order to ensure that functions can work with set types besides the standard `Set` and `BitSet` types.
###
`Test.GenericString`Type
The `GenericString` can be used to test generic string APIs that program to the `AbstractString` interface, in order to ensure that functions can work with string types besides the standard `String` type.
###
`Test.detect_ambiguities`Function
```
detect_ambiguities(mod1, mod2...; recursive=false,
ambiguous_bottom=false,
allowed_undefineds=nothing)
```
Returns a vector of `(Method,Method)` pairs of ambiguous methods defined in the specified modules. Use `recursive=true` to test in all submodules.
`ambiguous_bottom` controls whether ambiguities triggered only by `Union{}` type parameters are included; in most cases you probably want to set this to `false`. See [`Base.isambiguous`](../../base/base/index#Base.isambiguous).
See [`Test.detect_unbound_args`](#Test.detect_unbound_args) for an explanation of `allowed_undefineds`.
`allowed_undefineds` requires at least Julia 1.8.
###
`Test.detect_unbound_args`Function
```
detect_unbound_args(mod1, mod2...; recursive=false, allowed_undefineds=nothing)
```
Returns a vector of `Method`s which may have unbound type parameters. Use `recursive=true` to test in all submodules.
By default, any undefined symbols trigger a warning. This warning can be suppressed by supplying a collection of `GlobalRef`s for which the warning can be skipped. For example, setting
```
allow_undefineds = Set([GlobalRef(Base, :active_repl),
GlobalRef(Base, :active_repl_backend)])
```
would suppress warnings about `Base.active_repl` and `Base.active_repl_backend`.
`allowed_undefineds` requires at least Julia 1.8.
| programming_docs |
julia Unicode Unicode
=======
###
`Unicode.julia_chartransform`Function
```
Unicode.julia_chartransform(c::Union{Char,Integer})
```
Map the Unicode character (`Char`) or codepoint (`Integer`) `c` to the corresponding "equivalent" character or codepoint, respectively, according to the custom equivalence used within the Julia parser (in addition to NFC normalization).
For example, `'µ'` (U+00B5 micro) is treated as equivalent to `'μ'` (U+03BC mu) by Julia's parser, so `julia_chartransform` performs this transformation while leaving other characters unchanged:
```
julia> Unicode.julia_chartransform('µ')
'μ': Unicode U+03BC (category Ll: Letter, lowercase)
julia> Unicode.julia_chartransform('x')
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
```
`julia_chartransform` is mainly useful for passing to the [`Unicode.normalize`](#Unicode.normalize) function in order to mimic the normalization used by the Julia parser:
```
julia> s = "µö"
"µö"
julia> s2 = Unicode.normalize(s, compose=true, stable=true, chartransform=Unicode.julia_chartransform)
"μö"
julia> collect(s2)
2-element Vector{Char}:
'μ': Unicode U+03BC (category Ll: Letter, lowercase)
'ö': Unicode U+00F6 (category Ll: Letter, lowercase)
julia> s2 == string(Meta.parse(s))
true
```
This function was introduced in Julia 1.8.
###
`Unicode.isassigned`Function
```
Unicode.isassigned(c) -> Bool
```
Returns `true` if the given char or integer is an assigned Unicode code point.
**Examples**
```
julia> Unicode.isassigned(101)
true
julia> Unicode.isassigned('\x01')
true
```
###
`Unicode.isequal_normalized`Function
```
isequal_normalized(s1::AbstractString, s2::AbstractString; casefold=false, stripmark=false, chartransform=identity)
```
Return whether `s1` and `s2` are canonically equivalent Unicode strings. If `casefold=true`, ignores case (performs Unicode case-folding); if `stripmark=true`, strips diacritical marks and other combining characters.
As with [`Unicode.normalize`](#Unicode.normalize), you can also pass an arbitrary function via the `chartransform` keyword (mapping `Integer` codepoints to codepoints) to perform custom normalizations, such as [`Unicode.julia_chartransform`](#Unicode.julia_chartransform).
**Examples**
For example, the string `"noël"` can be constructed in two canonically equivalent ways in Unicode, depending on whether `"ë"` is formed from a single codepoint U+00EB or from the ASCII character `'o'` followed by the U+0308 combining-diaeresis character.
```
julia> s1 = "noël"
"noël"
julia> s2 = "noël"
"noël"
julia> s1 == s2
false
julia> isequal_normalized(s1, s2)
true
julia> isequal_normalized(s1, "noel", stripmark=true)
true
julia> isequal_normalized(s1, "NOËL", casefold=true)
true
```
###
`Unicode.normalize`Function
```
Unicode.normalize(s::AbstractString; keywords...)
Unicode.normalize(s::AbstractString, normalform::Symbol)
```
Normalize the string `s`. By default, canonical composition (`compose=true`) is performed without ensuring Unicode versioning stability (`compat=false`), which produces the shortest possible equivalent string but may introduce composition characters not present in earlier Unicode versions.
Alternatively, one of the four "normal forms" of the Unicode standard can be specified: `normalform` can be `:NFC`, `:NFD`, `:NFKC`, or `:NFKD`. Normal forms C (canonical composition) and D (canonical decomposition) convert different visually identical representations of the same abstract string into a single canonical form, with form C being more compact. Normal forms KC and KD additionally canonicalize "compatibility equivalents": they convert characters that are abstractly similar but visually distinct into a single canonical choice (e.g. they expand ligatures into the individual characters), with form KC being more compact.
Alternatively, finer control and additional transformations may be obtained by calling `Unicode.normalize(s; keywords...)`, where any number of the following boolean keywords options (which all default to `false` except for `compose`) are specified:
* `compose=false`: do not perform canonical composition
* `decompose=true`: do canonical decomposition instead of canonical composition (`compose=true` is ignored if present)
* `compat=true`: compatibility equivalents are canonicalized
* `casefold=true`: perform Unicode case folding, e.g. for case-insensitive string comparison
* `newline2lf=true`, `newline2ls=true`, or `newline2ps=true`: convert various newline sequences (LF, CRLF, CR, NEL) into a linefeed (LF), line-separation (LS), or paragraph-separation (PS) character, respectively
* `stripmark=true`: strip diacritical marks (e.g. accents)
* `stripignore=true`: strip Unicode's "default ignorable" characters (e.g. the soft hyphen or the left-to-right marker)
* `stripcc=true`: strip control characters; horizontal tabs and form feeds are converted to spaces; newlines are also converted to spaces unless a newline-conversion flag was specified
* `rejectna=true`: throw an error if unassigned code points are found
* `stable=true`: enforce Unicode versioning stability (never introduce characters missing from earlier Unicode versions)
You can also use the `chartransform` keyword (which defaults to `identity`) to pass an arbitrary *function* mapping `Integer` codepoints to codepoints, which is is called on each character in `s` as it is processed, in order to perform arbitrary additional normalizations. For example, by passing `chartransform=Unicode.julia_chartransform`, you can apply a few Julia-specific character normalizations that are performed by Julia when parsing identifiers (in addition to NFC normalization: `compose=true, stable=true`).
For example, NFKC corresponds to the options `compose=true, compat=true, stable=true`.
**Examples**
```
julia> "é" == Unicode.normalize("é") #LHS: Unicode U+00e9, RHS: U+0065 & U+0301
true
julia> "μ" == Unicode.normalize("µ", compat=true) #LHS: Unicode U+03bc, RHS: Unicode U+00b5
true
julia> Unicode.normalize("JuLiA", casefold=true)
"julia"
julia> Unicode.normalize("JúLiA", stripmark=true)
"JuLiA"
```
The `chartransform` keyword argument requires Julia 1.8.
###
`Unicode.graphemes`Function
```
graphemes(s::AbstractString) -> GraphemeIterator
```
Returns an iterator over substrings of `s` that correspond to the extended graphemes in the string, as defined by Unicode UAX #29. (Roughly, these are what users would perceive as single characters, even though they may contain more than one codepoint; for example a letter combined with an accent mark is a single grapheme.)
julia Memory-mapped I/O Memory-mapped I/O
=================
###
`Mmap.Anonymous`Type
```
Mmap.Anonymous(name::AbstractString="", readonly::Bool=false, create::Bool=true)
```
Create an `IO`-like object for creating zeroed-out mmapped-memory that is not tied to a file for use in [`mmap`](#Mmap.mmap). Used by `SharedArray` for creating shared memory arrays.
**Examples**
```
julia> using Mmap
julia> anon = Mmap.Anonymous();
julia> isreadable(anon)
true
julia> iswritable(anon)
true
julia> isopen(anon)
true
```
###
`Mmap.mmap`Function
```
mmap(io::Union{IOStream,AbstractString,Mmap.AnonymousMmap}[, type::Type{Array{T,N}}, dims, offset]; grow::Bool=true, shared::Bool=true)
mmap(type::Type{Array{T,N}}, dims)
```
Create an `Array` whose values are linked to a file, using memory-mapping. This provides a convenient way of working with data too large to fit in the computer's memory.
The type is an `Array{T,N}` with a bits-type element of `T` and dimension `N` that determines how the bytes of the array are interpreted. Note that the file must be stored in binary format, and no format conversions are possible (this is a limitation of operating systems, not Julia).
`dims` is a tuple or single [`Integer`](../../base/numbers/index#Core.Integer) specifying the size or length of the array.
The file is passed via the stream argument, either as an open [`IOStream`](../../base/io-network/index#Base.IOStream) or filename string. When you initialize the stream, use `"r"` for a "read-only" array, and `"w+"` to create a new array used to write values to disk.
If no `type` argument is specified, the default is `Vector{UInt8}`.
Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a header in the file. The default value for the offset is the current stream position for an `IOStream`.
The `grow` keyword argument specifies whether the disk file should be grown to accommodate the requested size of array (if the total file size is < requested array size). Write privileges are required to grow the file.
The `shared` keyword argument specifies whether the resulting `Array` and changes made to it will be visible to other processes mapping the same file.
For example, the following code
```
# Create a file for mmapping
# (you could alternatively use mmap to do this step, too)
using Mmap
A = rand(1:20, 5, 30)
s = open("/tmp/mmap.bin", "w+")
# We'll write the dimensions of the array as the first two Ints in the file
write(s, size(A,1))
write(s, size(A,2))
# Now write the data
write(s, A)
close(s)
# Test by reading it back in
s = open("/tmp/mmap.bin") # default is read-only
m = read(s, Int)
n = read(s, Int)
A2 = mmap(s, Matrix{Int}, (m,n))
```
creates a `m`-by-`n` `Matrix{Int}`, linked to the file associated with stream `s`.
A more portable file would need to encode the word size – 32 bit or 64 bit – and endianness information in the header. In practice, consider encoding binary data using standard formats like HDF5 (which can be used with memory-mapping).
```
mmap(io, BitArray, [dims, offset])
```
Create a [`BitArray`](../../base/arrays/index#Base.BitArray) whose values are linked to a file, using memory-mapping; it has the same purpose, works in the same way, and has the same arguments, as [`mmap`](#Mmap.mmap), but the byte representation is different.
**Examples**
```
julia> using Mmap
julia> io = open("mmap.bin", "w+");
julia> B = mmap(io, BitArray, (25,30000));
julia> B[3, 4000] = true;
julia> Mmap.sync!(B);
julia> close(io);
julia> io = open("mmap.bin", "r+");
julia> C = mmap(io, BitArray, (25,30000));
julia> C[3, 4000]
true
julia> C[2, 4000]
false
julia> close(io)
julia> rm("mmap.bin")
```
This creates a 25-by-30000 `BitArray`, linked to the file associated with stream `io`.
###
`Mmap.sync!`Function
```
Mmap.sync!(array)
```
Forces synchronization between the in-memory version of a memory-mapped `Array` or [`BitArray`](../../base/arrays/index#Base.BitArray) and the on-disk version.
julia Distributed Computing Distributed Computing
=====================
###
`Distributed.addprocs`Function
```
addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers
```
Launches worker processes via the specified cluster manager.
For example, Beowulf clusters are supported via a custom cluster manager implemented in the package `ClusterManagers.jl`.
The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable `JULIA_WORKER_TIMEOUT` in the worker process's environment. Relevant only when using TCP/IP as transport.
To launch workers without blocking the REPL, or the containing function if launching workers programmatically, execute `addprocs` in its own task.
**Examples**
```
# On busy clusters, call `addprocs` asynchronously
t = @async addprocs(...)
```
```
# Utilize workers as and when they come online
if nprocs() > 1 # Ensure at least one new worker is available
.... # perform distributed execution
end
```
```
# Retrieve newly launched worker IDs, or any error messages
if istaskdone(t) # Check if `addprocs` has completed to ensure `fetch` doesn't block
if nworkers() == N
new_pids = fetch(t)
else
fetch(t)
end
end
```
```
addprocs(machines; tunnel=false, sshflags=``, max_parallel=10, kwargs...) -> List of process identifiers
```
Add processes on remote machines via SSH. See `exename` to set the path to the `julia` installation on remote machines.
`machines` is a vector of machine specifications. Workers are started for each specification.
A machine specification is either a string `machine_spec` or a tuple - `(machine_spec, count)`.
`machine_spec` is a string of the form `[user@]host[:port] [bind_addr[:port]]`. `user` defaults to current user, `port` to the standard ssh port. If `[bind_addr[:port]]` is specified, other workers will connect to this worker at the specified `bind_addr` and `port`.
`count` is the number of workers to be launched on the specified host. If specified as `:auto` it will launch as many workers as the number of CPU threads on the specific host.
Keyword arguments:
* `tunnel`: if `true` then SSH tunneling will be used to connect to the worker from the master process. Default is `false`.
* `multiplex`: if `true` then SSH multiplexing is used for SSH tunneling. Default is `false`.
* `ssh`: the name or path of the SSH client executable used to start the workers. Default is `"ssh"`.
* `sshflags`: specifies additional ssh options, e.g. `sshflags=`-i /home/foo/bar.pem``
* `max_parallel`: specifies the maximum number of workers connected to in parallel at a host. Defaults to 10.
* `shell`: specifies the type of shell to which ssh connects on the workers.
+ `shell=:posix`: a POSIX-compatible Unix/Linux shell (sh, ksh, bash, dash, zsh, etc.). The default.
+ `shell=:csh`: a Unix C shell (csh, tcsh).
+ `shell=:wincmd`: Microsoft Windows `cmd.exe`.
* `dir`: specifies the working directory on the workers. Defaults to the host's current directory (as found by `pwd()`)
* `enable_threaded_blas`: if `true` then BLAS will run on multiple threads in added processes. Default is `false`.
* `exename`: name of the `julia` executable. Defaults to `"$(Sys.BINDIR)/julia"` or `"$(Sys.BINDIR)/julia-debug"` as the case may be.
* `exeflags`: additional flags passed to the worker processes.
* `topology`: Specifies how the workers connect to each other. Sending a message between unconnected workers results in an error.
+ `topology=:all_to_all`: All processes are connected to each other. The default.
+ `topology=:master_worker`: Only the driver process, i.e. `pid` 1 connects to the workers. The workers do not connect to each other.
+ `topology=:custom`: The `launch` method of the cluster manager specifies the connection topology via fields `ident` and `connect_idents` in `WorkerConfig`. A worker with a cluster manager identity `ident` will connect to all workers specified in `connect_idents`.
* `lazy`: Applicable only with `topology=:all_to_all`. If `true`, worker-worker connections are setup lazily, i.e. they are setup at the first instance of a remote call between workers. Default is true.
* `env`: provide an array of string pairs such as `env=["JULIA_DEPOT_PATH"=>"/depot"]` to request that environment variables are set on the remote machine. By default only the environment variable `JULIA_WORKER_TIMEOUT` is passed automatically from the local to the remote environment.
* `cmdline_cookie`: pass the authentication cookie via the `--worker` commandline option. The (more secure) default behaviour of passing the cookie via ssh stdio may hang with Windows workers that use older (pre-ConPTY) Julia or Windows versions, in which case `cmdline_cookie=true` offers a work-around.
The keyword arguments `ssh`, `shell`, `env` and `cmdline_cookie` were added in Julia 1.6.
Environment variables:
If the master process fails to establish a connection with a newly launched worker within 60.0 seconds, the worker treats it as a fatal situation and terminates. This timeout can be controlled via environment variable `JULIA_WORKER_TIMEOUT`. The value of `JULIA_WORKER_TIMEOUT` on the master process specifies the number of seconds a newly launched worker waits for connection establishment.
```
addprocs(; kwargs...) -> List of process identifiers
```
Equivalent to `addprocs(Sys.CPU_THREADS; kwargs...)`
Note that workers do not run a `.julia/config/startup.jl` startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes.
```
addprocs(np::Integer; restrict=true, kwargs...) -> List of process identifiers
```
Launches workers using the in-built `LocalManager` which only launches workers on the local host. This can be used to take advantage of multiple cores. `addprocs(4)` will add 4 processes on the local machine. If `restrict` is `true`, binding is restricted to `127.0.0.1`. Keyword args `dir`, `exename`, `exeflags`, `topology`, `lazy` and `enable_threaded_blas` have the same effect as documented for `addprocs(machines)`.
###
`Distributed.nprocs`Function
```
nprocs()
```
Get the number of available processes.
**Examples**
```
julia> nprocs()
3
julia> workers()
2-element Array{Int64,1}:
2
3
```
###
`Distributed.nworkers`Function
```
nworkers()
```
Get the number of available worker processes. This is one less than [`nprocs()`](#Distributed.nprocs). Equal to `nprocs()` if `nprocs() == 1`.
**Examples**
```
$ julia -p 2
julia> nprocs()
3
julia> nworkers()
2
```
###
`Distributed.procs`Method
```
procs()
```
Return a list of all process identifiers, including pid 1 (which is not included by [`workers()`](#Distributed.workers)).
**Examples**
```
$ julia -p 2
julia> procs()
3-element Array{Int64,1}:
1
2
3
```
###
`Distributed.procs`Method
```
procs(pid::Integer)
```
Return a list of all process identifiers on the same physical node. Specifically all workers bound to the same ip-address as `pid` are returned.
###
`Distributed.workers`Function
```
workers()
```
Return a list of all worker process identifiers.
**Examples**
```
$ julia -p 2
julia> workers()
2-element Array{Int64,1}:
2
3
```
###
`Distributed.rmprocs`Function
```
rmprocs(pids...; waitfor=typemax(Int))
```
Remove the specified workers. Note that only process 1 can add or remove workers.
Argument `waitfor` specifies how long to wait for the workers to shut down:
* If unspecified, `rmprocs` will wait until all requested `pids` are removed.
* An [`ErrorException`](../../base/base/index#Core.ErrorException) is raised if all workers cannot be terminated before the requested `waitfor` seconds.
* With a `waitfor` value of 0, the call returns immediately with the workers scheduled for removal in a different task. The scheduled [`Task`](../../base/parallel/index#Core.Task) object is returned. The user should call [`wait`](../../base/parallel/index#Base.wait) on the task before invoking any other parallel calls.
**Examples**
```
$ julia -p 5
julia> t = rmprocs(2, 3, waitfor=0)
Task (runnable) @0x0000000107c718d0
julia> wait(t)
julia> workers()
3-element Array{Int64,1}:
4
5
6
```
###
`Distributed.interrupt`Function
```
interrupt(pids::Integer...)
```
Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.
```
interrupt(pids::AbstractVector=workers())
```
Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.
###
`Distributed.myid`Function
```
myid()
```
Get the id of the current process.
**Examples**
```
julia> myid()
1
julia> remotecall_fetch(() -> myid(), 4)
4
```
###
`Distributed.pmap`Function
```
pmap(f, [::AbstractWorkerPool], c...; distributed=true, batch_size=1, on_error=nothing, retry_delays=[], retry_check=nothing) -> collection
```
Transform collection `c` by applying `f` to each element using available workers and tasks.
For multiple collection arguments, apply `f` elementwise.
Note that `f` must be made available to all worker processes; see [Code Availability and Loading Packages](../../manual/distributed-computing/index#code-availability) for details.
If a worker pool is not specified, all available workers, i.e., the default worker pool is used.
By default, `pmap` distributes the computation over all specified workers. To use only the local process and distribute over tasks, specify `distributed=false`. This is equivalent to using [`asyncmap`](../../base/parallel/index#Base.asyncmap). For example, `pmap(f, c; distributed=false)` is equivalent to `asyncmap(f,c; ntasks=()->nworkers())`
`pmap` can also use a mix of processes and tasks via the `batch_size` argument. For batch sizes greater than 1, the collection is processed in multiple batches, each of length `batch_size` or less. A batch is sent as a single request to a free worker, where a local [`asyncmap`](../../base/parallel/index#Base.asyncmap) processes elements from the batch using multiple concurrent tasks.
Any error stops `pmap` from processing the remainder of the collection. To override this behavior you can specify an error handling function via argument `on_error` which takes in a single argument, i.e., the exception. The function can stop the processing by rethrowing the error, or, to continue, return any value which is then returned inline with the results to the caller.
Consider the following two examples. The first one returns the exception object inline, the second a 0 in place of any exception:
```
julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=identity)
4-element Array{Any,1}:
1
ErrorException("foo")
3
ErrorException("foo")
julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=ex->0)
4-element Array{Int64,1}:
1
0
3
0
```
Errors can also be handled by retrying failed computations. Keyword arguments `retry_delays` and `retry_check` are passed through to [`retry`](../../base/base/index#Base.retry) as keyword arguments `delays` and `check` respectively. If batching is specified, and an entire batch fails, all items in the batch are retried.
Note that if both `on_error` and `retry_delays` are specified, the `on_error` hook is called before retrying. If `on_error` does not throw (or rethrow) an exception, the element will not be retried.
Example: On errors, retry `f` on an element a maximum of 3 times without any delay between retries.
```
pmap(f, c; retry_delays = zeros(3))
```
Example: Retry `f` only if the exception is not of type [`InexactError`](../../base/base/index#Core.InexactError), with exponentially increasing delays up to 3 times. Return a `NaN` in place for all `InexactError` occurrences.
```
pmap(f, c; on_error = e->(isa(e, InexactError) ? NaN : rethrow()), retry_delays = ExponentialBackOff(n = 3))
```
###
`Distributed.RemoteException`Type
```
RemoteException(captured)
```
Exceptions on remote computations are captured and rethrown locally. A `RemoteException` wraps the `pid` of the worker and a captured exception. A `CapturedException` captures the remote exception and a serializable form of the call stack when the exception was raised.
###
`Distributed.Future`Type
```
Future(w::Int, rrid::RRID, v::Union{Some, Nothing}=nothing)
```
A `Future` is a placeholder for a single computation of unknown termination status and time. For multiple potential computations, see `RemoteChannel`. See `remoteref_id` for identifying an `AbstractRemoteRef`.
###
`Distributed.RemoteChannel`Type
```
RemoteChannel(pid::Integer=myid())
```
Make a reference to a `Channel{Any}(1)` on process `pid`. The default `pid` is the current process.
```
RemoteChannel(f::Function, pid::Integer=myid())
```
Create references to remote channels of a specific size and type. `f` is a function that when executed on `pid` must return an implementation of an `AbstractChannel`.
For example, `RemoteChannel(()->Channel{Int}(10), pid)`, will return a reference to a channel of type `Int` and size 10 on `pid`.
The default `pid` is the current process.
###
`Base.fetch`Method
```
fetch(x::Future)
```
Wait for and get the value of a [`Future`](#Distributed.Future). The fetched value is cached locally. Further calls to `fetch` on the same reference return the cached value. If the remote value is an exception, throws a [`RemoteException`](#Distributed.RemoteException) which captures the remote exception and backtrace.
###
`Base.fetch`Method
```
fetch(c::RemoteChannel)
```
Wait for and get a value from a [`RemoteChannel`](#Distributed.RemoteChannel). Exceptions raised are the same as for a [`Future`](#Distributed.Future). Does not remove the item fetched.
###
`Distributed.remotecall`Method
```
remotecall(f, id::Integer, args...; kwargs...) -> Future
```
Call a function `f` asynchronously on the given arguments on the specified process. Return a [`Future`](#Distributed.Future). Keyword arguments, if any, are passed through to `f`.
###
`Distributed.remotecall_wait`Method
```
remotecall_wait(f, id::Integer, args...; kwargs...)
```
Perform a faster `wait(remotecall(...))` in one message on the `Worker` specified by worker id `id`. Keyword arguments, if any, are passed through to `f`.
See also [`wait`](../../base/parallel/index#Base.wait) and [`remotecall`](#Distributed.remotecall-Tuple%7BAny,%20Integer,%20Vararg%7BAny%7D%7D).
###
`Distributed.remotecall_fetch`Method
```
remotecall_fetch(f, id::Integer, args...; kwargs...)
```
Perform `fetch(remotecall(...))` in one message. Keyword arguments, if any, are passed through to `f`. Any remote exceptions are captured in a [`RemoteException`](#Distributed.RemoteException) and thrown.
See also [`fetch`](#) and [`remotecall`](#Distributed.remotecall-Tuple%7BAny,%20Integer,%20Vararg%7BAny%7D%7D).
**Examples**
```
$ julia -p 2
julia> remotecall_fetch(sqrt, 2, 4)
2.0
julia> remotecall_fetch(sqrt, 2, -4)
ERROR: On worker 2:
DomainError with -4.0:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
...
```
###
`Distributed.remote_do`Method
```
remote_do(f, id::Integer, args...; kwargs...) -> nothing
```
Executes `f` on worker `id` asynchronously. Unlike [`remotecall`](#Distributed.remotecall-Tuple%7BAny,%20Integer,%20Vararg%7BAny%7D%7D), it does not store the result of computation, nor is there a way to wait for its completion.
A successful invocation indicates that the request has been accepted for execution on the remote node.
While consecutive `remotecall`s to the same worker are serialized in the order they are invoked, the order of executions on the remote worker is undetermined. For example, `remote_do(f1, 2); remotecall(f2, 2); remote_do(f3, 2)` will serialize the call to `f1`, followed by `f2` and `f3` in that order. However, it is not guaranteed that `f1` is executed before `f3` on worker 2.
Any exceptions thrown by `f` are printed to [`stderr`](../../base/io-network/index#Base.stderr) on the remote worker.
Keyword arguments, if any, are passed through to `f`.
###
`Base.put!`Method
```
put!(rr::RemoteChannel, args...)
```
Store a set of values to the [`RemoteChannel`](#Distributed.RemoteChannel). If the channel is full, blocks until space is available. Return the first argument.
###
`Base.put!`Method
```
put!(rr::Future, v)
```
Store a value to a [`Future`](#Distributed.Future) `rr`. `Future`s are write-once remote references. A `put!` on an already set `Future` throws an `Exception`. All asynchronous remote calls return `Future`s and set the value to the return value of the call upon completion.
###
`Base.take!`Method
```
take!(rr::RemoteChannel, args...)
```
Fetch value(s) from a [`RemoteChannel`](#Distributed.RemoteChannel) `rr`, removing the value(s) in the process.
###
`Base.isready`Method
```
isready(rr::RemoteChannel, args...)
```
Determine whether a [`RemoteChannel`](#Distributed.RemoteChannel) has a value stored to it. Note that this function can cause race conditions, since by the time you receive its result it may no longer be true. However, it can be safely used on a [`Future`](#Distributed.Future) since they are assigned only once.
###
`Base.isready`Method
```
isready(rr::Future)
```
Determine whether a [`Future`](#Distributed.Future) has a value stored to it.
If the argument `Future` is owned by a different node, this call will block to wait for the answer. It is recommended to wait for `rr` in a separate task instead or to use a local [`Channel`](../../base/parallel/index#Base.Channel) as a proxy:
```
p = 1
f = Future(p)
errormonitor(@async put!(f, remotecall_fetch(long_computation, p)))
isready(f) # will not block
```
###
`Distributed.AbstractWorkerPool`Type
```
AbstractWorkerPool
```
Supertype for worker pools such as [`WorkerPool`](#Distributed.WorkerPool) and [`CachingPool`](#Distributed.CachingPool). An `AbstractWorkerPool` should implement:
* [`push!`](../../base/collections/index#Base.push!) - add a new worker to the overall pool (available + busy)
* [`put!`](#) - put back a worker to the available pool
* [`take!`](#) - take a worker from the available pool (to be used for remote function execution)
* [`length`](../../base/collections/index#Base.length) - number of workers available in the overall pool
* [`isready`](#) - return false if a `take!` on the pool would block, else true
The default implementations of the above (on a `AbstractWorkerPool`) require fields
* `channel::Channel{Int}`
* `workers::Set{Int}`
where `channel` contains free worker pids and `workers` is the set of all workers associated with this pool.
###
`Distributed.WorkerPool`Type
```
WorkerPool(workers::Vector{Int})
```
Create a `WorkerPool` from a vector of worker ids.
**Examples**
```
$ julia -p 3
julia> WorkerPool([2, 3])
WorkerPool(Channel{Int64}(sz_max:9223372036854775807,sz_curr:2), Set([2, 3]), RemoteChannel{Channel{Any}}(1, 1, 6))
```
###
`Distributed.CachingPool`Type
```
CachingPool(workers::Vector{Int})
```
An implementation of an `AbstractWorkerPool`. [`remote`](#Distributed.remote), [`remotecall_fetch`](#Distributed.remotecall_fetch-Tuple%7BAny,%20Integer,%20Vararg%7BAny%7D%7D), [`pmap`](#Distributed.pmap) (and other remote calls which execute functions remotely) benefit from caching the serialized/deserialized functions on the worker nodes, especially closures (which may capture large amounts of data).
The remote cache is maintained for the lifetime of the returned `CachingPool` object. To clear the cache earlier, use `clear!(pool)`.
For global variables, only the bindings are captured in a closure, not the data. `let` blocks can be used to capture global data.
**Examples**
```
const foo = rand(10^8);
wp = CachingPool(workers())
let foo = foo
pmap(i -> sum(foo) + i, wp, 1:100);
end
```
The above would transfer `foo` only once to each worker.
###
`Distributed.default_worker_pool`Function
```
default_worker_pool()
```
[`WorkerPool`](#Distributed.WorkerPool) containing idle [`workers`](#Distributed.workers) - used by `remote(f)` and [`pmap`](#Distributed.pmap) (by default).
**Examples**
```
$ julia -p 3
julia> default_worker_pool()
WorkerPool(Channel{Int64}(sz_max:9223372036854775807,sz_curr:3), Set([4, 2, 3]), RemoteChannel{Channel{Any}}(1, 1, 4))
```
###
`Distributed.clear!`Method
```
clear!(pool::CachingPool) -> pool
```
Removes all cached functions from all participating workers.
###
`Distributed.remote`Function
```
remote([p::AbstractWorkerPool], f) -> Function
```
Return an anonymous function that executes function `f` on an available worker (drawn from [`WorkerPool`](#Distributed.WorkerPool) `p` if provided) using [`remotecall_fetch`](#Distributed.remotecall_fetch-Tuple%7BAny,%20Integer,%20Vararg%7BAny%7D%7D).
###
`Distributed.remotecall`Method
```
remotecall(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future
```
[`WorkerPool`](#Distributed.WorkerPool) variant of `remotecall(f, pid, ....)`. Wait for and take a free worker from `pool` and perform a `remotecall` on it.
**Examples**
```
$ julia -p 3
julia> wp = WorkerPool([2, 3]);
julia> A = rand(3000);
julia> f = remotecall(maximum, wp, A)
Future(2, 1, 6, nothing)
```
In this example, the task ran on pid 2, called from pid 1.
###
`Distributed.remotecall_wait`Method
```
remotecall_wait(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future
```
[`WorkerPool`](#Distributed.WorkerPool) variant of `remotecall_wait(f, pid, ....)`. Wait for and take a free worker from `pool` and perform a `remotecall_wait` on it.
**Examples**
```
$ julia -p 3
julia> wp = WorkerPool([2, 3]);
julia> A = rand(3000);
julia> f = remotecall_wait(maximum, wp, A)
Future(3, 1, 9, nothing)
julia> fetch(f)
0.9995177101692958
```
###
`Distributed.remotecall_fetch`Method
```
remotecall_fetch(f, pool::AbstractWorkerPool, args...; kwargs...) -> result
```
[`WorkerPool`](#Distributed.WorkerPool) variant of `remotecall_fetch(f, pid, ....)`. Waits for and takes a free worker from `pool` and performs a `remotecall_fetch` on it.
**Examples**
```
$ julia -p 3
julia> wp = WorkerPool([2, 3]);
julia> A = rand(3000);
julia> remotecall_fetch(maximum, wp, A)
0.9995177101692958
```
###
`Distributed.remote_do`Method
```
remote_do(f, pool::AbstractWorkerPool, args...; kwargs...) -> nothing
```
[`WorkerPool`](#Distributed.WorkerPool) variant of `remote_do(f, pid, ....)`. Wait for and take a free worker from `pool` and perform a `remote_do` on it.
###
`Distributed.@spawnat`Macro
```
@spawnat p expr
```
Create a closure around an expression and run the closure asynchronously on process `p`. Return a [`Future`](#Distributed.Future) to the result. If `p` is the quoted literal symbol `:any`, then the system will pick a processor to use automatically.
**Examples**
```
julia> addprocs(3);
julia> f = @spawnat 2 myid()
Future(2, 1, 3, nothing)
julia> fetch(f)
2
julia> f = @spawnat :any myid()
Future(3, 1, 7, nothing)
julia> fetch(f)
3
```
The `:any` argument is available as of Julia 1.3.
###
`Distributed.@fetch`Macro
```
@fetch expr
```
Equivalent to `fetch(@spawnat :any expr)`. See [`fetch`](#) and [`@spawnat`](#Distributed.@spawnat).
**Examples**
```
julia> addprocs(3);
julia> @fetch myid()
2
julia> @fetch myid()
3
julia> @fetch myid()
4
julia> @fetch myid()
2
```
###
`Distributed.@fetchfrom`Macro
```
@fetchfrom
```
Equivalent to `fetch(@spawnat p expr)`. See [`fetch`](#) and [`@spawnat`](#Distributed.@spawnat).
**Examples**
```
julia> addprocs(3);
julia> @fetchfrom 2 myid()
2
julia> @fetchfrom 4 myid()
4
```
###
`Distributed.@distributed`Macro
```
@distributed
```
A distributed memory, parallel for loop of the form :
```
@distributed [reducer] for var = range
body
end
```
The specified range is partitioned and locally executed across all workers. In case an optional reducer function is specified, `@distributed` performs local reductions on each worker with a final reduction on the calling process.
Note that without a reducer function, `@distributed` executes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with [`@sync`](../../base/parallel/index#Base.@sync), like :
```
@sync @distributed for var = range
body
end
```
###
`Distributed.@everywhere`Macro
```
@everywhere [procs()] expr
```
Execute an expression under `Main` on all `procs`. Errors on any of the processes are collected into a [`CompositeException`](../../base/base/index#Base.CompositeException) and thrown. For example:
```
@everywhere bar = 1
```
will define `Main.bar` on all current processes. Any processes added later (say with [`addprocs()`](#Distributed.addprocs)) will not have the expression defined.
Unlike [`@spawnat`](#Distributed.@spawnat), `@everywhere` does not capture any local variables. Instead, local variables can be broadcast using interpolation:
```
foo = 1
@everywhere bar = $foo
```
The optional argument `procs` allows specifying a subset of all processes to have execute the expression.
Similar to calling `remotecall_eval(Main, procs, expr)`, but with two extra features:
```
- `using` and `import` statements run on the calling process first, to ensure
packages are precompiled.
- The current source file path used by `include` is propagated to other processes.
```
###
`Distributed.clear!`Method
```
clear!(syms, pids=workers(); mod=Main)
```
Clears global bindings in modules by initializing them to `nothing`. `syms` should be of type [`Symbol`](../../base/base/index#Core.Symbol) or a collection of `Symbol`s . `pids` and `mod` identify the processes and the module in which global variables are to be reinitialized. Only those names found to be defined under `mod` are cleared.
An exception is raised if a global constant is requested to be cleared.
###
`Distributed.remoteref_id`Function
```
remoteref_id(r::AbstractRemoteRef) -> RRID
```
`Future`s and `RemoteChannel`s are identified by fields:
* `where` - refers to the node where the underlying object/storage referred to by the reference actually exists.
* `whence` - refers to the node the remote reference was created from. Note that this is different from the node where the underlying object referred to actually exists. For example calling `RemoteChannel(2)` from the master process would result in a `where` value of 2 and a `whence` value of 1.
* `id` is unique across all references created from the worker specified by `whence`.
Taken together, `whence` and `id` uniquely identify a reference across all workers.
`remoteref_id` is a low-level API which returns a `RRID` object that wraps `whence` and `id` values of a remote reference.
###
`Distributed.channel_from_id`Function
```
channel_from_id(id) -> c
```
A low-level API which returns the backing `AbstractChannel` for an `id` returned by [`remoteref_id`](#Distributed.remoteref_id). The call is valid only on the node where the backing channel exists.
###
`Distributed.worker_id_from_socket`Function
```
worker_id_from_socket(s) -> pid
```
A low-level API which, given a `IO` connection or a `Worker`, returns the `pid` of the worker it is connected to. This is useful when writing custom [`serialize`](../serialization/index#Serialization.serialize) methods for a type, which optimizes the data written out depending on the receiving process id.
###
`Distributed.cluster_cookie`Method
```
cluster_cookie() -> cookie
```
Return the cluster cookie.
###
`Distributed.cluster_cookie`Method
```
cluster_cookie(cookie) -> cookie
```
Set the passed cookie as the cluster cookie, then returns it.
[Cluster Manager Interface](#Cluster-Manager-Interface)
--------------------------------------------------------
This interface provides a mechanism to launch and manage Julia workers on different cluster environments. There are two types of managers present in Base: `LocalManager`, for launching additional workers on the same host, and `SSHManager`, for launching on remote hosts via `ssh`. TCP/IP sockets are used to connect and transport messages between processes. It is possible for Cluster Managers to provide a different transport.
###
`Distributed.ClusterManager`Type
```
ClusterManager
```
Supertype for cluster managers, which control workers processes as a cluster. Cluster managers implement how workers can be added, removed and communicated with. `SSHManager` and `LocalManager` are subtypes of this.
###
`Distributed.WorkerConfig`Type
```
WorkerConfig
```
Type used by [`ClusterManager`](#Distributed.ClusterManager)s to control workers added to their clusters. Some fields are used by all cluster managers to access a host:
* `io` – the connection used to access the worker (a subtype of `IO` or `Nothing`)
* `host` – the host address (either a `String` or `Nothing`)
* `port` – the port on the host used to connect to the worker (either an `Int` or `Nothing`)
Some are used by the cluster manager to add workers to an already-initialized host:
* `count` – the number of workers to be launched on the host
* `exename` – the path to the Julia executable on the host, defaults to `"$(Sys.BINDIR)/julia"` or `"$(Sys.BINDIR)/julia-debug"`
* `exeflags` – flags to use when lauching Julia remotely
The `userdata` field is used to store information for each worker by external managers.
Some fields are used by `SSHManager` and similar managers:
* `tunnel` – `true` (use tunneling), `false` (do not use tunneling), or [`nothing`](../../base/constants/index#Core.nothing) (use default for the manager)
* `multiplex` – `true` (use SSH multiplexing for tunneling) or `false`
* `forward` – the forwarding option used for `-L` option of ssh
* `bind_addr` – the address on the remote host to bind to
* `sshflags` – flags to use in establishing the SSH connection
* `max_parallel` – the maximum number of workers to connect to in parallel on the host
Some fields are used by both `LocalManager`s and `SSHManager`s:
* `connect_at` – determines whether this is a worker-to-worker or driver-to-worker setup call
* `process` – the process which will be connected (usually the manager will assign this during [`addprocs`](#Distributed.addprocs))
* `ospid` – the process ID according to the host OS, used to interrupt worker processes
* `environ` – private dictionary used to store temporary information by Local/SSH managers
* `ident` – worker as identified by the [`ClusterManager`](#Distributed.ClusterManager)
* `connect_idents` – list of worker ids the worker must connect to if using a custom topology
* `enable_threaded_blas` – `true`, `false`, or `nothing`, whether to use threaded BLAS or not on the workers
###
`Distributed.launch`Function
```
launch(manager::ClusterManager, params::Dict, launched::Array, launch_ntfy::Condition)
```
Implemented by cluster managers. For every Julia worker launched by this function, it should append a `WorkerConfig` entry to `launched` and notify `launch_ntfy`. The function MUST exit once all workers, requested by `manager` have been launched. `params` is a dictionary of all keyword arguments [`addprocs`](#Distributed.addprocs) was called with.
###
`Distributed.manage`Function
```
manage(manager::ClusterManager, id::Integer, config::WorkerConfig. op::Symbol)
```
Implemented by cluster managers. It is called on the master process, during a worker's lifetime, with appropriate `op` values:
* with `:register`/`:deregister` when a worker is added / removed from the Julia worker pool.
* with `:interrupt` when `interrupt(workers)` is called. The `ClusterManager` should signal the appropriate worker with an interrupt signal.
* with `:finalize` for cleanup purposes.
###
`Base.kill`Method
```
kill(manager::ClusterManager, pid::Int, config::WorkerConfig)
```
Implemented by cluster managers. It is called on the master process, by [`rmprocs`](#Distributed.rmprocs). It should cause the remote worker specified by `pid` to exit. `kill(manager::ClusterManager.....)` executes a remote `exit()` on `pid`.
###
`Sockets.connect`Method
```
connect(manager::ClusterManager, pid::Int, config::WorkerConfig) -> (instrm::IO, outstrm::IO)
```
Implemented by cluster managers using custom transports. It should establish a logical connection to worker with id `pid`, specified by `config` and return a pair of `IO` objects. Messages from `pid` to current process will be read off `instrm`, while messages to be sent to `pid` will be written to `outstrm`. The custom transport implementation must ensure that messages are delivered and received completely and in order. `connect(manager::ClusterManager.....)` sets up TCP/IP socket connections in-between workers.
###
`Distributed.init_worker`Function
```
init_worker(cookie::AbstractString, manager::ClusterManager=DefaultClusterManager())
```
Called by cluster managers implementing custom transports. It initializes a newly launched process as a worker. Command line argument `--worker[=<cookie>]` has the effect of initializing a process as a worker using TCP/IP sockets for transport. `cookie` is a [`cluster_cookie`](#Distributed.cluster_cookie-Tuple%7B%7D).
###
`Distributed.start_worker`Function
```
start_worker([out::IO=stdout], cookie::AbstractString=readline(stdin); close_stdin::Bool=true, stderr_to_stdout::Bool=true)
```
`start_worker` is an internal function which is the default entry point for worker processes connecting via TCP/IP. It sets up the process as a Julia cluster worker.
host:port information is written to stream `out` (defaults to stdout).
The function reads the cookie from stdin if required, and listens on a free port (or if specified, the port in the `--bind-to` command line option) and schedules tasks to process incoming TCP connections and requests. It also (optionally) closes stdin and redirects stderr to stdout.
It does not return.
###
`Distributed.process_messages`Function
```
process_messages(r_stream::IO, w_stream::IO, incoming::Bool=true)
```
Called by cluster managers using custom transports. It should be called when the custom transport implementation receives the first message from a remote worker. The custom transport must manage a logical connection to the remote worker and provide two `IO` objects, one for incoming messages and the other for messages addressed to the remote worker. If `incoming` is `true`, the remote peer initiated the connection. Whichever of the pair initiates the connection sends the cluster cookie and its Julia version number to perform the authentication handshake.
See also [`cluster_cookie`](#Distributed.cluster_cookie-Tuple%7B%7D).
###
`Distributed.default_addprocs_params`Function
```
default_addprocs_params(mgr::ClusterManager) -> Dict{Symbol, Any}
```
Implemented by cluster managers. The default keyword parameters passed when calling `addprocs(mgr)`. The minimal set of options is available by calling `default_addprocs_params()`
| programming_docs |
julia Markdown Markdown
========
This section describes Julia's markdown syntax, which is enabled by the Markdown standard library. The following Markdown elements are supported:
[Inline elements](#Inline-elements)
------------------------------------
Here "inline" refers to elements that can be found within blocks of text, i.e. paragraphs. These include the following elements.
###
[Bold](#Bold)
Surround words with two asterisks, `**`, to display the enclosed text in boldface.
```
A paragraph containing a **bold** word.
```
###
[Italics](#Italics)
Surround words with one asterisk, `*`, to display the enclosed text in italics.
```
A paragraph containing an *italicized* word.
```
###
[Literals](#Literals)
Surround text that should be displayed exactly as written with single backticks, ``` .
```
A paragraph containing a `literal` word.
```
Literals should be used when writing text that refers to names of variables, functions, or other parts of a Julia program.
To include a backtick character within literal text use three backticks rather than one to enclose the text.
```
A paragraph containing ``` `backtick` characters ```.
```
By extension any odd number of backticks may be used to enclose a lesser number of backticks.
###
[$\LaTeX$](#%5C%5CLaTeX)
Surround text that should be displayed as mathematics using $\LaTeX$ syntax with double backticks, ```` .
```
A paragraph containing some ``\LaTeX`` markup.
```
As with literals in the previous section, if literal backticks need to be written within double backticks use an even number greater than two. Note that if a single literal backtick needs to be included within $\LaTeX$ markup then two enclosing backticks is sufficient.
The `\` character should be escaped appropriately if the text is embedded in a Julia source code, for example, `"``\\LaTeX`` syntax in a docstring."`, since it is interpreted as a string literal. Alternatively, in order to avoid escaping, it is possible to use the `raw` string macro together with the `@doc` macro:
```
@doc raw"``\LaTeX`` syntax in a docstring." functionname
```
###
[Links](#Links)
Links to either external or internal targets can be written using the following syntax, where the text enclosed in square brackets, `[ ]`, is the name of the link and the text enclosed in parentheses, `( )`, is the URL.
```
A paragraph containing a link to [Julia](http://www.julialang.org).
```
It's also possible to add cross-references to other documented functions/methods/variables within the Julia documentation itself. For example:
```
"""
tryparse(type, str; base)
Like [`parse`](@ref), but returns either a value of the requested type,
or [`nothing`](@ref) if the string does not contain a valid number.
"""
```
This will create a link in the generated docs to the [`parse`](../../base/numbers/index#Base.parse) documentation (which has more information about what this function actually does), and to the [`nothing`](../../base/constants/index#Core.nothing) documentation. It's good to include cross references to mutating/non-mutating versions of a function, or to highlight a difference between two similar-seeming functions.
The above cross referencing is *not* a Markdown feature, and relies on [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl), which is used to build base Julia's documentation.
###
[Footnote references](#Footnote-references)
Named and numbered footnote references can be written using the following syntax. A footnote name must be a single alphanumeric word containing no punctuation.
```
A paragraph containing a numbered footnote [^1] and a named one [^named].
```
The text associated with a footnote can be written anywhere within the same page as the footnote reference. The syntax used to define the footnote text is discussed in the [Footnotes](#Footnotes) section below.
[Toplevel elements](#Toplevel-elements)
----------------------------------------
The following elements can be written either at the "toplevel" of a document or within another "toplevel" element.
###
[Paragraphs](#Paragraphs)
A paragraph is a block of plain text, possibly containing any number of inline elements defined in the [Inline elements](#Inline-elements) section above, with one or more blank lines above and below it.
```
This is a paragraph.
And this is *another* paragraph containing some emphasized text.
A new line, but still part of the same paragraph.
```
###
[Headers](#Headers)
A document can be split up into different sections using headers. Headers use the following syntax:
```
# Level One
## Level Two
### Level Three
#### Level Four
##### Level Five
###### Level Six
```
A header line can contain any inline syntax in the same way as a paragraph can.
Try to avoid using too many levels of header within a single document. A heavily nested document may be indicative of a need to restructure it or split it into several pages covering separate topics.
###
[Code blocks](#Code-blocks)
Source code can be displayed as a literal block using an indent of four spaces as shown in the following example.
```
This is a paragraph.
function func(x)
# ...
end
Another paragraph.
```
Additionally, code blocks can be enclosed using triple backticks with an optional "language" to specify how a block of code should be highlighted.
```
A code block without a "language":
```
function func(x)
# ...
end
```
and another one with the "language" specified as `julia`:
```julia
function func(x)
# ...
end
```
```
"Fenced" code blocks, as shown in the last example, should be preferred over indented code blocks since there is no way to specify what language an indented code block is written in.
###
[Block quotes](#Block-quotes)
Text from external sources, such as quotations from books or websites, can be quoted using `>` characters prepended to each line of the quote as follows.
```
Here's a quote:
> Julia is a high-level, high-performance dynamic programming language for
> technical computing, with syntax that is familiar to users of other
> technical computing environments.
```
Note that a single space must appear after the `>` character on each line. Quoted blocks may themselves contain other toplevel or inline elements.
###
[Images](#Images)
The syntax for images is similar to the link syntax mentioned above. Prepending a `!` character to a link will display an image from the specified URL rather than a link to it.
```

```
###
[Lists](#Lists)
Unordered lists can be written by prepending each item in a list with either `*`, `+`, or `-`.
```
A list of items:
* item one
* item two
* item three
```
Note the two spaces before each `*` and the single space after each one.
Lists can contain other nested toplevel elements such as lists, code blocks, or quoteblocks. A blank line should be left between each list item when including any toplevel elements within a list.
```
Another list:
* item one
* item two
```
f(x) = x
```
* And a sublist:
+ sub-item one
+ sub-item two
```
The contents of each item in the list must line up with the first line of the item. In the above example the fenced code block must be indented by four spaces to align with the `i` in `item two`.
Ordered lists are written by replacing the "bullet" character, either `*`, `+`, or `-`, with a positive integer followed by either `.` or `)`.
```
Two ordered lists:
1. item one
2. item two
3. item three
5) item five
6) item six
7) item seven
```
An ordered list may start from a number other than one, as in the second list of the above example, where it is numbered from five. As with unordered lists, ordered lists can contain nested toplevel elements.
###
[Display equations](#Display-equations)
Large $\LaTeX$ equations that do not fit inline within a paragraph may be written as display equations using a fenced code block with the "language" `math` as in the example below.
```
```math
f(a) = \frac{1}{2\pi}\int_{0}^{2\pi} (\alpha+R\cos(\theta))d\theta
```
```
###
[Footnotes](#Footnotes)
This syntax is paired with the inline syntax for [Footnote references](#Footnote-references). Make sure to read that section as well.
Footnote text is defined using the following syntax, which is similar to footnote reference syntax, aside from the `:` character that is appended to the footnote label.
```
[^1]: Numbered footnote text.
[^note]:
Named footnote text containing several toplevel elements.
* item one
* item two
* item three
```julia
function func(x)
# ...
end
```
```
No checks are done during parsing to make sure that all footnote references have matching footnotes.
###
[Horizontal rules](#Horizontal-rules)
The equivalent of an `<hr>` HTML tag can be achieved using three hyphens (`---`). For example:
```
Text above the line.
---
And text below the line.
```
###
[Tables](#Tables)
Basic tables can be written using the syntax described below. Note that markdown tables have limited features and cannot contain nested toplevel elements unlike other elements discussed above – only inline elements are allowed. Tables must always contain a header row with column names. Cells cannot span multiple rows or columns of the table.
```
| Column One | Column Two | Column Three |
|:---------- | ---------- |:------------:|
| Row `1` | Column `2` | |
| *Row* 2 | **Row** 2 | Column ``3`` |
```
As illustrated in the above example each column of `|` characters must be aligned vertically.
A `:` character on either end of a column's header separator (the row containing `-` characters) specifies whether the row is left-aligned, right-aligned, or (when `:` appears on both ends) center-aligned. Providing no `:` characters will default to right-aligning the column.
###
[Admonitions](#Admonitions)
Specially formatted blocks, known as admonitions, can be used to highlight particular remarks. They can be defined using the following `!!!` syntax:
```
!!! note
This is the content of the note.
!!! warning "Beware!"
And this is another one.
This warning admonition has a custom title: `"Beware!"`.
```
The first word after `!!!` declares the type of the admonition. There are standard admonition types that should produce special styling. Namely (in order of decreasing severity): `danger`, `warning`, `info`/`note`, and `tip`.
You can also use your own admonition types, as long as the type name only contains lowercase Latin characters (a-z). For example, you could have a `terminology` block like this:
```
!!! terminology "julia vs Julia"
Strictly speaking, "Julia" refers to the language,
and "julia" to the standard implementation.
```
However, unless the code rendering the Markdown special-cases that particular admonition type, it will get the default styling.
A custom title for the box can be provided as a string (in double quotes) after the admonition type. If no title text is specified after the admonition type, then the type name will be used as the title (e.g. `"Note"` for the `note` admonition).
Admonitions, like most other toplevel elements, can contain other toplevel elements (e.g. lists, images).
[Markdown Syntax Extensions](#Markdown-Syntax-Extensions)
----------------------------------------------------------
Julia's markdown supports interpolation in a very similar way to basic string literals, with the difference that it will store the object itself in the Markdown tree (as opposed to converting it to a string). When the Markdown content is rendered the usual `show` methods will be called, and these can be overridden as usual. This design allows the Markdown to be extended with arbitrarily complex features (such as references) without cluttering the basic syntax.
In principle, the Markdown parser itself can also be arbitrarily extended by packages, or an entirely custom flavour of Markdown can be used, but this should generally be unnecessary.
julia Serialization Serialization
=============
###
`Serialization.serialize`Function
```
serialize(stream::IO, value)
```
Write an arbitrary value to a stream in an opaque format, such that it can be read back by [`deserialize`](#Serialization.deserialize). The read-back value will be as identical as possible to the original, but note that `Ptr` values are serialized as all-zero bit patterns (`NULL`).
An 8-byte identifying header is written to the stream first. To avoid writing the header, construct a `Serializer` and use it as the first argument to `serialize` instead. See also [`Serialization.writeheader`](#Serialization.writeheader).
The data format can change in minor (1.x) Julia releases, but files written by prior 1.x versions will remain readable. The main exception to this is when the definition of a type in an external package changes. If that occurs, it may be necessary to specify an explicit compatible version of the affected package in your environment. Renaming functions, even private functions, inside packages can also put existing files out of sync. Anonymous functions require special care: because their names are automatically generated, minor code changes can cause them to be renamed. Serializing anonymous functions should be avoided in files intended for long-term storage.
In some cases, the word size (32- or 64-bit) of the reading and writing machines must match. In rarer cases the OS or architecture must also match, for example when using packages that contain platform-dependent code.
```
serialize(filename::AbstractString, value)
```
Open a file and serialize the given value to it.
This method is available as of Julia 1.1.
###
`Serialization.deserialize`Function
```
deserialize(stream)
```
Read a value written by [`serialize`](#Serialization.serialize). `deserialize` assumes the binary data read from `stream` is correct and has been serialized by a compatible implementation of [`serialize`](#Serialization.serialize). `deserialize` is designed for simplicity and performance, and so does not validate the data read. Malformed data can result in process termination. The caller must ensure the integrity and correctness of data read from `stream`.
```
deserialize(filename::AbstractString)
```
Open a file and deserialize its contents.
This method is available as of Julia 1.1.
###
`Serialization.writeheader`Function
```
Serialization.writeheader(s::AbstractSerializer)
```
Write an identifying header to the specified serializer. The header consists of 8 bytes as follows:
| Offset | Description |
| --- | --- |
| 0 | tag byte (0x37) |
| 1-2 | signature bytes "JL" |
| 3 | protocol version |
| 4 | bits 0-1: endianness: 0 = little, 1 = big |
| 4 | bits 2-3: platform: 0 = 32-bit, 1 = 64-bit |
| 5-7 | reserved |
julia Lazy Artifacts Lazy Artifacts
==============
In order for a package to download artifacts lazily, `LazyArtifacts` must be explicitly listed as a dependency of that package.
For further information on artifacts, see [Artifacts](../artifacts/index#Artifacts).
julia Base64 Base64
======
###
`Base64.Base64`Module
```
Base64
```
Functionality for base-64 encoded strings and IO.
###
`Base64.Base64EncodePipe`Type
```
Base64EncodePipe(ostream)
```
Return a new write-only I/O stream, which converts any bytes written to it into base64-encoded ASCII bytes written to `ostream`. Calling [`close`](../../base/io-network/index#Base.close) on the `Base64EncodePipe` stream is necessary to complete the encoding (but does not close `ostream`).
**Examples**
```
julia> io = IOBuffer();
julia> iob64_encode = Base64EncodePipe(io);
julia> write(iob64_encode, "Hello!")
6
julia> close(iob64_encode);
julia> str = String(take!(io))
"SGVsbG8h"
julia> String(base64decode(str))
"Hello!"
```
###
`Base64.base64encode`Function
```
base64encode(writefunc, args...; context=nothing)
base64encode(args...; context=nothing)
```
Given a [`write`](../../base/io-network/index#Base.write)-like function `writefunc`, which takes an I/O stream as its first argument, `base64encode(writefunc, args...)` calls `writefunc` to write `args...` to a base64-encoded string, and returns the string. `base64encode(args...)` is equivalent to `base64encode(write, args...)`: it converts its arguments into bytes using the standard [`write`](../../base/io-network/index#Base.write) functions and returns the base64-encoded string.
The optional keyword argument `context` can be set to `:key=>value` pair or an `IO` or [`IOContext`](../../base/io-network/index#Base.IOContext) object whose attributes are used for the I/O stream passed to `writefunc` or `write`.
See also [`base64decode`](#Base64.base64decode).
###
`Base64.Base64DecodePipe`Type
```
Base64DecodePipe(istream)
```
Return a new read-only I/O stream, which decodes base64-encoded data read from `istream`.
**Examples**
```
julia> io = IOBuffer();
julia> iob64_decode = Base64DecodePipe(io);
julia> write(io, "SGVsbG8h")
8
julia> seekstart(io);
julia> String(read(iob64_decode))
"Hello!"
```
###
`Base64.base64decode`Function
```
base64decode(string)
```
Decode the base64-encoded `string` and returns a `Vector{UInt8}` of the decoded bytes.
See also [`base64encode`](#Base64.base64encode).
**Examples**
```
julia> b = base64decode("SGVsbG8h")
6-element Vector{UInt8}:
0x48
0x65
0x6c
0x6c
0x6f
0x21
julia> String(b)
"Hello!"
```
###
`Base64.stringmime`Function
```
stringmime(mime, x; context=nothing)
```
Returns an `AbstractString` containing the representation of `x` in the requested `mime` type. This is similar to [`repr(mime, x)`](#) except that binary data is base64-encoded as an ASCII string.
The optional keyword argument `context` can be set to `:key=>value` pair or an `IO` or [`IOContext`](../../base/io-network/index#Base.IOContext) object whose attributes are used for the I/O stream passed to [`show`](#).
julia The Julia REPL The Julia REPL
==============
Julia comes with a full-featured interactive command-line REPL (read-eval-print loop) built into the `julia` executable. In addition to allowing quick and easy evaluation of Julia statements, it has a searchable history, tab-completion, many helpful keybindings, and dedicated help and shell modes. The REPL can be started by simply calling `julia` with no arguments or double-clicking on the executable:
```
$ julia
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.8.5 (2023-01-08)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
julia>
```
To exit the interactive session, type `^D` – the control key together with the `d` key on a blank line – or type `exit()` followed by the return or enter key. The REPL greets you with a banner and a `julia>` prompt.
[The different prompt modes](#The-different-prompt-modes)
----------------------------------------------------------
###
[The Julian mode](#The-Julian-mode)
The REPL has five main modes of operation. The first and most common is the Julian prompt. It is the default mode of operation; each new line initially starts with `julia>`. It is here that you can enter Julia expressions. Hitting return or enter after a complete expression has been entered will evaluate the entry and show the result of the last expression.
```
julia> string(1 + 2)
"3"
```
There are a number useful features unique to interactive work. In addition to showing the result, the REPL also binds the result to the variable `ans`. A trailing semicolon on the line can be used as a flag to suppress showing the result.
```
julia> string(3 * 4);
julia> ans
"12"
```
In Julia mode, the REPL supports something called *prompt pasting*. This activates when pasting text that starts with `julia>` into the REPL. In that case, only expressions starting with `julia>` are parsed, others are removed. This makes it possible to paste a chunk of code that has been copied from a REPL session without having to scrub away prompts and outputs. This feature is enabled by default but can be disabled or enabled at will with `REPL.enable_promptpaste(::Bool)`. If it is enabled, you can try it out by pasting the code block above this paragraph straight into the REPL. This feature does not work on the standard Windows command prompt due to its limitation at detecting when a paste occurs.
Objects are printed at the REPL using the [`show`](#) function with a specific [`IOContext`](../../base/io-network/index#Base.IOContext). In particular, the `:limit` attribute is set to `true`. Other attributes can receive in certain `show` methods a default value if it's not already set, like `:compact`. It's possible, as an experimental feature, to specify the attributes used by the REPL via the `Base.active_repl.options.iocontext` dictionary (associating values to attributes). For example:
```
julia> rand(2, 2)
2×2 Array{Float64,2}:
0.8833 0.329197
0.719708 0.59114
julia> show(IOContext(stdout, :compact => false), "text/plain", rand(2, 2))
0.43540323669187075 0.15759787870609387
0.2540832269192739 0.4597637838786053
julia> Base.active_repl.options.iocontext[:compact] = false;
julia> rand(2, 2)
2×2 Array{Float64,2}:
0.2083967319174056 0.13330606013126012
0.6244375177790158 0.9777957560761545
```
In order to define automatically the values of this dictionary at startup time, one can use the [`atreplinit`](#Base.atreplinit) function in the `~/.julia/config/startup.jl` file, for example:
```
atreplinit() do repl
repl.options.iocontext[:compact] = false
end
```
###
[Help mode](#Help-mode)
When the cursor is at the beginning of the line, the prompt can be changed to a help mode by typing `?`. Julia will attempt to print help or documentation for anything entered in help mode:
```
julia> ? # upon typing ?, the prompt changes (in place) to: help?>
help?> string
search: string String Cstring Cwstring RevString randstring bytestring SubString
string(xs...)
Create a string from any values using the print function.
```
Macros, types and variables can also be queried:
```
help?> @time
@time
A macro to execute an expression, printing the time it took to execute, the number of allocations,
and the total number of bytes its execution caused to be allocated, before returning the value of the
expression.
See also @timev, @timed, @elapsed, and @allocated.
help?> Int32
search: Int32 UInt32
Int32 <: Signed
32-bit signed integer type.
```
A string or regex literal searches all docstrings using [`apropos`](../interactiveutils/index#Base.Docs.apropos):
```
help?> "aprop"
REPL.stripmd
Base.Docs.apropos
help?> r"ap..p"
Base.:∘
Base.shell_escape_posixly
Distributed.CachingPool
REPL.stripmd
Base.Docs.apropos
```
Another feature of help mode is the ability to access extended docstrings. You can do this by typing something like `??Print` rather than `?Print` which will display the `# Extended help` section from the source codes documentation.
Help mode can be exited by pressing backspace at the beginning of the line.
###
[Shell mode](#man-shell-mode)
Just as help mode is useful for quick access to documentation, another common task is to use the system shell to execute system commands. Just as `?` entered help mode when at the beginning of the line, a semicolon (`;`) will enter the shell mode. And it can be exited by pressing backspace at the beginning of the line.
```
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> echo hello
hello
```
For Windows users, Julia's shell mode does not expose windows shell commands. Hence, this will fail:
```
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> dir
ERROR: IOError: could not spawn `dir`: no such file or directory (ENOENT)
Stacktrace!
.......
```
However, you can get access to `PowerShell` like this:
```
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\elm>
```
... and to `cmd.exe` like that (see the `dir` command):
```
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> cmd
Microsoft Windows [version 10.0.17763.973]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\elm>dir
Volume in drive C has no label
Volume Serial Number is 1643-0CD7
Directory of C:\Users\elm
29/01/2020 22:15 <DIR> .
29/01/2020 22:15 <DIR> ..
02/02/2020 08:06 <DIR> .atom
```
###
[Pkg mode](#Pkg-mode)
The Package manager mode accepts specialized commands for loading and updating packages. It is entered by pressing the `]` key at the Julian REPL prompt and exited by pressing CTRL-C or pressing the backspace key at the beginning of the line. The prompt for this mode is `pkg>`. It supports its own help-mode, which is entered by pressing `?` at the beginning of the line of the `pkg>` prompt. The Package manager mode is documented in the Pkg manual, available at <https://julialang.github.io/Pkg.jl/v1/>.
###
[Search modes](#Search-modes)
In all of the above modes, the executed lines get saved to a history file, which can be searched. To initiate an incremental search through the previous history, type `^R` – the control key together with the `r` key. The prompt will change to `(reverse-i-search)`':`, and as you type the search query will appear in the quotes. The most recent result that matches the query will dynamically update to the right of the colon as more is typed. To find an older result using the same query, simply type `^R` again.
Just as `^R` is a reverse search, `^S` is a forward search, with the prompt `(i-search)`':`. The two may be used in conjunction with each other to move through the previous or next matching results, respectively.
All executed commands in the Julia REPL are logged into `~/.julia/logs/repl_history.jl` along with a timestamp of when it was executed and the current REPL mode you were in. Search mode queries this log file in order to find the commands which you previously ran. This can be disabled at startup by passing the `--history-file=no` flag to Julia.
[Key bindings](#Key-bindings)
------------------------------
The Julia REPL makes great use of key bindings. Several control-key bindings were already introduced above (`^D` to exit, `^R` and `^S` for searching), but there are many more. In addition to the control-key, there are also meta-key bindings. These vary more by platform, but most terminals default to using alt- or option- held down with a key to send the meta-key (or can be configured to do so), or pressing Esc and then the key.
| Keybinding | Description |
| --- | --- |
| **Program control** | |
| `^D` | Exit (when buffer is empty) |
| `^C` | Interrupt or cancel |
| `^L` | Clear console screen |
| Return/Enter, `^J` | New line, executing if it is complete |
| meta-Return/Enter | Insert new line without executing it |
| `?` or `;` | Enter help or shell mode (when at start of a line) |
| `^R`, `^S` | Incremental history search, described above |
| **Cursor movement** | |
| Right arrow, `^F` | Move right one character |
| Left arrow, `^B` | Move left one character |
| ctrl-Right, `meta-F` | Move right one word |
| ctrl-Left, `meta-B` | Move left one word |
| Home, `^A` | Move to beginning of line |
| End, `^E` | Move to end of line |
| Up arrow, `^P` | Move up one line (or change to the previous history entry that matches the text before the cursor) |
| Down arrow, `^N` | Move down one line (or change to the next history entry that matches the text before the cursor) |
| Shift-Arrow Key | Move cursor according to the direction of the Arrow key, while activating the region ("shift selection") |
| Page-up, `meta-P` | Change to the previous history entry |
| Page-down, `meta-N` | Change to the next history entry |
| `meta-<` | Change to the first history entry (of the current session if it is before the current position in history) |
| `meta->` | Change to the last history entry |
| `^-Space` | Set the "mark" in the editing region (and de-activate the region if it's active) |
| `^-Space ^-Space` | Set the "mark" in the editing region and make the region "active", i.e. highlighted |
| `^G` | De-activate the region (i.e. make it not highlighted) |
| `^X^X` | Exchange the current position with the mark |
| **Editing** | |
| Backspace, `^H` | Delete the previous character, or the whole region when it's active |
| Delete, `^D` | Forward delete one character (when buffer has text) |
| meta-Backspace | Delete the previous word |
| `meta-d` | Forward delete the next word |
| `^W` | Delete previous text up to the nearest whitespace |
| `meta-w` | Copy the current region in the kill ring |
| `meta-W` | "Kill" the current region, placing the text in the kill ring |
| `^K` | "Kill" to end of line, placing the text in the kill ring |
| `^Y` | "Yank" insert the text from the kill ring |
| `meta-y` | Replace a previously yanked text with an older entry from the kill ring |
| `^T` | Transpose the characters about the cursor |
| `meta-Up arrow` | Transpose current line with line above |
| `meta-Down arrow` | Transpose current line with line below |
| `meta-u` | Change the next word to uppercase |
| `meta-c` | Change the next word to titlecase |
| `meta-l` | Change the next word to lowercase |
| `^/`, `^_` | Undo previous editing action |
| `^Q` | Write a number in REPL and press `^Q` to open editor at corresponding stackframe or method |
| `meta-Left Arrow` | indent the current line on the left |
| `meta-Right Arrow` | indent the current line on the right |
| `meta-.` | insert last word from previous history entry |
###
[Customizing keybindings](#Customizing-keybindings)
Julia's REPL keybindings may be fully customized to a user's preferences by passing a dictionary to `REPL.setup_interface`. The keys of this dictionary may be characters or strings. The key `'*'` refers to the default action. Control plus character `x` bindings are indicated with `"^x"`. Meta plus `x` can be written `"\\M-x"` or `"\ex"`, and Control plus `x` can be written `"\\C-x"` or `"^x"`. The values of the custom keymap must be `nothing` (indicating that the input should be ignored) or functions that accept the signature `(PromptState, AbstractREPL, Char)`. The `REPL.setup_interface` function must be called before the REPL is initialized, by registering the operation with [`atreplinit`](#Base.atreplinit) . For example, to bind the up and down arrow keys to move through history without prefix search, one could put the following code in `~/.julia/config/startup.jl`:
```
import REPL
import REPL.LineEdit
const mykeys = Dict{Any,Any}(
# Up Arrow
"\e[A" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)),
# Down Arrow
"\e[B" => (s,o...)->(LineEdit.edit_move_down(s) || LineEdit.history_next(s, LineEdit.mode(s).hist))
)
function customize_keys(repl)
repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
end
atreplinit(customize_keys)
```
Users should refer to `LineEdit.jl` to discover the available actions on key input.
[Tab completion](#Tab-completion)
----------------------------------
In both the Julian and help modes of the REPL, one can enter the first few characters of a function or type and then press the tab key to get a list all matches:
```
julia> x[TAB]
julia> xor
```
In some cases it only completes part of the name, up to the next ambiguity:
```
julia> mapf[TAB]
julia> mapfold
```
If you hit tab again, then you get the list of things that might complete this:
```
julia> mapfold[TAB]
mapfoldl mapfoldr
```
Like other components of the REPL, the search is case-sensitive:
```
julia> stri[TAB]
stride strides string strip
julia> Stri[TAB]
StridedArray StridedMatrix StridedVecOrMat StridedVector String
```
The tab key can also be used to substitute LaTeX math symbols with their Unicode equivalents, and get a list of LaTeX matches as well:
```
julia> \pi[TAB]
julia> π
π = 3.1415926535897...
julia> e\_1[TAB] = [1,0]
julia> e₁ = [1,0]
2-element Array{Int64,1}:
1
0
julia> e\^1[TAB] = [1 0]
julia> e¹ = [1 0]
1×2 Array{Int64,2}:
1 0
julia> \sqrt[TAB]2 # √ is equivalent to the sqrt function
julia> √2
1.4142135623730951
julia> \hbar[TAB](h) = h / 2\pi[TAB]
julia> ħ(h) = h / 2π
ħ (generic function with 1 method)
julia> \h[TAB]
\hat \hermitconjmatrix \hkswarow \hrectangle
\hatapprox \hexagon \hookleftarrow \hrectangleblack
\hbar \hexagonblack \hookrightarrow \hslash
\heartsuit \hksearow \house \hspace
julia> α="\alpha[TAB]" # LaTeX completion also works in strings
julia> α="α"
```
A full list of tab-completions can be found in the [Unicode Input](../../manual/unicode-input/index#Unicode-Input) section of the manual.
Completion of paths works for strings and julia's shell mode:
```
julia> path="/[TAB]"
.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
shell> /[TAB]
.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
```
Dictionary keys can also be tab completed:
```
julia> foo = Dict("qwer1"=>1, "qwer2"=>2, "asdf"=>3)
Dict{String,Int64} with 3 entries:
"qwer2" => 2
"asdf" => 3
"qwer1" => 1
julia> foo["q[TAB]
"qwer1" "qwer2"
julia> foo["qwer
```
Tab completion can also help completing fields:
```
julia> x = 3 + 4im;
julia> julia> x.[TAB][TAB]
im re
julia> import UUIDs
julia> UUIDs.uuid[TAB][TAB]
uuid1 uuid4 uuid5 uuid_version
```
Fields for output from functions can also be completed:
```
julia> split("","")[1].[TAB]
lastindex offset string
```
The completion of fields for output from functions uses type inference, and it can only suggest fields if the function is type stable.
Tab completion can help with investigation of the available methods matching the input arguments:
```
julia> max([TAB] # All methods are displayed, not shown here due to size of the list
julia> max([1, 2], [TAB] # All methods where `Vector{Int}` matches as first argument
max(x, y) in Base at operators.jl:215
max(a, b, c, xs...) in Base at operators.jl:281
julia> max([1, 2], max(1, 2), [TAB] # All methods matching the arguments.
max(x, y) in Base at operators.jl:215
max(a, b, c, xs...) in Base at operators.jl:281
```
Keywords are also displayed in the suggested methods after `;`, see below line where `limit` and `keepempty` are keyword arguments:
```
julia> split("1 1 1", [TAB]
split(str::AbstractString; limit, keepempty) in Base at strings/util.jl:302
split(str::T, splitter; limit, keepempty) where T<:AbstractString in Base at strings/util.jl:277
```
The completion of the methods uses type inference and can therefore see if the arguments match even if the arguments are output from functions. The function needs to be type stable for the completion to be able to remove non-matching methods.
If you wonder which methods can be used with particular argument types, use `?` as the function name. This shows an example of looking for functions in InteractiveUtils that accept a single string:
```
julia> InteractiveUtils.?("somefile")[TAB]
edit(path::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:197
less(file::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:266
```
This listed methods in the `InteractiveUtils` module that can be called on a string. By default, this excludes methods where all arguments are typed as `Any`, but you can see those too by holding down SHIFT-TAB instead of TAB:
```
julia> InteractiveUtils.?("somefile")[SHIFT-TAB]
apropos(string) in REPL at REPL/src/docview.jl:796
clipboard(x) in InteractiveUtils at InteractiveUtils/src/clipboard.jl:64
code_llvm(f) in InteractiveUtils at InteractiveUtils/src/codeview.jl:221
code_native(f) in InteractiveUtils at InteractiveUtils/src/codeview.jl:243
edit(path::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:197
edit(f) in InteractiveUtils at InteractiveUtils/src/editless.jl:225
eval(x) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:3
include(x) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:3
less(file::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:266
less(f) in InteractiveUtils at InteractiveUtils/src/editless.jl:274
report_bug(kind) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:391
separate_kwargs(args...; kwargs...) in InteractiveUtils at InteractiveUtils/src/macros.jl:7
```
You can also use `?("somefile")[TAB]` and look across all modules, but the method lists can be long.
By omitting the closing parenthesis, you can include functions that might require additional arguments:
```
julia> using Mmap
help?> Mmap.?("file",[TAB]
Mmap.Anonymous(name::String, readonly::Bool, create::Bool) in Mmap at Mmap/src/Mmap.jl:16
mmap(file::AbstractString) in Mmap at Mmap/src/Mmap.jl:245
mmap(file::AbstractString, ::Type{T}) where T<:Array in Mmap at Mmap/src/Mmap.jl:245
mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}) where {T<:Array, N} in Mmap at Mmap/src/Mmap.jl:245
mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}, offset::Integer; grow, shared) where {T<:Array, N} in Mmap at Mmap/src/Mmap.jl:245
mmap(file::AbstractString, ::Type{T}, len::Integer) where T<:Array in Mmap at Mmap/src/Mmap.jl:251
mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer; grow, shared) where T<:Array in Mmap at Mmap/src/Mmap.jl:251
mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}) where {T<:BitArray, N} in Mmap at Mmap/src/Mmap.jl:316
mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}, offset::Integer; grow, shared) where {T<:BitArray, N} in Mmap at Mmap/src/Mmap.jl:316
mmap(file::AbstractString, ::Type{T}, len::Integer) where T<:BitArray in Mmap at Mmap/src/Mmap.jl:322
mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer; grow, shared) where T<:BitArray in Mmap at Mmap/src/Mmap.jl:322
```
[Customizing Colors](#Customizing-Colors)
------------------------------------------
The colors used by Julia and the REPL can be customized, as well. To change the color of the Julia prompt you can add something like the following to your `~/.julia/config/startup.jl` file, which is to be placed inside your home directory:
```
function customize_colors(repl)
repl.prompt_color = Base.text_colors[:cyan]
end
atreplinit(customize_colors)
```
The available color keys can be seen by typing `Base.text_colors` in the help mode of the REPL. In addition, the integers 0 to 255 can be used as color keys for terminals with 256 color support.
You can also change the colors for the help and shell prompts and input and answer text by setting the appropriate field of `repl` in the `customize_colors` function above (respectively, `help_color`, `shell_color`, `input_color`, and `answer_color`). For the latter two, be sure that the `envcolors` field is also set to false.
It is also possible to apply boldface formatting by using `Base.text_colors[:bold]` as a color. For instance, to print answers in boldface font, one can use the following as a `~/.julia/config/startup.jl`:
```
function customize_colors(repl)
repl.envcolors = false
repl.answer_color = Base.text_colors[:bold]
end
atreplinit(customize_colors)
```
You can also customize the color used to render warning and informational messages by setting the appropriate environment variables. For instance, to render error, warning, and informational messages respectively in magenta, yellow, and cyan you can add the following to your `~/.julia/config/startup.jl` file:
```
ENV["JULIA_ERROR_COLOR"] = :magenta
ENV["JULIA_WARN_COLOR"] = :yellow
ENV["JULIA_INFO_COLOR"] = :cyan
```
[TerminalMenus](#TerminalMenus)
--------------------------------
TerminalMenus is a submodule of the Julia REPL and enables small, low-profile interactive menus in the terminal.
###
[Examples](#Examples)
```
import REPL
using REPL.TerminalMenus
options = ["apple", "orange", "grape", "strawberry",
"blueberry", "peach", "lemon", "lime"]
```
####
[RadioMenu](#RadioMenu)
The RadioMenu allows the user to select one option from the list. The `request` function displays the interactive menu and returns the index of the selected choice. If a user presses 'q' or `ctrl-c`, `request` will return a `-1`.
```
# `pagesize` is the number of items to be displayed at a time.
# The UI will scroll if the number of options is greater
# than the `pagesize`
menu = RadioMenu(options, pagesize=4)
# `request` displays the menu and returns the index after the
# user has selected a choice
choice = request("Choose your favorite fruit:", menu)
if choice != -1
println("Your favorite fruit is ", options[choice], "!")
else
println("Menu canceled.")
end
```
Output:
```
Choose your favorite fruit:
^ grape
strawberry
> blueberry
v peach
Your favorite fruit is blueberry!
```
####
[MultiSelectMenu](#MultiSelectMenu)
The MultiSelectMenu allows users to select many choices from a list.
```
# here we use the default `pagesize` 10
menu = MultiSelectMenu(options)
# `request` returns a `Set` of selected indices
# if the menu us canceled (ctrl-c or q), return an empty set
choices = request("Select the fruits you like:", menu)
if length(choices) > 0
println("You like the following fruits:")
for i in choices
println(" - ", options[i])
end
else
println("Menu canceled.")
end
```
Output:
```
Select the fruits you like:
[press: d=done, a=all, n=none]
[ ] apple
> [X] orange
[X] grape
[ ] strawberry
[ ] blueberry
[X] peach
[ ] lemon
[ ] lime
You like the following fruits:
- orange
- grape
- peach
```
###
[Customization / Configuration](#Customization-/-Configuration)
####
[ConfiguredMenu subtypes](#ConfiguredMenu-subtypes)
Starting with Julia 1.6, the recommended way to configure menus is via the constructor. For instance, the default multiple-selection menu
```
julia> menu = MultiSelectMenu(options, pagesize=5);
julia> request(menu) # ASCII is used by default
[press: d=done, a=all, n=none]
[ ] apple
[X] orange
[ ] grape
> [X] strawberry
v [ ] blueberry
```
can instead be rendered with Unicode selection and navigation characters with
```
julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode);
julia> request(menu)
[press: d=done, a=all, n=none]
⬚ apple
✓ orange
⬚ grape
→ ✓ strawberry
↓ ⬚ blueberry
```
More fine-grained configuration is also possible:
```
julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode, checked="YEP!", unchecked="NOPE", cursor='⧐');
julia> request(menu)
julia> request(menu)
[press: d=done, a=all, n=none]
NOPE apple
YEP! orange
NOPE grape
⧐ YEP! strawberry
↓ NOPE blueberry
```
Aside from the overall `charset` option, for `RadioMenu` the configurable options are:
* `cursor::Char='>'|'→'`: character to use for cursor
* `up_arrow::Char='^'|'↑'`: character to use for up arrow
* `down_arrow::Char='v'|'↓'`: character to use for down arrow
* `updown_arrow::Char='I'|'↕'`: character to use for up/down arrow in one-line page
* `scroll_wrap::Bool=false`: optionally wrap-around at the beginning/end of a menu
* `ctrl_c_interrupt::Bool=true`: If `false`, return empty on ^C, if `true` throw InterruptException() on ^C
`MultiSelectMenu` adds:
* `checked::String="[X]"|"✓"`: string to use for checked
* `unchecked::String="[ ]"|"⬚")`: string to use for unchecked
You can create new menu types of your own. Types that are derived from `TerminalMenus.ConfiguredMenu` configure the menu options at construction time.
####
[Legacy interface](#Legacy-interface)
Prior to Julia 1.6, and still supported throughout Julia 1.x, one can also configure menus by calling `TerminalMenus.config()`.
[References](#References)
--------------------------
###
[REPL](#REPL)
###
`Base.atreplinit`Function
```
atreplinit(f)
```
Register a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The argument of `f` is the REPL object. This function should be called from within the `.julia/config/startup.jl` initialization file.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/client.jl#L355-L362)###
[TerminalMenus](#TerminalMenus-2)
####
[Configuration](#Configuration)
###
`REPL.TerminalMenus.Config`Type
```
Config(; scroll_wrap=false, ctrl_c_interrupt=true, charset=:ascii, cursor::Char, up_arrow::Char, down_arrow::Char)
```
Configure behavior for selection menus via keyword arguments:
* `scroll_wrap`, if `true`, causes the menu to wrap around when scrolling above the first or below the last entry
* `ctrl_c_interrupt`, if `true`, throws an `InterruptException` if the user hits Ctrl-C during menu selection. If `false`, [`TerminalMenus.request`](#REPL.TerminalMenus.request) will return the default result from [`TerminalMenus.selected`](#REPL.TerminalMenus.selected).
* `charset` affects the default values for `cursor`, `up_arrow`, and `down_arrow`, and can be `:ascii` or `:unicode`
* `cursor` is the character printed to indicate the option that will be chosen by hitting "Enter." Defaults are '>' or '→', depending on `charset`.
* `up_arrow` is the character printed when the display does not include the first entry. Defaults are '^' or '↑', depending on `charset`.
* `down_arrow` is the character printed when the display does not include the last entry. Defaults are 'v' or '↓', depending on `charset`.
Subtypes of `ConfiguredMenu` will print `cursor`, `up_arrow`, and `down_arrow` automatically as needed, your `writeline` method should not print them.
`Config` is available as of Julia 1.6. On older releases use the global `CONFIG`.
###
`REPL.TerminalMenus.MultiSelectConfig`Type
```
MultiSelectConfig(; charset=:ascii, checked::String, unchecked::String, kwargs...)
```
Configure behavior for a multiple-selection menu via keyword arguments:
* `checked` is the string to print when an option has been selected. Defaults are "[X]" or "✓", depending on `charset`.
* `unchecked` is the string to print when an option has not been selected. Defaults are "[ ]" or "⬚", depending on `charset`.
All other keyword arguments are as described for [`TerminalMenus.Config`](#REPL.TerminalMenus.Config). `checked` and `unchecked` are not printed automatically, and should be printed by your `writeline` method.
`MultiSelectConfig` is available as of Julia 1.6. On older releases use the global `CONFIG`.
###
`REPL.TerminalMenus.config`Function
```
config( <see arguments> )
```
Keyword-only function to configure global menu parameters
**Arguments**
* `charset::Symbol=:na`: ui characters to use (`:ascii` or `:unicode`); overridden by other arguments
* `cursor::Char='>'|'→'`: character to use for cursor
* `up_arrow::Char='^'|'↑'`: character to use for up arrow
* `down_arrow::Char='v'|'↓'`: character to use for down arrow
* `checked::String="[X]"|"✓"`: string to use for checked
* `unchecked::String="[ ]"|"⬚")`: string to use for unchecked
* `scroll::Symbol=:nowrap`: If `:wrap` wrap cursor around top and bottom, if :`nowrap` do not wrap cursor
* `supress_output::Bool=false`: Ignored legacy argument, pass `suppress_output` as a keyword argument to `request` instead.
* `ctrl_c_interrupt::Bool=true`: If `false`, return empty on ^C, if `true` throw InterruptException() on ^C
As of Julia 1.6, `config` is deprecated. Use `Config` or `MultiSelectConfig` instead.
####
[User interaction](#User-interaction)
###
`REPL.TerminalMenus.request`Function
```
request(m::AbstractMenu; cursor=1)
```
Display the menu and enter interactive mode. `cursor` indicates the item number used for the initial cursor position. `cursor` can be either an `Int` or a `RefValue{Int}`. The latter is useful for observation and control of the cursor position from the outside.
Returns `selected(m)`.
The `cursor` argument requires Julia 1.6 or later.
```
request([term,] msg::AbstractString, m::AbstractMenu)
```
Shorthand for `println(msg); request(m)`.
####
[AbstractMenu extension interface](#AbstractMenu-extension-interface)
Any subtype of `AbstractMenu` must be mutable, and must contain the fields `pagesize::Int` and `pageoffset::Int`. Any subtype must also implement the following functions:
###
`REPL.TerminalMenus.pick`Function
```
pick(m::AbstractMenu, cursor::Int)
```
Defines what happens when a user presses the Enter key while the menu is open. If `true` is returned, `request()` will exit. `cursor` indexes the position of the selection.
###
`REPL.TerminalMenus.cancel`Function
```
cancel(m::AbstractMenu)
```
Define what happens when a user cancels ('q' or ctrl-c) a menu. `request()` will always exit after calling this function.
###
`REPL.TerminalMenus.writeline`Function
```
writeline(buf::IO, m::AbstractMenu, idx::Int, iscursor::Bool)
```
Write the option at index `idx` to `buf`. `iscursor`, if `true`, indicates that this item is at the current cursor position (the one that will be selected by hitting "Enter").
If `m` is a `ConfiguredMenu`, `TerminalMenus` will print the cursor indicator. Otherwise the callee is expected to handle such printing.
`writeline` requires Julia 1.6 or higher.
On older versions of Julia, this was `writeLine(buf::IO, m::AbstractMenu, idx, iscursor::Bool)` and `m` is assumed to be unconfigured. The selection and cursor indicators can be obtained from `TerminalMenus.CONFIG`.
This older function is supported on all Julia 1.x versions but will be dropped in Julia 2.0.
It must also implement either `options` or `numoptions`:
###
`REPL.TerminalMenus.options`Function
```
options(m::AbstractMenu)
```
Return a list of strings to be displayed as options in the current page.
Alternatively, implement `numoptions`, in which case `options` is not needed.
###
`REPL.TerminalMenus.numoptions`Function
```
numoptions(m::AbstractMenu) -> Int
```
Return the number of options in menu `m`. Defaults to `length(options(m))`.
This function requires Julia 1.6 or later.
If the subtype does not have a field named `selected`, it must also implement
###
`REPL.TerminalMenus.selected`Function
```
selected(m::AbstractMenu)
```
Return information about the user-selected option. By default it returns `m.selected`.
The following are optional but can allow additional customization:
###
`REPL.TerminalMenus.header`Function
```
header(m::AbstractMenu) -> String
```
Returns a header string to be printed above the menu. Defaults to "".
###
`REPL.TerminalMenus.keypress`Function
```
keypress(m::AbstractMenu, i::UInt32) -> Bool
```
Handle any non-standard keypress event. If `true` is returned, [`TerminalMenus.request`](#REPL.TerminalMenus.request) will exit. Defaults to `false`.
| programming_docs |
julia Printf Printf
======
###
`Printf.@printf`Macro
```
@printf([io::IO], "%Fmt", args...)
```
Print `args` using C `printf` style format specification string. Optionally, an `IO` may be passed as the first argument to redirect output.
**Examples**
```
julia> @printf "Hello %s" "world"
Hello world
julia> @printf "Scientific notation %e" 1.234
Scientific notation 1.234000e+00
julia> @printf "Scientific notation three digits %.3e" 1.23456
Scientific notation three digits 1.235e+00
julia> @printf "Decimal two digits %.2f" 1.23456
Decimal two digits 1.23
julia> @printf "Padded to length 5 %5i" 123
Padded to length 5 123
julia> @printf "Padded with zeros to length 6 %06i" 123
Padded with zeros to length 6 000123
julia> @printf "Use shorter of decimal or scientific %g %g" 1.23 12300000.0
Use shorter of decimal or scientific 1.23 1.23e+07
```
For a systematic specification of the format, see [here](https://www.cplusplus.com/reference/cstdio/printf/). See also [`@sprintf`](#Printf.@sprintf).
**Caveats**
`Inf` and `NaN` are printed consistently as `Inf` and `NaN` for flags `%a`, `%A`, `%e`, `%E`, `%f`, `%F`, `%g`, and `%G`. Furthermore, if a floating point number is equally close to the numeric values of two possible output strings, the output string further away from zero is chosen.
**Examples**
```
julia> @printf("%f %F %f %F", Inf, Inf, NaN, NaN)
Inf Inf NaN NaN
julia> @printf "%.0f %.1f %f" 0.5 0.025 -0.0078125
0 0.0 -0.007812
```
Starting in Julia 1.8, `%s` (string) and `%c` (character) widths are computed using [`textwidth`](../../base/strings/index#Base.Unicode.textwidth), which e.g. ignores zero-width characters (such as combining characters for diacritical marks) and treats certain "wide" characters (e.g. emoji) as width `2`.
###
`Printf.@sprintf`Macro
```
@sprintf("%Fmt", args...)
```
Return [`@printf`](#Printf.@printf) formatted output as string.
**Examples**
```
julia> @sprintf "this is a %s %15.1f" "test" 34.567
"this is a test 34.6"
```
julia LibCURL LibCURL
=======
This is a simple Julia wrapper around http://curl.haxx.se/libcurl/ generated using [Clang.jl](https://github.com/ihnorton/Clang.jl). Please see the [libcurl API documentation](https://curl.haxx.se/libcurl/c/) for help on how to use this package.
julia Interactive Utilities Interactive Utilities
=====================
This module is intended for interactive work. It is loaded automaticaly in [interactive mode](../../manual/command-line-options/index#command-line-options).
###
`Base.Docs.apropos`Function
```
apropos([io::IO=stdout], pattern::Union{AbstractString,Regex})
```
Search available docstrings for entries containing `pattern`.
When `pattern` is a string, case is ignored. Results are printed to `io`.
`apropos` can be called from the help mode in the REPL by wrapping the query in double quotes:
```
help?> "pattern"
```
###
`InteractiveUtils.varinfo`Function
```
varinfo(m::Module=Main, pattern::Regex=r""; all::Bool = false, imported::Bool = false, sortby::Symbol = :name, minsize::Int = 0)
```
Return a markdown table giving information about exported global variables in a module, optionally restricted to those matching `pattern`.
The memory consumption estimate is an approximate lower bound on the size of the internal structure of the object.
* `all` : also list non-exported objects defined in the module, deprecated objects, and compiler-generated objects.
* `imported` : also list objects explicitly imported from other modules.
* `recursive` : recursively include objects in sub-modules, observing the same settings in each.
* `sortby` : the column to sort results by. Options are `:name` (default), `:size`, and `:summary`.
* `minsize` : only includes objects with size at least `minsize` bytes. Defaults to `0`.
###
`InteractiveUtils.versioninfo`Function
```
versioninfo(io::IO=stdout; verbose::Bool=false)
```
Print information about the version of Julia in use. The output is controlled with boolean keyword arguments:
* `verbose`: print all additional information
The output of this function may contain sensitive information. Before sharing the output, please review the output and remove any data that should not be shared publicly.
See also: [`VERSION`](../../base/constants/index#Base.VERSION).
###
`InteractiveUtils.methodswith`Function
```
methodswith(typ[, module or function]; supertypes::Bool=false])
```
Return an array of methods with an argument of type `typ`.
The optional second argument restricts the search to a particular module or function (the default is all top-level modules).
If keyword `supertypes` is `true`, also return arguments with a parent type of `typ`, excluding type `Any`.
###
`InteractiveUtils.subtypes`Function
```
subtypes(T::DataType)
```
Return a list of immediate subtypes of DataType `T`. Note that all currently loaded subtypes are included, including those not visible in the current module.
See also [`supertype`](../../base/base/index#Base.supertype), [`supertypes`](#InteractiveUtils.supertypes), [`methodswith`](#InteractiveUtils.methodswith).
**Examples**
```
julia> subtypes(Integer)
3-element Vector{Any}:
Bool
Signed
Unsigned
```
###
`InteractiveUtils.supertypes`Function
```
supertypes(T::Type)
```
Return a tuple `(T, ..., Any)` of `T` and all its supertypes, as determined by successive calls to the [`supertype`](../../base/base/index#Base.supertype) function, listed in order of `<:` and terminated by `Any`.
See also [`subtypes`](#InteractiveUtils.subtypes).
**Examples**
```
julia> supertypes(Int)
(Int64, Signed, Integer, Real, Number, Any)
```
###
`InteractiveUtils.edit`Method
```
edit(path::AbstractString, line::Integer=0)
```
Edit a file or directory optionally providing a line number to edit the file at. Return to the `julia` prompt when you quit the editor. The editor can be changed by setting `JULIA_EDITOR`, `VISUAL` or `EDITOR` as an environment variable.
See also [`define_editor`](#InteractiveUtils.define_editor).
###
`InteractiveUtils.edit`Method
```
edit(function, [types])
edit(module)
```
Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. For modules, open the main source file. The module needs to be loaded with `using` or `import` first.
`edit` on modules requires at least Julia 1.1.
To ensure that the file can be opened at the given line, you may need to call `define_editor` first.
###
`InteractiveUtils.@edit`Macro
```
@edit
```
Evaluates the arguments to the function or macro call, determines their types, and calls the `edit` function on the resulting expression.
See also: [`@less`](#InteractiveUtils.@less), [`@which`](#InteractiveUtils.@which).
###
`InteractiveUtils.define_editor`Function
```
define_editor(fn, pattern; wait=false)
```
Define a new editor matching `pattern` that can be used to open a file (possibly at a given line number) using `fn`.
The `fn` argument is a function that determines how to open a file with the given editor. It should take three arguments, as follows:
* `cmd` - a base command object for the editor
* `path` - the path to the source file to open
* `line` - the line number to open the editor at
Editors which cannot open to a specific line with a command may ignore the `line` argument. The `fn` callback must return either an appropriate `Cmd` object to open a file or `nothing` to indicate that they cannot edit this file. Use `nothing` to indicate that this editor is not appropriate for the current environment and another editor should be attempted. It is possible to add more general editing hooks that need not spawn external commands by pushing a callback directly to the vector `EDITOR_CALLBACKS`.
The `pattern` argument is a string, regular expression, or an array of strings and regular expressions. For the `fn` to be called, one of the patterns must match the value of `EDITOR`, `VISUAL` or `JULIA_EDITOR`. For strings, the string must equal the [`basename`](../../base/file/index#Base.Filesystem.basename) of the first word of the editor command, with its extension, if any, removed. E.g. "vi" doesn't match "vim -g" but matches "/usr/bin/vi -m"; it also matches `vi.exe`. If `pattern` is a regex it is matched against all of the editor command as a shell-escaped string. An array pattern matches if any of its items match. If multiple editors match, the one added most recently is used.
By default julia does not wait for the editor to close, running it in the background. However, if the editor is terminal based, you will probably want to set `wait=true` and julia will wait for the editor to close before resuming.
If one of the editor environment variables is set, but no editor entry matches it, the default editor entry is invoked:
```
(cmd, path, line) -> `$cmd $path`
```
Note that many editors are already defined. All of the following commands should already work:
* emacs
* emacsclient
* vim
* nvim
* nano
* micro
* kak
* textmate
* mate
* kate
* subl
* atom
* notepad++
* Visual Studio Code
* open
* pycharm
* bbedit
**Example:**
The following defines the usage of terminal-based `emacs`:
```
define_editor(
r"\bemacs\b.*\s(-nw|--no-window-system)\b", wait=true) do cmd, path, line
`$cmd +$line $path`
end
```
`define_editor` was introduced in Julia 1.4.
###
`InteractiveUtils.less`Method
```
less(file::AbstractString, [line::Integer])
```
Show a file using the default pager, optionally providing a starting line number. Returns to the `julia` prompt when you quit the pager.
###
`InteractiveUtils.less`Method
```
less(function, [types])
```
Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.
###
`InteractiveUtils.@less`Macro
```
@less
```
Evaluates the arguments to the function or macro call, determines their types, and calls the `less` function on the resulting expression.
See also: [`@edit`](#InteractiveUtils.@edit), [`@which`](#InteractiveUtils.@which), [`@code_lowered`](#InteractiveUtils.@code_lowered).
###
`InteractiveUtils.@which`Macro
```
@which
```
Applied to a function or macro call, it evaluates the arguments to the specified call, and returns the `Method` object for the method that would be called for those arguments. Applied to a variable, it returns the module in which the variable was bound. It calls out to the [`which`](#) function.
See also: [`@less`](#InteractiveUtils.@less), [`@edit`](#InteractiveUtils.@edit).
###
`InteractiveUtils.@functionloc`Macro
```
@functionloc
```
Applied to a function or macro call, it evaluates the arguments to the specified call, and returns a tuple `(filename,line)` giving the location for the method that would be called for those arguments. It calls out to the `functionloc` function.
###
`InteractiveUtils.@code_lowered`Macro
```
@code_lowered
```
Evaluates the arguments to the function or macro call, determines their types, and calls [`code_lowered`](../../base/base/index#Base.code_lowered) on the resulting expression.
###
`InteractiveUtils.@code_typed`Macro
```
@code_typed
```
Evaluates the arguments to the function or macro call, determines their types, and calls [`code_typed`](../../base/base/index#Base.code_typed) on the resulting expression. Use the optional argument `optimize` with
```
@code_typed optimize=true foo(x)
```
to control whether additional optimizations, such as inlining, are also applied.
###
`InteractiveUtils.code_warntype`Function
```
code_warntype([io::IO], f, types; debuginfo=:default)
```
Prints lowered and type-inferred ASTs for the methods matching the given generic function and type signature to `io` which defaults to `stdout`. The ASTs are annotated in such a way as to cause "non-leaf" types to be emphasized (if color is available, displayed in red). This serves as a warning of potential type instability. Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. In particular, unions containing either [`missing`](../../base/base/index#Base.missing) or [`nothing`](../../base/constants/index#Core.nothing) are displayed in yellow, since these are often intentional.
Keyword argument `debuginfo` may be one of `:source` or `:none` (default), to specify the verbosity of code comments.
See [`@code_warntype`](../../manual/performance-tips/index#man-code-warntype) for more information.
###
`InteractiveUtils.@code_warntype`Macro
```
@code_warntype
```
Evaluates the arguments to the function or macro call, determines their types, and calls [`code_warntype`](#InteractiveUtils.code_warntype) on the resulting expression.
###
`InteractiveUtils.code_llvm`Function
```
code_llvm([io=stdout,], f, types; raw=false, dump_module=false, optimize=true, debuginfo=:default)
```
Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to `io`.
If the `optimize` keyword is unset, the code will be shown before LLVM optimizations. All metadata and dbg.\* calls are removed from the printed bitcode. For the full IR, set the `raw` keyword to true. To dump the entire module that encapsulates the function (with declarations), set the `dump_module` keyword to true. Keyword argument `debuginfo` may be one of source (default) or none, to specify the verbosity of code comments.
###
`InteractiveUtils.@code_llvm`Macro
```
@code_llvm
```
Evaluates the arguments to the function or macro call, determines their types, and calls [`code_llvm`](#InteractiveUtils.code_llvm) on the resulting expression. Set the optional keyword arguments `raw`, `dump_module`, `debuginfo`, `optimize` by putting them and their value before the function call, like this:
```
@code_llvm raw=true dump_module=true debuginfo=:default f(x)
@code_llvm optimize=false f(x)
```
`optimize` controls whether additional optimizations, such as inlining, are also applied. `raw` makes all metadata and dbg.\* calls visible. `debuginfo` may be one of `:source` (default) or `:none`, to specify the verbosity of code comments. `dump_module` prints the entire module that encapsulates the function.
###
`InteractiveUtils.code_native`Function
```
code_native([io=stdout,], f, types; syntax=:att, debuginfo=:default, binary=false, dump_module=true)
```
Prints the native assembly instructions generated for running the method matching the given generic function and type signature to `io`.
* Set assembly syntax by setting `syntax` to `:att` (default) for AT&T syntax or `:intel` for Intel syntax.
* Specify verbosity of code comments by setting `debuginfo` to `:source` (default) or `:none`.
* If `binary` is `true`, also print the binary machine code for each instruction precedented by an abbreviated address.
* If `dump_module` is `false`, do not print metadata such as rodata or directives.
See also: [`@code_native`](#InteractiveUtils.@code_native), [`code_llvm`](#InteractiveUtils.code_llvm), [`code_typed`](../../base/base/index#Base.code_typed) and [`code_lowered`](../../base/base/index#Base.code_lowered)
###
`InteractiveUtils.@code_native`Macro
```
@code_native
```
Evaluates the arguments to the function or macro call, determines their types, and calls [`code_native`](#InteractiveUtils.code_native) on the resulting expression.
Set any of the optional keyword arguments `syntax`, `debuginfo`, `binary` or `dump_module` by putting it before the function call, like this:
```
@code_native syntax=:intel debuginfo=:default binary=true dump_module=false f(x)
```
* Set assembly syntax by setting `syntax` to `:att` (default) for AT&T syntax or `:intel` for Intel syntax.
* Specify verbosity of code comments by setting `debuginfo` to `:source` (default) or `:none`.
* If `binary` is `true`, also print the binary machine code for each instruction precedented by an abbreviated address.
* If `dump_module` is `false`, do not print metadata such as rodata or directives.
See also: [`code_native`](#InteractiveUtils.code_native), [`@code_llvm`](#InteractiveUtils.@code_llvm), [`@code_typed`](#InteractiveUtils.@code_typed) and [`@code_lowered`](#InteractiveUtils.@code_lowered)
###
`InteractiveUtils.@time_imports`Macro
```
@time_imports
```
A macro to execute an expression and produce a report of any time spent importing packages and their dependencies. Any compilation time will be reported as a percentage, and how much of which was recompilation, if any.
During the load process a package sequentially imports all of its dependencies, not just its direct dependencies.
```
julia> @time_imports using CSV
50.7 ms Parsers 17.52% compilation time
0.2 ms DataValueInterfaces
1.6 ms DataAPI
0.1 ms IteratorInterfaceExtensions
0.1 ms TableTraits
17.5 ms Tables
26.8 ms PooledArrays
193.7 ms SentinelArrays 75.12% compilation time
8.6 ms InlineStrings
20.3 ms WeakRefStrings
2.0 ms TranscodingStreams
1.4 ms Zlib_jll
1.8 ms CodecZlib
0.8 ms Compat
13.1 ms FilePathsBase 28.39% compilation time
1681.2 ms CSV 92.40% compilation time
```
This macro requires at least Julia 1.8
###
`InteractiveUtils.clipboard`Function
```
clipboard(x)
```
Send a printed form of `x` to the operating system clipboard ("copy").
```
clipboard() -> AbstractString
```
Return a string with the contents of the operating system clipboard ("paste").
julia Shared Arrays Shared Arrays
=============
###
`SharedArrays.SharedArray`Type
```
SharedArray{T}(dims::NTuple; init=false, pids=Int[])
SharedArray{T,N}(...)
```
Construct a `SharedArray` of a bits type `T` and size `dims` across the processes specified by `pids` - all of which have to be on the same host. If `N` is specified by calling `SharedArray{T,N}(dims)`, then `N` must match the length of `dims`.
If `pids` is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, `localindices` and `indexpids` will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver.
If an `init` function of the type `initfn(S::SharedArray)` is specified, it is called on all the participating workers.
The shared array is valid as long as a reference to the `SharedArray` object exists on the node which created the mapping.
```
SharedArray{T}(filename::AbstractString, dims::NTuple, [offset=0]; mode=nothing, init=false, pids=Int[])
SharedArray{T,N}(...)
```
Construct a `SharedArray` backed by the file `filename`, with element type `T` (must be a bits type) and size `dims`, across the processes specified by `pids` - all of which have to be on the same host. This file is mmapped into the host memory, with the following consequences:
* The array data must be represented in binary format (e.g., an ASCII format like CSV cannot be supported)
* Any changes you make to the array values (e.g., `A[3] = 0`) will also change the values on disk
If `pids` is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, `localindices` and `indexpids` will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver.
`mode` must be one of `"r"`, `"r+"`, `"w+"`, or `"a+"`, and defaults to `"r+"` if the file specified by `filename` already exists, or `"w+"` if not. If an `init` function of the type `initfn(S::SharedArray)` is specified, it is called on all the participating workers. You cannot specify an `init` function if the file is not writable.
`offset` allows you to skip the specified number of bytes at the beginning of the file.
###
`SharedArrays.SharedVector`Type
```
SharedVector
```
A one-dimensional [`SharedArray`](#SharedArrays.SharedArray).
###
`SharedArrays.SharedMatrix`Type
```
SharedMatrix
```
A two-dimensional [`SharedArray`](#SharedArrays.SharedArray).
###
`Distributed.procs`Method
```
procs(S::SharedArray)
```
Get the vector of processes mapping the shared array.
###
`SharedArrays.sdata`Function
```
sdata(S::SharedArray)
```
Returns the actual `Array` object backing `S`.
###
`SharedArrays.indexpids`Function
```
indexpids(S::SharedArray)
```
Returns the current worker's index in the list of workers mapping the `SharedArray` (i.e. in the same list returned by `procs(S)`), or 0 if the `SharedArray` is not mapped locally.
###
`SharedArrays.localindices`Function
```
localindices(S::SharedArray)
```
Returns a range describing the "default" indices to be handled by the current process. This range should be interpreted in the sense of linear indexing, i.e., as a sub-range of `1:length(S)`. In multi-process contexts, returns an empty range in the parent process (or any process for which [`indexpids`](#SharedArrays.indexpids) returns 0).
It's worth emphasizing that `localindices` exists purely as a convenience, and you can partition work on the array among workers any way you wish. For a `SharedArray`, all indices should be equally fast for each worker process.
| programming_docs |
julia Profiling Profiling
=========
[CPU Profiling](#CPU-Profiling)
--------------------------------
There are two main approaches to CPU profiling julia code:
[Via `@profile`](#Via-@profile)
--------------------------------
Where profiling is enabled for a given call via the `@profile` macro.
```
julia> using Profile
julia> @profile foo()
julia> Profile.print()
Overhead ╎ [+additional indent] Count File:Line; Function
=========================================================
╎147 @Base/client.jl:506; _start()
╎ 147 @Base/client.jl:318; exec_options(opts::Base.JLOptions)
...
```
[Triggered During Execution](#Triggered-During-Execution)
----------------------------------------------------------
Tasks that are already running can also be profiled for a fixed time period at any user-triggered time.
To trigger the profiling:
* MacOS & FreeBSD (BSD-based platforms): Use `ctrl-t` or pass a `SIGINFO` signal to the julia process i.e. `% kill -INFO $julia_pid`
* Linux: Pass a `SIGUSR1` signal to the julia process i.e. `% kill -USR1 $julia_pid`
* Windows: Not currently supported.
First, a single stack trace at the instant that the signal was thrown is shown, then a 1 second profile is collected, followed by the profile report at the next yield point, which may be at task completion for code without yield points e.g. tight loops.
```
julia> foo()
##== the user sends a trigger while foo is running ==##
load: 2.53 cmd: julia 88903 running 6.16u 0.97s
======================================================================================
Information request received. A stacktrace will print followed by a 1.0 second profile
======================================================================================
signal (29): Information request: 29
__psynch_cvwait at /usr/lib/system/libsystem_kernel.dylib (unknown line)
_pthread_cond_wait at /usr/lib/system/libsystem_pthread.dylib (unknown line)
...
======================================================================
Profile collected. A report will print if the Profile module is loaded
======================================================================
Overhead ╎ [+additional indent] Count File:Line; Function
=========================================================
Thread 1 Task 0x000000011687c010 Total snapshots: 572. Utilization: 100%
╎147 @Base/client.jl:506; _start()
╎ 147 @Base/client.jl:318; exec_options(opts::Base.JLOptions)
...
Thread 2 Task 0x0000000116960010 Total snapshots: 572. Utilization: 0%
╎572 @Base/task.jl:587; task_done_hook(t::Task)
╎ 572 @Base/task.jl:879; wait()
...
```
###
[Customization](#Customization)
The duration of the profiling can be adjusted via [`Profile.set_peek_duration`](#Profile.set_peek_duration)
The profile report is broken down by thread and task. Pass a no-arg function to `Profile.peek_report[]` to override this. i.e. `Profile.peek_report[] = () -> Profile.print()` to remove any grouping. This could also be overridden by an external profile data consumer.
[Reference](#Reference)
------------------------
###
`Profile.@profile`Macro
```
@profile
```
`@profile <expression>` runs your expression while taking periodic backtraces. These are appended to an internal buffer of backtraces.
The methods in `Profile` are not exported and need to be called e.g. as `Profile.print()`.
###
`Profile.clear`Function
```
clear()
```
Clear any existing backtraces from the internal buffer.
###
`Profile.print`Function
```
print([io::IO = stdout,] [data::Vector = fetch()], [lidict::Union{LineInfoDict, LineInfoFlatDict} = getdict(data)]; kwargs...)
```
Prints profiling results to `io` (by default, `stdout`). If you do not supply a `data` vector, the internal buffer of accumulated backtraces will be used.
The keyword arguments can be any combination of:
* `format` – Determines whether backtraces are printed with (default, `:tree`) or without (`:flat`) indentation indicating tree structure.
* `C` – If `true`, backtraces from C and Fortran code are shown (normally they are excluded).
* `combine` – If `true` (default), instruction pointers are merged that correspond to the same line of code.
* `maxdepth` – Limits the depth higher than `maxdepth` in the `:tree` format.
* `sortedby` – Controls the order in `:flat` format. `:filefuncline` (default) sorts by the source line, `:count` sorts in order of number of collected samples, and `:overhead` sorts by the number of samples incurred by each function by itself.
* `groupby` – Controls grouping over tasks and threads, or no grouping. Options are `:none` (default), `:thread`, `:task`, `[:thread, :task]`, or `[:task, :thread]` where the last two provide nested grouping.
* `noisefloor` – Limits frames that exceed the heuristic noise floor of the sample (only applies to format `:tree`). A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which `n <= noisefloor * √N`, where `n` is the number of samples on this line, and `N` is the number of samples for the callee.
* `mincount` – Limits the printout to only those lines with at least `mincount` occurrences.
* `recur` – Controls the recursion handling in `:tree` format. `:off` (default) prints the tree as normal. `:flat` instead compresses any recursion (by ip), showing the approximate effect of converting any self-recursion into an iterator. `:flatc` does the same but also includes collapsing of C frames (may do odd things around `jl_apply`).
* `threads::Union{Int,AbstractVector{Int}}` – Specify which threads to include snapshots from in the report. Note that this does not control which threads samples are collected on (which may also have been collected on another machine).
* `tasks::Union{Int,AbstractVector{Int}}` – Specify which tasks to include snapshots from in the report. Note that this does not control which tasks samples are collected within.
```
print([io::IO = stdout,] data::Vector, lidict::LineInfoDict; kwargs...)
```
Prints profiling results to `io`. This variant is used to examine results exported by a previous call to [`retrieve`](#Profile.retrieve). Supply the vector `data` of backtraces and a dictionary `lidict` of line information.
See `Profile.print([io], data)` for an explanation of the valid keyword arguments.
###
`Profile.init`Function
```
init(; n::Integer, delay::Real)
```
Configure the `delay` between backtraces (measured in seconds), and the number `n` of instruction pointers that may be stored per thread. Each instruction pointer corresponds to a single line of code; backtraces generally consist of a long list of instruction pointers. Note that 6 spaces for instruction pointers per backtrace are used to store metadata and two NULL end markers. Current settings can be obtained by calling this function with no arguments, and each can be set independently using keywords or in the order `(n, delay)`.
As of Julia 1.8, this function allocates space for `n` instruction pointers per thread being profiled. Previously this was `n` total.
###
`Profile.fetch`Function
```
fetch(;include_meta = true) -> data
```
Returns a copy of the buffer of profile backtraces. Note that the values in `data` have meaning only on this machine in the current session, because it depends on the exact memory addresses used in JIT-compiling. This function is primarily for internal use; [`retrieve`](#Profile.retrieve) may be a better choice for most users. By default metadata such as threadid and taskid is included. Set `include_meta` to `false` to strip metadata.
###
`Profile.retrieve`Function
```
retrieve(; kwargs...) -> data, lidict
```
"Exports" profiling results in a portable format, returning the set of all backtraces (`data`) and a dictionary that maps the (session-specific) instruction pointers in `data` to `LineInfo` values that store the file name, function name, and line number. This function allows you to save profiling results for future analysis.
###
`Profile.callers`Function
```
callers(funcname, [data, lidict], [filename=<filename>], [linerange=<start:stop>]) -> Vector{Tuple{count, lineinfo}}
```
Given a previous profiling run, determine who called a particular function. Supplying the filename (and optionally, range of line numbers over which the function is defined) allows you to disambiguate an overloaded method. The returned value is a vector containing a count of the number of calls and line information about the caller. One can optionally supply backtrace `data` obtained from [`retrieve`](#Profile.retrieve); otherwise, the current internal profile buffer is used.
###
`Profile.clear_malloc_data`Function
```
clear_malloc_data()
```
Clears any stored memory allocation data when running julia with `--track-allocation`. Execute the command(s) you want to test (to force JIT-compilation), then call [`clear_malloc_data`](#Profile.clear_malloc_data). Then execute your command(s) again, quit Julia, and examine the resulting `*.mem` files.
###
`Profile.get_peek_duration`Function
```
get_peek_duration()
```
Get the duration in seconds of the profile "peek" that is triggered via `SIGINFO` or `SIGUSR1`, depending on platform.
###
`Profile.set_peek_duration`Function
```
set_peek_duration(t::Float64)
```
Set the duration in seconds of the profile "peek" that is triggered via `SIGINFO` or `SIGUSR1`, depending on platform.
[Memory profiling](#Memory-profiling)
--------------------------------------
###
`Profile.Allocs.@profile`Macro
```
Profile.Allocs.@profile [sample_rate=0.0001] expr
```
Profile allocations that happen during `expr`, returning both the result and and AllocResults struct.
A sample rate of 1.0 will record everything; 0.0 will record nothing.
```
julia> Profile.Allocs.@profile sample_rate=0.01 peakflops()
1.03733270279065e11
julia> results = Profile.Allocs.fetch()
julia> last(sort(results.allocs, by=x->x.size))
Profile.Allocs.Alloc(Vector{Any}, Base.StackTraces.StackFrame[_new_array_ at array.c:127, ...], 5576)
```
The current implementation of the Allocations Profiler does not capture types for all allocations. Allocations for which the profiler could not capture the type are represented as having type `Profile.Allocs.UnknownType`.
You can read more about the missing types and the plan to improve this, here: https://github.com/JuliaLang/julia/issues/43688.
The allocation profiler was added in Julia 1.8.
The methods in `Profile.Allocs` are not exported and need to be called e.g. as `Profile.Allocs.fetch()`.
###
`Profile.Allocs.clear`Function
```
Profile.Allocs.clear()
```
Clear all previously profiled allocation information from memory.
###
`Profile.Allocs.fetch`Function
```
Profile.Allocs.fetch()
```
Retrieve the recorded allocations, and decode them into Julia objects which can be analyzed.
###
`Profile.Allocs.start`Function
```
Profile.Allocs.start(sample_rate::Real)
```
Begin recording allocations with the given sample rate A sample rate of 1.0 will record everything; 0.0 will record nothing.
###
`Profile.Allocs.stop`Function
```
Profile.Allocs.stop()
```
Stop recording allocations.
julia Delimited Files Delimited Files
===============
###
`DelimitedFiles.readdlm`Method
```
readdlm(source, delim::AbstractChar, T::Type, eol::AbstractChar; header=false, skipstart=0, skipblanks=true, use_mmap, quotes=true, dims, comments=false, comment_char='#')
```
Read a matrix from the source where each line (separated by `eol`) gives one row, with elements separated by the given delimiter. The source can be a text file, stream or byte array. Memory mapped files can be used by passing the byte array representation of the mapped segment as source.
If `T` is a numeric type, the result is an array of that type, with any non-numeric elements as `NaN` for floating-point types, or zero. Other useful values of `T` include `String`, `AbstractString`, and `Any`.
If `header` is `true`, the first row of data will be read as header and the tuple `(data_cells, header_cells)` is returned instead of only `data_cells`.
Specifying `skipstart` will ignore the corresponding number of initial lines from the input.
If `skipblanks` is `true`, blank lines in the input will be ignored.
If `use_mmap` is `true`, the file specified by `source` is memory mapped for potential speedups if the file is large. Default is `false`. On a Windows filesystem, `use_mmap` should not be set to `true` unless the file is only read once and is also not written to. Some edge cases exist where an OS is Unix-like but the filesystem is Windows-like.
If `quotes` is `true`, columns enclosed within double-quote (") characters are allowed to contain new lines and column delimiters. Double-quote characters within a quoted field must be escaped with another double-quote. Specifying `dims` as a tuple of the expected rows and columns (including header, if any) may speed up reading of large files. If `comments` is `true`, lines beginning with `comment_char` and text following `comment_char` in any line are ignored.
**Examples**
```
julia> using DelimitedFiles
julia> x = [1; 2; 3; 4];
julia> y = [5; 6; 7; 8];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x y])
end
julia> readdlm("delim_file.txt", '\t', Int, '\n')
4×2 Matrix{Int64}:
1 5
2 6
3 7
4 8
julia> rm("delim_file.txt")
```
###
`DelimitedFiles.readdlm`Method
```
readdlm(source, delim::AbstractChar, eol::AbstractChar; options...)
```
If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.
###
`DelimitedFiles.readdlm`Method
```
readdlm(source, delim::AbstractChar, T::Type; options...)
```
The end of line delimiter is taken as `\n`.
**Examples**
```
julia> using DelimitedFiles
julia> x = [1; 2; 3; 4];
julia> y = [1.1; 2.2; 3.3; 4.4];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x y], ',')
end;
julia> readdlm("delim_file.txt", ',', Float64)
4×2 Matrix{Float64}:
1.0 1.1
2.0 2.2
3.0 3.3
4.0 4.4
julia> rm("delim_file.txt")
```
###
`DelimitedFiles.readdlm`Method
```
readdlm(source, delim::AbstractChar; options...)
```
The end of line delimiter is taken as `\n`. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.
**Examples**
```
julia> using DelimitedFiles
julia> x = [1; 2; 3; 4];
julia> y = [1.1; 2.2; 3.3; 4.4];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x y], ',')
end;
julia> readdlm("delim_file.txt", ',')
4×2 Matrix{Float64}:
1.0 1.1
2.0 2.2
3.0 3.3
4.0 4.4
julia> z = ["a"; "b"; "c"; "d"];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x z], ',')
end;
julia> readdlm("delim_file.txt", ',')
4×2 Matrix{Any}:
1 "a"
2 "b"
3 "c"
4 "d"
julia> rm("delim_file.txt")
```
###
`DelimitedFiles.readdlm`Method
```
readdlm(source, T::Type; options...)
```
The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as `\n`.
**Examples**
```
julia> using DelimitedFiles
julia> x = [1; 2; 3; 4];
julia> y = [5; 6; 7; 8];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x y])
end;
julia> readdlm("delim_file.txt", Int64)
4×2 Matrix{Int64}:
1 5
2 6
3 7
4 8
julia> readdlm("delim_file.txt", Float64)
4×2 Matrix{Float64}:
1.0 5.0
2.0 6.0
3.0 7.0
4.0 8.0
julia> rm("delim_file.txt")
```
###
`DelimitedFiles.readdlm`Method
```
readdlm(source; options...)
```
The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as `\n`. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.
**Examples**
```
julia> using DelimitedFiles
julia> x = [1; 2; 3; 4];
julia> y = ["a"; "b"; "c"; "d"];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x y])
end;
julia> readdlm("delim_file.txt")
4×2 Matrix{Any}:
1 "a"
2 "b"
3 "c"
4 "d"
julia> rm("delim_file.txt")
```
###
`DelimitedFiles.writedlm`Function
```
writedlm(f, A, delim='\t'; opts)
```
Write `A` (a vector, matrix, or an iterable collection of iterable rows) as text to `f` (either a filename string or an `IO` stream) using the given delimiter `delim` (which defaults to tab, but can be any printable Julia object, typically a `Char` or `AbstractString`).
For example, two vectors `x` and `y` of the same length can be written as two columns of tab-delimited text to `f` by either `writedlm(f, [x y])` or by `writedlm(f, zip(x, y))`.
**Examples**
```
julia> using DelimitedFiles
julia> x = [1; 2; 3; 4];
julia> y = [5; 6; 7; 8];
julia> open("delim_file.txt", "w") do io
writedlm(io, [x y])
end
julia> readdlm("delim_file.txt", '\t', Int, '\n')
4×2 Matrix{Int64}:
1 5
2 6
3 7
4 8
julia> rm("delim_file.txt")
```
julia NetworkOptions NetworkOptions
==============
###
`NetworkOptions.ca_roots`Function
```
ca_roots() :: Union{Nothing, String}
```
The `ca_roots()` function tells the caller where, if anywhere, to find a file or directory of PEM-encoded certificate authority roots. By default, on systems like Windows and macOS where the built-in TLS engines know how to verify hosts using the system's built-in certificate verification mechanism, this function will return `nothing`. On classic UNIX systems (excluding macOS), root certificates are typically stored in a file in `/etc`: the common places for the current UNIX system will be searched and if one of these paths exists, it will be returned; if none of these typical root certificate paths exist, then the path to the set of root certificates that are bundled with Julia is returned.
The default value returned by `ca_roots()` may be overridden by setting the `JULIA_SSL_CA_ROOTS_PATH`, `SSL_CERT_DIR`, or `SSL_CERT_FILE` environment variables, in which case this function will always return the value of the first of these variables that is set (whether the path exists or not). If `JULIA_SSL_CA_ROOTS_PATH` is set to the empty string, then the other variables are ignored (as if unset); if the other variables are set to the empty string, they behave is if they are not set.
###
`NetworkOptions.ca_roots_path`Function
```
ca_roots_path() :: String
```
The `ca_roots_path()` function is similar to the `ca_roots()` function except that it always returns a path to a file or directory of PEM-encoded certificate authority roots. When called on a system like Windows or macOS, where system root certificates are not stored in the file system, it will currently return the path to the set of root certificates that are bundled with Julia. (In the future, this function may instead extract the root certificates from the system and save them to a file whose path would be returned.)
If it is possible to configure a library that uses TLS to use the system certificates that is generally preferable: i.e. it is better to use `ca_roots()` which returns `nothing` to indicate that the system certs should be used. The `ca_roots_path()` function should only be used when configuring libraries which *require* a path to a file or directory for root certificates.
The default value returned by `ca_roots_path()` may be overridden by setting the `JULIA_SSL_CA_ROOTS_PATH`, `SSL_CERT_DIR`, or `SSL_CERT_FILE` environment variables, in which case this function will always return the value of the first of these variables that is set (whether the path exists or not). If `JULIA_SSL_CA_ROOTS_PATH` is set to the empty string, then the other variables are ignored (as if unset); if the other variables are set to the empty string, they behave is if they are not set.
###
`NetworkOptions.ssh_dir`Function
```
ssh_dir() :: String
```
The `ssh_dir()` function returns the location of the directory where the `ssh` program keeps/looks for configuration files. By default this is `~/.ssh` but this can be overridden by setting the environment variable `SSH_DIR`.
###
`NetworkOptions.ssh_key_pass`Function
```
ssh_key_pass() :: String
```
The `ssh_key_pass()` function returns the value of the environment variable `SSH_KEY_PASS` if it is set or `nothing` if it is not set. In the future, this may be able to find a password by other means, such as secure system storage, so packages that need a password to decrypt an SSH private key should use this API instead of directly checking the environment variable so that they gain such capabilities automatically when they are added.
###
`NetworkOptions.ssh_key_name`Function
```
ssh_key_name() :: String
```
The `ssh_key_name()` function returns the base name of key files that SSH should use for when establishing a connection. There is usually no reason that this function should be called directly and libraries should generally use the `ssh_key_path` and `ssh_pub_key_path` functions to get full paths. If the environment variable `SSH_KEY_NAME` is set then this function returns that; otherwise it returns `id_rsa` by default.
###
`NetworkOptions.ssh_key_path`Function
```
ssh_key_path() :: String
```
The `ssh_key_path()` function returns the path of the SSH private key file that should be used for SSH connections. If the `SSH_KEY_PATH` environment variable is set then it will return that value. Otherwise it defaults to returning
```
joinpath(ssh_dir(), ssh_key_name())
```
This default value in turn depends on the `SSH_DIR` and `SSH_KEY_NAME` environment variables.
###
`NetworkOptions.ssh_pub_key_path`Function
```
ssh_pub_key_path() :: String
```
The `ssh_pub_key_path()` function returns the path of the SSH public key file that should be used for SSH connections. If the `SSH_PUB_KEY_PATH` environment variable is set then it will return that value. If that isn't set but `SSH_KEY_PATH` is set, it will return that path with the `.pub` suffix appended. If neither is set, it defaults to returning
```
joinpath(ssh_dir(), ssh_key_name() * ".pub")
```
This default value in turn depends on the `SSH_DIR` and `SSH_KEY_NAME` environment variables.
###
`NetworkOptions.ssh_known_hosts_files`Function
```
ssh_known_hosts_files() :: Vector{String}
```
The `ssh_known_hosts_files()` function returns a vector of paths of SSH known hosts files that should be used when establishing the identities of remote servers for SSH connections. By default this function returns
```
[joinpath(ssh_dir(), "known_hosts"), bundled_known_hosts]
```
where `bundled_known_hosts` is the path of a copy of a known hosts file that is bundled with this package (containing known hosts keys for `github.com` and `gitlab.com`). If the environment variable `SSH_KNOWN_HOSTS_FILES` is set, however, then its value is split into paths on the `:` character (or on `;` on Windows) and this vector of paths is returned instead. If any component of this vector is empty, it is expanded to the default known hosts paths.
Packages that use `ssh_known_hosts_files()` should ideally look for matching entries by comparing the host name and key types, considering the first entry in any of the files which matches to be the definitive identity of the host. If the caller cannot compare the key type (e.g. because it has been hashes) then it must approximate the above algorithm by looking for all matching entries for a host in each file: if a file has any entries for a host then one of them must match; the caller should only continue to search further known hosts files if there are no entries for the host in question in an earlier file.
###
`NetworkOptions.ssh_known_hosts_file`Function
```
ssh_known_hosts_file() :: String
```
The `ssh_known_hosts_file()` function returns a single path of an SSH known hosts file that should be used when establishing the identities of remote servers for SSH connections. It returns the first path returned by `ssh_known_hosts_files` that actually exists. Callers who can look in more than one known hosts file should use `ssh_known_hosts_files` instead and look for host matches in all the files returned as described in that function's docs.
###
`NetworkOptions.verify_host`Function
```
verify_host(url::AbstractString, [transport::AbstractString]) :: Bool
```
The `verify_host` function tells the caller whether the identity of a host should be verified when communicating over secure transports like TLS or SSH. The `url` argument may be:
1. a proper URL staring with `proto://`
2. an `ssh`-style bare host name or host name prefixed with `user@`
3. an `scp`-style host as above, followed by `:` and a path location
In each case the host name part is parsed out and the decision about whether to verify or not is made based solely on the host name, not anything else about the input URL. In particular, the protocol of the URL does not matter (more below).
The `transport` argument indicates the kind of transport that the query is about. The currently known values are `SSL` (alias `TLS`) and `SSH`. If the transport is omitted, the query will return `true` only if the host name should not be verified regardless of transport.
The host name is matched against the host patterns in the relevant environment variables depending on whether `transport` is supplied and what its value is:
* `JULIA_NO_VERIFY_HOSTS` — hosts that should not be verified for any transport
* `JULIA_SSL_NO_VERIFY_HOSTS` — hosts that should not be verified for SSL/TLS
* `JULIA_SSH_NO_VERIFY_HOSTS` — hosts that should not be verified for SSH
* `JULIA_ALWAYS_VERIFY_HOSTS` — hosts that should always be verified
The values of each of these variables is a comma-separated list of host name patterns with the following syntax — each pattern is split on `.` into parts and each part must one of:
1. A literal domain name component consisting of one or more ASCII letter, digit, hyphen or underscore (technically not part of a legal host name, but sometimes used). A literal domain name component matches only itself.
2. A `**`, which matches zero or more domain name components.
3. A `*`, which match any one domain name component.
When matching a host name against a pattern list in one of these variables, the host name is split on `.` into components and that sequence of words is matched against the pattern: a literal pattern matches exactly one host name component with that value; a `*` pattern matches exactly one host name component with any value; a `**` pattern matches any number of host name components. For example:
* `**` matches any host name
* `**.org` matches any host name in the `.org` top-level domain
* `example.com` matches only the exact host name `example.com`
* `*.example.com` matches `api.example.com` but not `example.com` or `v1.api.example.com`
* `**.example.com` matches any domain under `example.com`, including `example.com` itself, `api.example.com` and `v1.api.example.com`
| programming_docs |
julia UUIDs UUIDs
=====
###
`UUIDs.uuid1`Function
```
uuid1([rng::AbstractRNG]) -> UUID
```
Generates a version 1 (time-based) universally unique identifier (UUID), as specified by RFC 4122. Note that the Node ID is randomly generated (does not identify the host) according to section 4.5 of the RFC.
The default rng used by `uuid1` is not `GLOBAL_RNG` and every invocation of `uuid1()` without an argument should be expected to return a unique identifier. Importantly, the outputs of `uuid1` do not repeat even when `Random.seed!(seed)` is called. Currently (as of Julia 1.6), `uuid1` uses `Random.RandomDevice` as the default rng. However, this is an implementation detail that may change in the future.
The output of `uuid1` does not depend on `GLOBAL_RNG` as of Julia 1.6.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> uuid1(rng)
UUID("cfc395e8-590f-11e8-1f13-43a2532b2fa8")
```
###
`UUIDs.uuid4`Function
```
uuid4([rng::AbstractRNG]) -> UUID
```
Generates a version 4 (random or pseudo-random) universally unique identifier (UUID), as specified by RFC 4122.
The default rng used by `uuid4` is not `GLOBAL_RNG` and every invocation of `uuid4()` without an argument should be expected to return a unique identifier. Importantly, the outputs of `uuid4` do not repeat even when `Random.seed!(seed)` is called. Currently (as of Julia 1.6), `uuid4` uses `Random.RandomDevice` as the default rng. However, this is an implementation detail that may change in the future.
The output of `uuid4` does not depend on `GLOBAL_RNG` as of Julia 1.6.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> uuid4(rng)
UUID("7a052949-c101-4ca3-9a7e-43a2532b2fa8")
```
###
`UUIDs.uuid5`Function
```
uuid5(ns::UUID, name::String) -> UUID
```
Generates a version 5 (namespace and domain-based) universally unique identifier (UUID), as specified by RFC 4122.
This function requires at least Julia 1.1.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> u4 = uuid4(rng)
UUID("7a052949-c101-4ca3-9a7e-43a2532b2fa8")
julia> u5 = uuid5(u4, "julia")
UUID("086cc5bb-2461-57d8-8068-0aed7f5b5cd1")
```
###
`UUIDs.uuid_version`Function
```
uuid_version(u::UUID) -> Int
```
Inspects the given UUID and returns its version (see [RFC 4122](https://www.ietf.org/rfc/rfc4122)).
**Examples**
```
julia> uuid_version(uuid4())
4
```
julia SHA SHA
===
[SHA functions](#SHA-functions)
--------------------------------
Usage is very straightforward:
```
julia> using SHA
julia> bytes2hex(sha256("test"))
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
```
Each exported function (at the time of this writing, SHA-1, SHA-2 224, 256, 384 and 512, and SHA-3 224, 256, 384 and 512 functions are implemented) takes in either an `AbstractVector{UInt8}`, an `AbstractString` or an `IO` object. This makes it trivial to checksum a file:
```
shell> cat /tmp/test.txt
test
julia> using SHA
julia> open("/tmp/test.txt") do f
sha2_256(f)
end
32-element Array{UInt8,1}:
0x9f
0x86
0xd0
0x81
0x88
0x4c
0x7d
0x65
⋮
0x5d
0x6c
0x15
0xb0
0xf0
0x0a
0x08
```
###
[All SHA functions](#All-SHA-functions)
Due to the colloquial usage of `sha256` to refer to `sha2_256`, convenience functions are provided, mapping `shaxxx()` function calls to `sha2_xxx()`. For SHA-3, no such colloquialisms exist and the user must use the full `sha3_xxx()` names.
`shaxxx()` takes `AbstractString` and array-like objects (`NTuple` and `Array`) with elements of type `UInt8`.
**SHA-1**
###
`SHA.sha1`Function
```
sha1(data)
```
Hash data using the `sha1` algorithm and return the resulting digest. See also [`SHA1_CTX`](#SHA.SHA1_CTX).
```
sha1(io::IO)
```
Hash data from io using `sha1` algorithm.
**SHA-2**
###
`SHA.sha224`Function
```
sha224(data)
```
Hash data using the `sha224` algorithm and return the resulting digest. See also [`SHA2_224_CTX`](#SHA.SHA2_224_CTX).
```
sha224(io::IO)
```
Hash data from io using `sha224` algorithm.
###
`SHA.sha256`Function
```
sha256(data)
```
Hash data using the `sha256` algorithm and return the resulting digest. See also [`SHA2_256_CTX`](#SHA.SHA2_256_CTX).
```
sha256(io::IO)
```
Hash data from io using `sha256` algorithm.
###
`SHA.sha384`Function
```
sha384(data)
```
Hash data using the `sha384` algorithm and return the resulting digest. See also [`SHA2_384_CTX`](#SHA.SHA2_384_CTX).
```
sha384(io::IO)
```
Hash data from io using `sha384` algorithm.
###
`SHA.sha512`Function
```
sha512(data)
```
Hash data using the `sha512` algorithm and return the resulting digest. See also [`SHA2_512_CTX`](#SHA.SHA2_512_CTX).
```
sha512(io::IO)
```
Hash data from io using `sha512` algorithm.
###
`SHA.sha2_224`Function
```
sha2_224(data)
```
Hash data using the `sha2_224` algorithm and return the resulting digest. See also [`SHA2_224_CTX`](#SHA.SHA2_224_CTX).
```
sha2_224(io::IO)
```
Hash data from io using `sha2_224` algorithm.
###
`SHA.sha2_256`Function
```
sha2_256(data)
```
Hash data using the `sha2_256` algorithm and return the resulting digest. See also [`SHA2_256_CTX`](#SHA.SHA2_256_CTX).
```
sha2_256(io::IO)
```
Hash data from io using `sha2_256` algorithm.
###
`SHA.sha2_384`Function
```
sha2_384(data)
```
Hash data using the `sha2_384` algorithm and return the resulting digest. See also [`SHA2_384_CTX`](#SHA.SHA2_384_CTX).
```
sha2_384(io::IO)
```
Hash data from io using `sha2_384` algorithm.
###
`SHA.sha2_512`Function
```
sha2_512(data)
```
Hash data using the `sha2_512` algorithm and return the resulting digest. See also [`SHA2_512_CTX`](#SHA.SHA2_512_CTX).
```
sha2_512(io::IO)
```
Hash data from io using `sha2_512` algorithm.
**SHA-3**
###
`SHA.sha3_224`Function
```
sha3_224(data)
```
Hash data using the `sha3_224` algorithm and return the resulting digest. See also [`SHA3_224_CTX`](#SHA.SHA3_224_CTX).
```
sha3_224(io::IO)
```
Hash data from io using `sha3_224` algorithm.
###
`SHA.sha3_256`Function
```
sha3_256(data)
```
Hash data using the `sha3_256` algorithm and return the resulting digest. See also [`SHA3_256_CTX`](#SHA.SHA3_256_CTX).
```
sha3_256(io::IO)
```
Hash data from io using `sha3_256` algorithm.
###
`SHA.sha3_384`Function
```
sha3_384(data)
```
Hash data using the `sha3_384` algorithm and return the resulting digest. See also [`SHA3_384_CTX`](#SHA.SHA3_384_CTX).
```
sha3_384(io::IO)
```
Hash data from io using `sha3_384` algorithm.
###
`SHA.sha3_512`Function
```
sha3_512(data)
```
Hash data using the `sha3_512` algorithm and return the resulting digest. See also [`SHA3_512_CTX`](#SHA.SHA3_512_CTX).
```
sha3_512(io::IO)
```
Hash data from io using `sha3_512` algorithm.
[Working with context](#Working-with-context)
----------------------------------------------
To create a hash from multiple items the `SHAX_XXX_CTX()` types can be used to create a stateful hash object that is updated with `update!` and finalized with `digest!`
```
julia> using SHA
julia> ctx = SHA2_256_CTX()
SHA2 256-bit hash state
julia> update!(ctx, b"some data")
0x0000000000000009
julia> update!(ctx, b"some more data")
0x0000000000000017
julia> digest!(ctx)
32-element Vector{UInt8}:
0xbe
0xcf
0x23
0xda
0xaf
0x02
0xf7
0xa3
0x57
0x92
⋮
0x89
0x4f
0x59
0xd8
0xb3
0xb4
0x81
0x8b
0xc5
```
Note that, at the time of this writing, the SHA3 code is not optimized, and as such is roughly an order of magnitude slower than SHA2.
###
`SHA.update!`Function
```
update!(context, data[, datalen])
```
Update the SHA context with the bytes in data. See also [`digest!`](#SHA.digest!) for finalizing the hash.
**Examples**
```
julia> ctx = SHA1_CTX()
SHA1 hash state
julia> update!(ctx, b"data to to be hashed")
```
###
`SHA.digest!`Function
```
digest!(context)
```
Finalize the SHA context and return the hash as array of bytes (Array{Uint8, 1}).
**Examples**
```
julia> ctx = SHA1_CTX()
SHA1 hash state
julia> update!(ctx, b"data to to be hashed")
julia> digest!(ctx)
20-element Array{UInt8,1}:
0x83
0xe4
⋮
0x89
0xf5
```
###
[All SHA context types](#All-SHA-context-types)
**SHA-1**
###
`SHA.SHA1_CTX`Type
```
SHA1_CTX()
```
Construct an empty SHA1 context.
**SHA-2**
Convenience types are also provided, where `SHAXXX_CTX` is a type alias for `SHA2_XXX_CTX`.
###
`SHA.SHA224_CTX`Type
```
SHA2_224_CTX()
```
Construct an empty SHA2\_224 context.
###
`SHA.SHA256_CTX`Type
```
SHA2_256_CTX()
```
Construct an empty SHA2\_256 context.
###
`SHA.SHA384_CTX`Type
```
SHA2_384()
```
Construct an empty SHA2\_384 context.
###
`SHA.SHA512_CTX`Type
```
SHA2_512_CTX()
```
Construct an empty SHA2\_512 context.
###
`SHA.SHA2_224_CTX`Type
```
SHA2_224_CTX()
```
Construct an empty SHA2\_224 context.
###
`SHA.SHA2_256_CTX`Type
```
SHA2_256_CTX()
```
Construct an empty SHA2\_256 context.
###
`SHA.SHA2_384_CTX`Type
```
SHA2_384()
```
Construct an empty SHA2\_384 context.
###
`SHA.SHA2_512_CTX`Type
```
SHA2_512_CTX()
```
Construct an empty SHA2\_512 context.
**SHA-3**
###
`SHA.SHA3_224_CTX`Type
```
SHA3_224_CTX()
```
Construct an empty SHA3\_224 context.
###
`SHA.SHA3_256_CTX`Type
```
SHA3_256_CTX()
```
Construct an empty SHA3\_256 context.
###
`SHA.SHA3_384_CTX`Type
```
SHA3_384_CTX()
```
Construct an empty SHA3\_384 context.
###
`SHA.SHA3_512_CTX`Type
```
SHA3_512_CTX()
```
Construct an empty SHA3\_512 context.
[HMAC functions](#HMAC-functions)
----------------------------------
```
julia> using SHA
julia> key = collect(codeunits("key_string"))
10-element Vector{UInt8}:
0x6b
0x65
0x79
0x5f
0x73
0x74
0x72
0x69
0x6e
0x67
julia> bytes2hex(hmac_sha3_256(key, "test-message"))
"bc49a6f2aa29b27ee5ed1e944edd7f3d153e8a01535d98b5e24dac9a589a6248"
```
To create a hash from multiple items, the `HMAC_CTX()` types can be used to create a stateful hash object that is updated with `update!` and finalized with `digest!`.
```
julia> using SHA
julia> key = collect(codeunits("key_string"))
10-element Vector{UInt8}:
0x6b
0x65
0x79
0x5f
0x73
0x74
0x72
0x69
0x6e
0x67
julia> ctx = HMAC_CTX(SHA3_256_CTX(), key);
julia> update!(ctx, b"test-")
0x0000000000000000000000000000008d
julia> update!(ctx, b"message")
0x00000000000000000000000000000094
julia> bytes2hex(digest!(ctx))
"bc49a6f2aa29b27ee5ed1e944edd7f3d153e8a01535d98b5e24dac9a589a6248"
```
###
[All HMAC functions](#All-HMAC-functions)
**HMAC context type**
###
`SHA.HMAC_CTX`Type
```
HMAC_CTX(ctx::CTX, key::Vector{UInt8}) where {CTX<:SHA_CTX}
```
Construct an empty HMAC\_CTX context.
**SHA-1**
###
`SHA.hmac_sha1`Function
```
hmac_sha1(key, data)
```
Hash data using the `sha1` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha1(key, io::IO)
```
Hash data from `io` with the passed key using `sha1` algorithm.
**SHA-2**
###
`SHA.hmac_sha224`Function
```
hmac_sha224(key, data)
```
Hash data using the `sha224` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha224(key, io::IO)
```
Hash data from `io` with the passed key using `sha224` algorithm.
###
`SHA.hmac_sha256`Function
```
hmac_sha256(key, data)
```
Hash data using the `sha256` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha256(key, io::IO)
```
Hash data from `io` with the passed key using `sha256` algorithm.
###
`SHA.hmac_sha384`Function
```
hmac_sha384(key, data)
```
Hash data using the `sha384` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha384(key, io::IO)
```
Hash data from `io` with the passed key using `sha384` algorithm.
###
`SHA.hmac_sha512`Function
```
hmac_sha512(key, data)
```
Hash data using the `sha512` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha512(key, io::IO)
```
Hash data from `io` with the passed key using `sha512` algorithm.
###
`SHA.hmac_sha2_224`Function
```
hmac_sha2_224(key, data)
```
Hash data using the `sha2_224` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha2_224(key, io::IO)
```
Hash data from `io` with the passed key using `sha2_224` algorithm.
###
`SHA.hmac_sha2_256`Function
```
hmac_sha2_256(key, data)
```
Hash data using the `sha2_256` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha2_256(key, io::IO)
```
Hash data from `io` with the passed key using `sha2_256` algorithm.
###
`SHA.hmac_sha2_384`Function
```
hmac_sha2_384(key, data)
```
Hash data using the `sha2_384` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha2_384(key, io::IO)
```
Hash data from `io` with the passed key using `sha2_384` algorithm.
###
`SHA.hmac_sha2_512`Function
```
hmac_sha2_512(key, data)
```
Hash data using the `sha2_512` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha2_512(key, io::IO)
```
Hash data from `io` with the passed key using `sha2_512` algorithm.
**SHA-3**
###
`SHA.hmac_sha3_224`Function
```
hmac_sha3_224(key, data)
```
Hash data using the `sha3_224` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha3_224(key, io::IO)
```
Hash data from `io` with the passed key using `sha3_224` algorithm.
###
`SHA.hmac_sha3_256`Function
```
hmac_sha3_256(key, data)
```
Hash data using the `sha3_256` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha3_256(key, io::IO)
```
Hash data from `io` with the passed key using `sha3_256` algorithm.
###
`SHA.hmac_sha3_384`Function
```
hmac_sha3_384(key, data)
```
Hash data using the `sha3_384` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha3_384(key, io::IO)
```
Hash data from `io` with the passed key using `sha3_384` algorithm.
###
`SHA.hmac_sha3_512`Function
```
hmac_sha3_512(key, data)
```
Hash data using the `sha3_512` algorithm using the passed key. See also [`HMAC_CTX`](#SHA.HMAC_CTX).
```
hmac_sha3_512(key, io::IO)
```
Hash data from `io` with the passed key using `sha3_512` algorithm.
julia Linear Algebra Linear Algebra
==============
In addition to (and as part of) its support for multi-dimensional arrays, Julia provides native implementations of many common and useful linear algebra operations which can be loaded with `using LinearAlgebra`. Basic operations, such as [`tr`](#LinearAlgebra.tr), [`det`](#LinearAlgebra.det), and [`inv`](#) are all supported:
```
julia> A = [1 2 3; 4 1 6; 7 8 1]
3×3 Matrix{Int64}:
1 2 3
4 1 6
7 8 1
julia> tr(A)
3
julia> det(A)
104.0
julia> inv(A)
3×3 Matrix{Float64}:
-0.451923 0.211538 0.0865385
0.365385 -0.192308 0.0576923
0.240385 0.0576923 -0.0673077
```
As well as other useful operations, such as finding eigenvalues or eigenvectors:
```
julia> A = [-4. -17.; 2. 2.]
2×2 Matrix{Float64}:
-4.0 -17.0
2.0 2.0
julia> eigvals(A)
2-element Vector{ComplexF64}:
-1.0 - 5.0im
-1.0 + 5.0im
julia> eigvecs(A)
2×2 Matrix{ComplexF64}:
0.945905-0.0im 0.945905+0.0im
-0.166924+0.278207im -0.166924-0.278207im
```
In addition, Julia provides many [factorizations](#man-linalg-factorizations) which can be used to speed up problems such as linear solve or matrix exponentiation by pre-factorizing a matrix into a form more amenable (for performance or memory reasons) to the problem. See the documentation on [`factorize`](#LinearAlgebra.factorize) for more information. As an example:
```
julia> A = [1.5 2 -4; 3 -1 -6; -10 2.3 4]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
3.0 -1.0 -6.0
-10.0 2.3 4.0
julia> factorize(A)
LU{Float64, Matrix{Float64}, Vector{Int64}}
L factor:
3×3 Matrix{Float64}:
1.0 0.0 0.0
-0.15 1.0 0.0
-0.3 -0.132196 1.0
U factor:
3×3 Matrix{Float64}:
-10.0 2.3 4.0
0.0 2.345 -3.4
0.0 0.0 -5.24947
```
Since `A` is not Hermitian, symmetric, triangular, tridiagonal, or bidiagonal, an LU factorization may be the best we can do. Compare with:
```
julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> factorize(B)
BunchKaufman{Float64, Matrix{Float64}, Vector{Int64}}
D factor:
3×3 Tridiagonal{Float64, Vector{Float64}}:
-1.64286 0.0 ⋅
0.0 -2.8 0.0
⋅ 0.0 5.0
U factor:
3×3 UnitUpperTriangular{Float64, Matrix{Float64}}:
1.0 0.142857 -0.8
⋅ 1.0 -0.6
⋅ ⋅ 1.0
permutation:
3-element Vector{Int64}:
1
2
3
```
Here, Julia was able to detect that `B` is in fact symmetric, and used a more appropriate factorization. Often it's possible to write more efficient code for a matrix that is known to have certain properties e.g. it is symmetric, or tridiagonal. Julia provides some special types so that you can "tag" matrices as having these properties. For instance:
```
julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> sB = Symmetric(B)
3×3 Symmetric{Float64, Matrix{Float64}}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
```
`sB` has been tagged as a matrix that's (real) symmetric, so for later operations we might perform on it, such as eigenfactorization or computing matrix-vector products, efficiencies can be found by only referencing half of it. For example:
```
julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
3×3 Matrix{Float64}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> sB = Symmetric(B)
3×3 Symmetric{Float64, Matrix{Float64}}:
1.5 2.0 -4.0
2.0 -1.0 -3.0
-4.0 -3.0 5.0
julia> x = [1; 2; 3]
3-element Vector{Int64}:
1
2
3
julia> sB\x
3-element Vector{Float64}:
-1.7391304347826084
-1.1086956521739126
-1.4565217391304346
```
The `\` operation here performs the linear solution. The left-division operator is pretty powerful and it's easy to write compact, readable code that is flexible enough to solve all sorts of systems of linear equations.
[Special matrices](#Special-matrices)
--------------------------------------
[Matrices with special symmetries and structures](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=3274) arise often in linear algebra and are frequently associated with various matrix factorizations. Julia features a rich collection of special matrix types, which allow for fast computation with specialized routines that are specially developed for particular matrix types.
The following tables summarize the types of special matrices that have been implemented in Julia, as well as whether hooks to various optimized methods for them in LAPACK are available.
| Type | Description |
| --- | --- |
| [`Symmetric`](#LinearAlgebra.Symmetric) | [Symmetric matrix](https://en.wikipedia.org/wiki/Symmetric_matrix) |
| [`Hermitian`](#LinearAlgebra.Hermitian) | [Hermitian matrix](https://en.wikipedia.org/wiki/Hermitian_matrix) |
| [`UpperTriangular`](#LinearAlgebra.UpperTriangular) | Upper [triangular matrix](https://en.wikipedia.org/wiki/Triangular_matrix) |
| [`UnitUpperTriangular`](#LinearAlgebra.UnitUpperTriangular) | Upper [triangular matrix](https://en.wikipedia.org/wiki/Triangular_matrix) with unit diagonal |
| [`LowerTriangular`](#LinearAlgebra.LowerTriangular) | Lower [triangular matrix](https://en.wikipedia.org/wiki/Triangular_matrix) |
| [`UnitLowerTriangular`](#LinearAlgebra.UnitLowerTriangular) | Lower [triangular matrix](https://en.wikipedia.org/wiki/Triangular_matrix) with unit diagonal |
| [`UpperHessenberg`](#LinearAlgebra.UpperHessenberg) | Upper [Hessenberg matrix](https://en.wikipedia.org/wiki/Hessenberg_matrix) |
| [`Tridiagonal`](#LinearAlgebra.Tridiagonal) | [Tridiagonal matrix](https://en.wikipedia.org/wiki/Tridiagonal_matrix) |
| [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal) | Symmetric tridiagonal matrix |
| [`Bidiagonal`](#LinearAlgebra.Bidiagonal) | Upper/lower [bidiagonal matrix](https://en.wikipedia.org/wiki/Bidiagonal_matrix) |
| [`Diagonal`](#LinearAlgebra.Diagonal) | [Diagonal matrix](https://en.wikipedia.org/wiki/Diagonal_matrix) |
| [`UniformScaling`](#LinearAlgebra.UniformScaling) | [Uniform scaling operator](https://en.wikipedia.org/wiki/Uniform_scaling) |
###
[Elementary operations](#Elementary-operations)
| Matrix type | `+` | `-` | `*` | `\` | Other functions with optimized methods |
| --- | --- | --- | --- | --- | --- |
| [`Symmetric`](#LinearAlgebra.Symmetric) | | | | MV | [`inv`](#), [`sqrt`](#), [`exp`](#) |
| [`Hermitian`](#LinearAlgebra.Hermitian) | | | | MV | [`inv`](#), [`sqrt`](#), [`exp`](#) |
| [`UpperTriangular`](#LinearAlgebra.UpperTriangular) | | | MV | MV | [`inv`](#), [`det`](#LinearAlgebra.det) |
| [`UnitUpperTriangular`](#LinearAlgebra.UnitUpperTriangular) | | | MV | MV | [`inv`](#), [`det`](#LinearAlgebra.det) |
| [`LowerTriangular`](#LinearAlgebra.LowerTriangular) | | | MV | MV | [`inv`](#), [`det`](#LinearAlgebra.det) |
| [`UnitLowerTriangular`](#LinearAlgebra.UnitLowerTriangular) | | | MV | MV | [`inv`](#), [`det`](#LinearAlgebra.det) |
| [`UpperHessenberg`](#LinearAlgebra.UpperHessenberg) | | | | MM | [`inv`](#), [`det`](#LinearAlgebra.det) |
| [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal) | M | M | MS | MV | [`eigmax`](#LinearAlgebra.eigmax), [`eigmin`](#LinearAlgebra.eigmin) |
| [`Tridiagonal`](#LinearAlgebra.Tridiagonal) | M | M | MS | MV | |
| [`Bidiagonal`](#LinearAlgebra.Bidiagonal) | M | M | MS | MV | |
| [`Diagonal`](#LinearAlgebra.Diagonal) | M | M | MV | MV | [`inv`](#), [`det`](#LinearAlgebra.det), [`logdet`](#LinearAlgebra.logdet), [`/`](../../base/math/index#Base.:/) |
| [`UniformScaling`](#LinearAlgebra.UniformScaling) | M | M | MVS | MVS | [`/`](../../base/math/index#Base.:/) |
Legend:
| Key | Description |
| --- | --- |
| M (matrix) | An optimized method for matrix-matrix operations is available |
| V (vector) | An optimized method for matrix-vector operations is available |
| S (scalar) | An optimized method for matrix-scalar operations is available |
###
[Matrix factorizations](#Matrix-factorizations)
| Matrix type | LAPACK | [`eigen`](#LinearAlgebra.eigen) | [`eigvals`](#LinearAlgebra.eigvals) | [`eigvecs`](#LinearAlgebra.eigvecs) | [`svd`](#LinearAlgebra.svd) | [`svdvals`](#LinearAlgebra.svdvals) |
| --- | --- | --- | --- | --- | --- | --- |
| [`Symmetric`](#LinearAlgebra.Symmetric) | SY | | ARI | | | |
| [`Hermitian`](#LinearAlgebra.Hermitian) | HE | | ARI | | | |
| [`UpperTriangular`](#LinearAlgebra.UpperTriangular) | TR | A | A | A | | |
| [`UnitUpperTriangular`](#LinearAlgebra.UnitUpperTriangular) | TR | A | A | A | | |
| [`LowerTriangular`](#LinearAlgebra.LowerTriangular) | TR | A | A | A | | |
| [`UnitLowerTriangular`](#LinearAlgebra.UnitLowerTriangular) | TR | A | A | A | | |
| [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal) | ST | A | ARI | AV | | |
| [`Tridiagonal`](#LinearAlgebra.Tridiagonal) | GT | | | | | |
| [`Bidiagonal`](#LinearAlgebra.Bidiagonal) | BD | | | | A | A |
| [`Diagonal`](#LinearAlgebra.Diagonal) | DI | | A | | | |
Legend:
| Key | Description | Example |
| --- | --- | --- |
| A (all) | An optimized method to find all the characteristic values and/or vectors is available | e.g. `eigvals(M)` |
| R (range) | An optimized method to find the `il`th through the `ih`th characteristic values are available | `eigvals(M, il, ih)` |
| I (interval) | An optimized method to find the characteristic values in the interval [`vl`, `vh`] is available | `eigvals(M, vl, vh)` |
| V (vectors) | An optimized method to find the characteristic vectors corresponding to the characteristic values `x=[x1, x2,...]` is available | `eigvecs(M, x)` |
###
[The uniform scaling operator](#The-uniform-scaling-operator)
A [`UniformScaling`](#LinearAlgebra.UniformScaling) operator represents a scalar times the identity operator, `λ*I`. The identity operator `I` is defined as a constant and is an instance of `UniformScaling`. The size of these operators are generic and match the other matrix in the binary operations [`+`](../../base/math/index#Base.:+), [`-`](#), [`*`](#) and [`\`](#). For `A+I` and `A-I` this means that `A` must be square. Multiplication with the identity operator `I` is a noop (except for checking that the scaling factor is one) and therefore almost without overhead.
To see the `UniformScaling` operator in action:
```
julia> U = UniformScaling(2);
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> a + U
2×2 Matrix{Int64}:
3 2
3 6
julia> a * U
2×2 Matrix{Int64}:
2 4
6 8
julia> [a U]
2×4 Matrix{Int64}:
1 2 2 0
3 4 0 2
julia> b = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> b - U
ERROR: DimensionMismatch: matrix is not square: dimensions are (2, 3)
Stacktrace:
[...]
```
If you need to solve many systems of the form `(A+μI)x = b` for the same `A` and different `μ`, it might be beneficial to first compute the Hessenberg factorization `F` of `A` via the [`hessenberg`](#LinearAlgebra.hessenberg) function. Given `F`, Julia employs an efficient algorithm for `(F+μ*I) \ b` (equivalent to `(A+μ*I)x \ b`) and related operations like determinants.
[Matrix factorizations](#man-linalg-factorizations)
----------------------------------------------------
[Matrix factorizations (a.k.a. matrix decompositions)](https://en.wikipedia.org/wiki/Matrix_decomposition) compute the factorization of a matrix into a product of matrices, and are one of the central concepts in linear algebra.
The following table summarizes the types of matrix factorizations that have been implemented in Julia. Details of their associated methods can be found in the [Standard functions](#Standard-functions) section of the Linear Algebra documentation.
| Type | Description |
| --- | --- |
| `BunchKaufman` | Bunch-Kaufman factorization |
| `Cholesky` | [Cholesky factorization](https://en.wikipedia.org/wiki/Cholesky_decomposition) |
| `CholeskyPivoted` | [Pivoted](https://en.wikipedia.org/wiki/Pivot_element) Cholesky factorization |
| `LDLt` | [LDL(T) factorization](https://en.wikipedia.org/wiki/Cholesky_decomposition#LDL_decomposition) |
| `LU` | [LU factorization](https://en.wikipedia.org/wiki/LU_decomposition) |
| `QR` | [QR factorization](https://en.wikipedia.org/wiki/QR_decomposition) |
| `QRCompactWY` | Compact WY form of the QR factorization |
| `QRPivoted` | Pivoted [QR factorization](https://en.wikipedia.org/wiki/QR_decomposition) |
| `LQ` | [QR factorization](https://en.wikipedia.org/wiki/QR_decomposition) of `transpose(A)` |
| `Hessenberg` | [Hessenberg decomposition](http://mathworld.wolfram.com/HessenbergDecomposition.html) |
| `Eigen` | [Spectral decomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) |
| `GeneralizedEigen` | [Generalized spectral decomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix#Generalized_eigenvalue_problem) |
| `SVD` | [Singular value decomposition](https://en.wikipedia.org/wiki/Singular_value_decomposition) |
| `GeneralizedSVD` | [Generalized SVD](https://en.wikipedia.org/wiki/Generalized_singular_value_decomposition#Higher_order_version) |
| `Schur` | [Schur decomposition](https://en.wikipedia.org/wiki/Schur_decomposition) |
| `GeneralizedSchur` | [Generalized Schur decomposition](https://en.wikipedia.org/wiki/Schur_decomposition#Generalized_Schur_decomposition) |
[Standard functions](#Standard-functions)
------------------------------------------
Linear algebra functions in Julia are largely implemented by calling functions from [LAPACK](http://www.netlib.org/lapack/). Sparse matrix factorizations call functions from [SuiteSparse](http://suitesparse.com). Other sparse solvers are available as Julia packages.
###
`Base.:*`Method
```
*(A::AbstractMatrix, B::AbstractMatrix)
```
Matrix multiplication.
**Examples**
```
julia> [1 1; 0 1] * [1 0; 1 1]
2×2 Matrix{Int64}:
2 1
1 1
```
###
`Base.:\`Method
```
\(A, B)
```
Matrix division using a polyalgorithm. For input matrices `A` and `B`, the result `X` is such that `A*X == B` when `A` is square. The solver that is used depends upon the structure of `A`. If `A` is upper or lower triangular (or diagonal), no factorization of `A` is required and the system is solved with either forward or backward substitution. For non-triangular square matrices, an LU factorization is used.
For rectangular `A` the result is the minimum-norm least squares solution computed by a pivoted QR factorization of `A` and a rank estimate of `A` based on the R factor.
When `A` is sparse, a similar polyalgorithm is used. For indefinite matrices, the `LDLt` factorization does not use pivoting during the numerical factorization and therefore the procedure can fail even for invertible matrices.
See also: [`factorize`](#LinearAlgebra.factorize), [`pinv`](#LinearAlgebra.pinv).
**Examples**
```
julia> A = [1 0; 1 -2]; B = [32; -4];
julia> X = A \ B
2-element Vector{Float64}:
32.0
18.0
julia> A * X == B
true
```
###
`Base.:/`Method
```
A / B
```
Matrix right-division: `A / B` is equivalent to `(B' \ A')'` where [`\`](#Base.:%5C%5C-Tuple%7BAny,%20Any%7D) is the left-division operator. For square matrices, the result `X` is such that `A == X*B`.
See also: [`rdiv!`](../stdlib/linearalgebra/index#LinearAlgebra.rdiv!).
**Examples**
```
julia> A = Float64[1 4 5; 3 9 2]; B = Float64[1 4 2; 3 4 2; 8 7 1];
julia> X = A / B
2×3 Matrix{Float64}:
-0.65 3.75 -1.2
3.25 -2.75 1.0
julia> isapprox(A, X*B)
true
julia> isapprox(X, A*pinv(B))
true
```
###
`LinearAlgebra.SingularException`Type
```
SingularException
```
Exception thrown when the input matrix has one or more zero-valued eigenvalues, and is not invertible. A linear solve involving such a matrix cannot be computed. The `info` field indicates the location of (one of) the singular value(s).
###
`LinearAlgebra.PosDefException`Type
```
PosDefException
```
Exception thrown when the input matrix was not [positive definite](https://en.wikipedia.org/wiki/Definiteness_of_a_matrix). Some linear algebra functions and factorizations are only applicable to positive definite matrices. The `info` field indicates the location of (one of) the eigenvalue(s) which is (are) less than/equal to 0.
###
`LinearAlgebra.ZeroPivotException`Type
```
ZeroPivotException <: Exception
```
Exception thrown when a matrix factorization/solve encounters a zero in a pivot (diagonal) position and cannot proceed. This may *not* mean that the matrix is singular: it may be fruitful to switch to a diffent factorization such as pivoted LU that can re-order variables to eliminate spurious zero pivots. The `info` field indicates the location of (one of) the zero pivot(s).
###
`LinearAlgebra.dot`Function
```
dot(x, y)
x ⋅ y
```
Compute the dot product between two vectors. For complex vectors, the first vector is conjugated.
`dot` also works on arbitrary iterable objects, including arrays of any dimension, as long as `dot` is defined on the elements.
`dot` is semantically equivalent to `sum(dot(vx,vy) for (vx,vy) in zip(x, y))`, with the added restriction that the arguments must have equal lengths.
`x ⋅ y` (where `⋅` can be typed by tab-completing `\cdot` in the REPL) is a synonym for `dot(x, y)`.
**Examples**
```
julia> dot([1; 1], [2; 3])
5
julia> dot([im; im], [1; 1])
0 - 2im
julia> dot(1:5, 2:6)
70
julia> x = fill(2., (5,5));
julia> y = fill(3., (5,5));
julia> dot(x, y)
150.0
```
###
`LinearAlgebra.dot`Method
```
dot(x, A, y)
```
Compute the generalized dot product `dot(x, A*y)` between two vectors `x` and `y`, without storing the intermediate result of `A*y`. As for the two-argument [`dot(_,_)`](#LinearAlgebra.dot), this acts recursively. Moreover, for complex vectors, the first vector is conjugated.
Three-argument `dot` requires at least Julia 1.4.
**Examples**
```
julia> dot([1; 1], [1 2; 3 4], [2; 3])
26
julia> dot(1:5, reshape(1:25, 5, 5), 2:6)
4850
julia> ⋅(1:5, reshape(1:25, 5, 5), 2:6) == dot(1:5, reshape(1:25, 5, 5), 2:6)
true
```
###
`LinearAlgebra.cross`Function
```
cross(x, y)
×(x,y)
```
Compute the cross product of two 3-vectors.
**Examples**
```
julia> a = [0;1;0]
3-element Vector{Int64}:
0
1
0
julia> b = [0;0;1]
3-element Vector{Int64}:
0
0
1
julia> cross(a,b)
3-element Vector{Int64}:
1
0
0
```
###
`LinearAlgebra.factorize`Function
```
factorize(A)
```
Compute a convenient factorization of `A`, based upon the type of the input matrix. `factorize` checks `A` to see if it is symmetric/triangular/etc. if `A` is passed as a generic matrix. `factorize` checks every element of `A` to verify/rule out each property. It will short-circuit as soon as it can rule out symmetry/triangular structure. The return value can be reused for efficient solving of multiple systems. For example: `A=factorize(A); x=A\b; y=A\C`.
| Properties of `A` | type of factorization |
| --- | --- |
| Positive-definite | Cholesky (see [`cholesky`](#LinearAlgebra.cholesky)) |
| Dense Symmetric/Hermitian | Bunch-Kaufman (see [`bunchkaufman`](#LinearAlgebra.bunchkaufman)) |
| Sparse Symmetric/Hermitian | LDLt (see [`ldlt`](#LinearAlgebra.ldlt)) |
| Triangular | Triangular |
| Diagonal | Diagonal |
| Bidiagonal | Bidiagonal |
| Tridiagonal | LU (see [`lu`](#LinearAlgebra.lu)) |
| Symmetric real tridiagonal | LDLt (see [`ldlt`](#LinearAlgebra.ldlt)) |
| General square | LU (see [`lu`](#LinearAlgebra.lu)) |
| General non-square | QR (see [`qr`](#LinearAlgebra.qr)) |
If `factorize` is called on a Hermitian positive-definite matrix, for instance, then `factorize` will return a Cholesky factorization.
**Examples**
```
julia> A = Array(Bidiagonal(fill(1.0, (5, 5)), :U))
5×5 Matrix{Float64}:
1.0 1.0 0.0 0.0 0.0
0.0 1.0 1.0 0.0 0.0
0.0 0.0 1.0 1.0 0.0
0.0 0.0 0.0 1.0 1.0
0.0 0.0 0.0 0.0 1.0
julia> factorize(A) # factorize will check to see that A is already factorized
5×5 Bidiagonal{Float64, Vector{Float64}}:
1.0 1.0 ⋅ ⋅ ⋅
⋅ 1.0 1.0 ⋅ ⋅
⋅ ⋅ 1.0 1.0 ⋅
⋅ ⋅ ⋅ 1.0 1.0
⋅ ⋅ ⋅ ⋅ 1.0
```
This returns a `5×5 Bidiagonal{Float64}`, which can now be passed to other linear algebra functions (e.g. eigensolvers) which will use specialized methods for `Bidiagonal` types.
###
`LinearAlgebra.Diagonal`Type
```
Diagonal(V::AbstractVector)
```
Construct a matrix with `V` as its diagonal.
See also [`diag`](#LinearAlgebra.diag), [`diagm`](#LinearAlgebra.diagm).
**Examples**
```
julia> Diagonal([1, 10, 100])
3×3 Diagonal{Int64, Vector{Int64}}:
1 ⋅ ⋅
⋅ 10 ⋅
⋅ ⋅ 100
julia> diagm([7, 13])
2×2 Matrix{Int64}:
7 0
0 13
```
```
Diagonal(A::AbstractMatrix)
```
Construct a matrix from the diagonal of `A`.
**Examples**
```
julia> A = permutedims(reshape(1:15, 5, 3))
3×5 Matrix{Int64}:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
julia> Diagonal(A)
3×3 Diagonal{Int64, Vector{Int64}}:
1 ⋅ ⋅
⋅ 7 ⋅
⋅ ⋅ 13
julia> diag(A, 2)
3-element Vector{Int64}:
3
9
15
```
```
Diagonal{T}(undef, n)
```
Construct an uninitialized `Diagonal{T}` of length `n`. See `undef`.
###
`LinearAlgebra.Bidiagonal`Type
```
Bidiagonal(dv::V, ev::V, uplo::Symbol) where V <: AbstractVector
```
Constructs an upper (`uplo=:U`) or lower (`uplo=:L`) bidiagonal matrix using the given diagonal (`dv`) and off-diagonal (`ev`) vectors. The result is of type `Bidiagonal` and provides efficient specialized linear solvers, but may be converted into a regular matrix with [`convert(Array, _)`](../../base/base/index#Base.convert) (or `Array(_)` for short). The length of `ev` must be one less than the length of `dv`.
**Examples**
```
julia> dv = [1, 2, 3, 4]
4-element Vector{Int64}:
1
2
3
4
julia> ev = [7, 8, 9]
3-element Vector{Int64}:
7
8
9
julia> Bu = Bidiagonal(dv, ev, :U) # ev is on the first superdiagonal
4×4 Bidiagonal{Int64, Vector{Int64}}:
1 7 ⋅ ⋅
⋅ 2 8 ⋅
⋅ ⋅ 3 9
⋅ ⋅ ⋅ 4
julia> Bl = Bidiagonal(dv, ev, :L) # ev is on the first subdiagonal
4×4 Bidiagonal{Int64, Vector{Int64}}:
1 ⋅ ⋅ ⋅
7 2 ⋅ ⋅
⋅ 8 3 ⋅
⋅ ⋅ 9 4
```
```
Bidiagonal(A, uplo::Symbol)
```
Construct a `Bidiagonal` matrix from the main diagonal of `A` and its first super- (if `uplo=:U`) or sub-diagonal (if `uplo=:L`).
**Examples**
```
julia> A = [1 1 1 1; 2 2 2 2; 3 3 3 3; 4 4 4 4]
4×4 Matrix{Int64}:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
julia> Bidiagonal(A, :U) # contains the main diagonal and first superdiagonal of A
4×4 Bidiagonal{Int64, Vector{Int64}}:
1 1 ⋅ ⋅
⋅ 2 2 ⋅
⋅ ⋅ 3 3
⋅ ⋅ ⋅ 4
julia> Bidiagonal(A, :L) # contains the main diagonal and first subdiagonal of A
4×4 Bidiagonal{Int64, Vector{Int64}}:
1 ⋅ ⋅ ⋅
2 2 ⋅ ⋅
⋅ 3 3 ⋅
⋅ ⋅ 4 4
```
###
`LinearAlgebra.SymTridiagonal`Type
```
SymTridiagonal(dv::V, ev::V) where V <: AbstractVector
```
Construct a symmetric tridiagonal matrix from the diagonal (`dv`) and first sub/super-diagonal (`ev`), respectively. The result is of type `SymTridiagonal` and provides efficient specialized eigensolvers, but may be converted into a regular matrix with [`convert(Array, _)`](../../base/base/index#Base.convert) (or `Array(_)` for short).
For `SymTridiagonal` block matrices, the elements of `dv` are symmetrized. The argument `ev` is interpreted as the superdiagonal. Blocks from the subdiagonal are (materialized) transpose of the corresponding superdiagonal blocks.
**Examples**
```
julia> dv = [1, 2, 3, 4]
4-element Vector{Int64}:
1
2
3
4
julia> ev = [7, 8, 9]
3-element Vector{Int64}:
7
8
9
julia> SymTridiagonal(dv, ev)
4×4 SymTridiagonal{Int64, Vector{Int64}}:
1 7 ⋅ ⋅
7 2 8 ⋅
⋅ 8 3 9
⋅ ⋅ 9 4
julia> A = SymTridiagonal(fill([1 2; 3 4], 3), fill([1 2; 3 4], 2));
julia> A[1,1]
2×2 Symmetric{Int64, Matrix{Int64}}:
1 2
2 4
julia> A[1,2]
2×2 Matrix{Int64}:
1 2
3 4
julia> A[2,1]
2×2 Matrix{Int64}:
1 3
2 4
```
```
SymTridiagonal(A::AbstractMatrix)
```
Construct a symmetric tridiagonal matrix from the diagonal and first superdiagonal of the symmetric matrix `A`.
**Examples**
```
julia> A = [1 2 3; 2 4 5; 3 5 6]
3×3 Matrix{Int64}:
1 2 3
2 4 5
3 5 6
julia> SymTridiagonal(A)
3×3 SymTridiagonal{Int64, Vector{Int64}}:
1 2 ⋅
2 4 5
⋅ 5 6
julia> B = reshape([[1 2; 2 3], [1 2; 3 4], [1 3; 2 4], [1 2; 2 3]], 2, 2);
julia> SymTridiagonal(B)
2×2 SymTridiagonal{Matrix{Int64}, Vector{Matrix{Int64}}}:
[1 2; 2 3] [1 3; 2 4]
[1 2; 3 4] [1 2; 2 3]
```
###
`LinearAlgebra.Tridiagonal`Type
```
Tridiagonal(dl::V, d::V, du::V) where V <: AbstractVector
```
Construct a tridiagonal matrix from the first subdiagonal, diagonal, and first superdiagonal, respectively. The result is of type `Tridiagonal` and provides efficient specialized linear solvers, but may be converted into a regular matrix with [`convert(Array, _)`](../../base/base/index#Base.convert) (or `Array(_)` for short). The lengths of `dl` and `du` must be one less than the length of `d`.
**Examples**
```
julia> dl = [1, 2, 3];
julia> du = [4, 5, 6];
julia> d = [7, 8, 9, 0];
julia> Tridiagonal(dl, d, du)
4×4 Tridiagonal{Int64, Vector{Int64}}:
7 4 ⋅ ⋅
1 8 5 ⋅
⋅ 2 9 6
⋅ ⋅ 3 0
```
```
Tridiagonal(A)
```
Construct a tridiagonal matrix from the first sub-diagonal, diagonal and first super-diagonal of the matrix `A`.
**Examples**
```
julia> A = [1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4]
4×4 Matrix{Int64}:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
julia> Tridiagonal(A)
4×4 Tridiagonal{Int64, Vector{Int64}}:
1 2 ⋅ ⋅
1 2 3 ⋅
⋅ 2 3 4
⋅ ⋅ 3 4
```
###
`LinearAlgebra.Symmetric`Type
```
Symmetric(A, uplo=:U)
```
Construct a `Symmetric` view of the upper (if `uplo = :U`) or lower (if `uplo = :L`) triangle of the matrix `A`.
**Examples**
```
julia> A = [1 0 2 0 3; 0 4 0 5 0; 6 0 7 0 8; 0 9 0 1 0; 2 0 3 0 4]
5×5 Matrix{Int64}:
1 0 2 0 3
0 4 0 5 0
6 0 7 0 8
0 9 0 1 0
2 0 3 0 4
julia> Supper = Symmetric(A)
5×5 Symmetric{Int64, Matrix{Int64}}:
1 0 2 0 3
0 4 0 5 0
2 0 7 0 8
0 5 0 1 0
3 0 8 0 4
julia> Slower = Symmetric(A, :L)
5×5 Symmetric{Int64, Matrix{Int64}}:
1 0 6 0 2
0 4 0 9 0
6 0 7 0 3
0 9 0 1 0
2 0 3 0 4
```
Note that `Supper` will not be equal to `Slower` unless `A` is itself symmetric (e.g. if `A == transpose(A)`).
###
`LinearAlgebra.Hermitian`Type
```
Hermitian(A, uplo=:U)
```
Construct a `Hermitian` view of the upper (if `uplo = :U`) or lower (if `uplo = :L`) triangle of the matrix `A`.
**Examples**
```
julia> A = [1 0 2+2im 0 3-3im; 0 4 0 5 0; 6-6im 0 7 0 8+8im; 0 9 0 1 0; 2+2im 0 3-3im 0 4];
julia> Hupper = Hermitian(A)
5×5 Hermitian{Complex{Int64}, Matrix{Complex{Int64}}}:
1+0im 0+0im 2+2im 0+0im 3-3im
0+0im 4+0im 0+0im 5+0im 0+0im
2-2im 0+0im 7+0im 0+0im 8+8im
0+0im 5+0im 0+0im 1+0im 0+0im
3+3im 0+0im 8-8im 0+0im 4+0im
julia> Hlower = Hermitian(A, :L)
5×5 Hermitian{Complex{Int64}, Matrix{Complex{Int64}}}:
1+0im 0+0im 6+6im 0+0im 2-2im
0+0im 4+0im 0+0im 9+0im 0+0im
6-6im 0+0im 7+0im 0+0im 3+3im
0+0im 9+0im 0+0im 1+0im 0+0im
2+2im 0+0im 3-3im 0+0im 4+0im
```
Note that `Hupper` will not be equal to `Hlower` unless `A` is itself Hermitian (e.g. if `A == adjoint(A)`).
All non-real parts of the diagonal will be ignored.
```
Hermitian(fill(complex(1,1), 1, 1)) == fill(1, 1, 1)
```
###
`LinearAlgebra.LowerTriangular`Type
```
LowerTriangular(A::AbstractMatrix)
```
Construct a `LowerTriangular` view of the matrix `A`.
**Examples**
```
julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
3×3 Matrix{Float64}:
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
julia> LowerTriangular(A)
3×3 LowerTriangular{Float64, Matrix{Float64}}:
1.0 ⋅ ⋅
4.0 5.0 ⋅
7.0 8.0 9.0
```
###
`LinearAlgebra.UpperTriangular`Type
```
UpperTriangular(A::AbstractMatrix)
```
Construct an `UpperTriangular` view of the matrix `A`.
**Examples**
```
julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
3×3 Matrix{Float64}:
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
julia> UpperTriangular(A)
3×3 UpperTriangular{Float64, Matrix{Float64}}:
1.0 2.0 3.0
⋅ 5.0 6.0
⋅ ⋅ 9.0
```
###
`LinearAlgebra.UnitLowerTriangular`Type
```
UnitLowerTriangular(A::AbstractMatrix)
```
Construct a `UnitLowerTriangular` view of the matrix `A`. Such a view has the [`oneunit`](../../base/numbers/index#Base.oneunit) of the [`eltype`](../../base/collections/index#Base.eltype) of `A` on its diagonal.
**Examples**
```
julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
3×3 Matrix{Float64}:
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
julia> UnitLowerTriangular(A)
3×3 UnitLowerTriangular{Float64, Matrix{Float64}}:
1.0 ⋅ ⋅
4.0 1.0 ⋅
7.0 8.0 1.0
```
###
`LinearAlgebra.UnitUpperTriangular`Type
```
UnitUpperTriangular(A::AbstractMatrix)
```
Construct an `UnitUpperTriangular` view of the matrix `A`. Such a view has the [`oneunit`](../../base/numbers/index#Base.oneunit) of the [`eltype`](../../base/collections/index#Base.eltype) of `A` on its diagonal.
**Examples**
```
julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
3×3 Matrix{Float64}:
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
julia> UnitUpperTriangular(A)
3×3 UnitUpperTriangular{Float64, Matrix{Float64}}:
1.0 2.0 3.0
⋅ 1.0 6.0
⋅ ⋅ 1.0
```
###
`LinearAlgebra.UpperHessenberg`Type
```
UpperHessenberg(A::AbstractMatrix)
```
Construct an `UpperHessenberg` view of the matrix `A`. Entries of `A` below the first subdiagonal are ignored.
Efficient algorithms are implemented for `H \ b`, `det(H)`, and similar.
See also the [`hessenberg`](#LinearAlgebra.hessenberg) function to factor any matrix into a similar upper-Hessenberg matrix.
If `F::Hessenberg` is the factorization object, the unitary matrix can be accessed with `F.Q` and the Hessenberg matrix with `F.H`. When `Q` is extracted, the resulting type is the `HessenbergQ` object, and may be converted to a regular matrix with [`convert(Array, _)`](../../base/base/index#Base.convert) (or `Array(_)` for short).
Iterating the decomposition produces the factors `F.Q` and `F.H`.
**Examples**
```
julia> A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
4×4 Matrix{Int64}:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
julia> UpperHessenberg(A)
4×4 UpperHessenberg{Int64, Matrix{Int64}}:
1 2 3 4
5 6 7 8
⋅ 10 11 12
⋅ ⋅ 15 16
```
###
`LinearAlgebra.UniformScaling`Type
```
UniformScaling{T<:Number}
```
Generically sized uniform scaling operator defined as a scalar times the identity operator, `λ*I`. Although without an explicit `size`, it acts similarly to a matrix in many cases and includes support for some indexing. See also [`I`](#LinearAlgebra.I).
Indexing using ranges is available as of Julia 1.6.
**Examples**
```
julia> J = UniformScaling(2.)
UniformScaling{Float64}
2.0*I
julia> A = [1. 2.; 3. 4.]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> J*A
2×2 Matrix{Float64}:
2.0 4.0
6.0 8.0
julia> J[1:2, 1:2]
2×2 Matrix{Float64}:
2.0 0.0
0.0 2.0
```
###
`LinearAlgebra.I`Constant
```
I
```
An object of type [`UniformScaling`](#LinearAlgebra.UniformScaling), representing an identity matrix of any size.
**Examples**
```
julia> fill(1, (5,6)) * I == fill(1, (5,6))
true
julia> [1 2im 3; 1im 2 3] * I
2×3 Matrix{Complex{Int64}}:
1+0im 0+2im 3+0im
0+1im 2+0im 3+0im
```
###
`LinearAlgebra.UniformScaling`Method
```
(I::UniformScaling)(n::Integer)
```
Construct a `Diagonal` matrix from a `UniformScaling`.
This method is available as of Julia 1.2.
**Examples**
```
julia> I(3)
3×3 Diagonal{Bool, Vector{Bool}}:
1 ⋅ ⋅
⋅ 1 ⋅
⋅ ⋅ 1
julia> (0.7*I)(3)
3×3 Diagonal{Float64, Vector{Float64}}:
0.7 ⋅ ⋅
⋅ 0.7 ⋅
⋅ ⋅ 0.7
```
###
`LinearAlgebra.Factorization`Type
```
LinearAlgebra.Factorization
```
Abstract type for [matrix factorizations](https://en.wikipedia.org/wiki/Matrix_decomposition) a.k.a. matrix decompositions. See [online documentation](#man-linalg-factorizations) for a list of available matrix factorizations.
###
`LinearAlgebra.LU`Type
```
LU <: Factorization
```
Matrix factorization type of the `LU` factorization of a square matrix `A`. This is the return type of [`lu`](#LinearAlgebra.lu), the corresponding matrix factorization function.
The individual components of the factorization `F::LU` can be accessed via [`getproperty`](../../base/base/index#Base.getproperty):
| Component | Description |
| --- | --- |
| `F.L` | `L` (unit lower triangular) part of `LU` |
| `F.U` | `U` (upper triangular) part of `LU` |
| `F.p` | (right) permutation `Vector` |
| `F.P` | (right) permutation `Matrix` |
Iterating the factorization produces the components `F.L`, `F.U`, and `F.p`.
**Examples**
```
julia> A = [4 3; 6 3]
2×2 Matrix{Int64}:
4 3
6 3
julia> F = lu(A)
LU{Float64, Matrix{Float64}, Vector{Int64}}
L factor:
2×2 Matrix{Float64}:
1.0 0.0
0.666667 1.0
U factor:
2×2 Matrix{Float64}:
6.0 3.0
0.0 1.0
julia> F.L * F.U == A[F.p, :]
true
julia> l, u, p = lu(A); # destructuring via iteration
julia> l == F.L && u == F.U && p == F.p
true
```
###
`LinearAlgebra.lu`Function
```
lu(A::SparseMatrixCSC; check = true) -> F::UmfpackLU
```
Compute the LU factorization of a sparse matrix `A`.
For sparse `A` with real or complex element type, the return type of `F` is `UmfpackLU{Tv, Ti}`, with `Tv` = [`Float64`](../../base/numbers/index#Core.Float64) or `ComplexF64` respectively and `Ti` is an integer type ([`Int32`](../../base/numbers/index#Core.Int32) or [`Int64`](../../base/numbers/index#Core.Int64)).
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
The individual components of the factorization `F` can be accessed by indexing:
| Component | Description |
| --- | --- |
| `L` | `L` (lower triangular) part of `LU` |
| `U` | `U` (upper triangular) part of `LU` |
| `p` | right permutation `Vector` |
| `q` | left permutation `Vector` |
| `Rs` | `Vector` of scaling factors |
| `:` | `(L,U,p,q,Rs)` components |
The relation between `F` and `A` is
`F.L*F.U == (F.Rs .* A)[F.p, F.q]`
`F` further supports the following functions:
* [`\`](#)
* [`det`](#LinearAlgebra.det)
`lu(A::SparseMatrixCSC)` uses the UMFPACK library that is part of SuiteSparse. As this library only supports sparse matrices with [`Float64`](../../base/numbers/index#Core.Float64) or `ComplexF64` elements, `lu` converts `A` into a copy that is of type `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
```
lu(A, pivot = RowMaximum(); check = true) -> F::LU
```
Compute the LU factorization of `A`.
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
In most cases, if `A` is a subtype `S` of `AbstractMatrix{T}` with an element type `T` supporting `+`, `-`, `*` and `/`, the return type is `LU{T,S{T}}`. If pivoting is chosen (default) the element type should also support [`abs`](../../base/math/index#Base.abs) and [`<`](#). Pivoting can be turned off by passing `pivot = NoPivot()`.
The individual components of the factorization `F` can be accessed via [`getproperty`](../../base/base/index#Base.getproperty):
| Component | Description |
| --- | --- |
| `F.L` | `L` (lower triangular) part of `LU` |
| `F.U` | `U` (upper triangular) part of `LU` |
| `F.p` | (right) permutation `Vector` |
| `F.P` | (right) permutation `Matrix` |
Iterating the factorization produces the components `F.L`, `F.U`, and `F.p`.
The relationship between `F` and `A` is
`F.L*F.U == A[F.p, :]`
`F` further supports the following functions:
| Supported function | `LU` | `LU{T,Tridiagonal{T}}` |
| --- | --- | --- |
| [`/`](../../base/math/index#Base.:/) | ✓ | |
| [`\`](#) | ✓ | ✓ |
| [`inv`](#) | ✓ | ✓ |
| [`det`](#LinearAlgebra.det) | ✓ | ✓ |
| [`logdet`](#LinearAlgebra.logdet) | ✓ | ✓ |
| [`logabsdet`](#LinearAlgebra.logabsdet) | ✓ | ✓ |
| [`size`](../../base/arrays/index#Base.size) | ✓ | ✓ |
**Examples**
```
julia> A = [4 3; 6 3]
2×2 Matrix{Int64}:
4 3
6 3
julia> F = lu(A)
LU{Float64, Matrix{Float64}, Vector{Int64}}
L factor:
2×2 Matrix{Float64}:
1.0 0.0
0.666667 1.0
U factor:
2×2 Matrix{Float64}:
6.0 3.0
0.0 1.0
julia> F.L * F.U == A[F.p, :]
true
julia> l, u, p = lu(A); # destructuring via iteration
julia> l == F.L && u == F.U && p == F.p
true
```
###
`LinearAlgebra.lu!`Function
```
lu!(F::UmfpackLU, A::SparseMatrixCSC; check=true) -> F::UmfpackLU
```
Compute the LU factorization of a sparse matrix `A`, reusing the symbolic factorization of an already existing LU factorization stored in `F`. The sparse matrix `A` must have an identical nonzero pattern as the matrix used to create the LU factorization `F`, otherwise an error is thrown.
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
`lu!(F::UmfpackLU, A::SparseMatrixCSC)` uses the UMFPACK library that is part of SuiteSparse. As this library only supports sparse matrices with [`Float64`](../../base/numbers/index#Core.Float64) or `ComplexF64` elements, `lu!` converts `A` into a copy that is of type `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
`lu!` for `UmfpackLU` requires at least Julia 1.5.
**Examples**
```
julia> A = sparse(Float64[1.0 2.0; 0.0 3.0]);
julia> F = lu(A);
julia> B = sparse(Float64[1.0 1.0; 0.0 1.0]);
julia> lu!(F, B);
julia> F \ ones(2)
2-element Vector{Float64}:
0.0
1.0
```
```
lu!(A, pivot = RowMaximum(); check = true) -> LU
```
`lu!` is the same as [`lu`](#LinearAlgebra.lu), but saves space by overwriting the input `A`, instead of creating a copy. An [`InexactError`](../../base/base/index#Core.InexactError) exception is thrown if the factorization produces a number not representable by the element type of `A`, e.g. for integer types.
**Examples**
```
julia> A = [4. 3.; 6. 3.]
2×2 Matrix{Float64}:
4.0 3.0
6.0 3.0
julia> F = lu!(A)
LU{Float64, Matrix{Float64}, Vector{Int64}}
L factor:
2×2 Matrix{Float64}:
1.0 0.0
0.666667 1.0
U factor:
2×2 Matrix{Float64}:
6.0 3.0
0.0 1.0
julia> iA = [4 3; 6 3]
2×2 Matrix{Int64}:
4 3
6 3
julia> lu!(iA)
ERROR: InexactError: Int64(0.6666666666666666)
Stacktrace:
[...]
```
###
`LinearAlgebra.Cholesky`Type
```
Cholesky <: Factorization
```
Matrix factorization type of the Cholesky factorization of a dense symmetric/Hermitian positive definite matrix `A`. This is the return type of [`cholesky`](#LinearAlgebra.cholesky), the corresponding matrix factorization function.
The triangular Cholesky factor can be obtained from the factorization `F::Cholesky` via `F.L` and `F.U`, where `A ≈ F.U' * F.U ≈ F.L * F.L'`.
The following functions are available for `Cholesky` objects: [`size`](../../base/arrays/index#Base.size), [`\`](#), [`inv`](#), [`det`](#LinearAlgebra.det), [`logdet`](#LinearAlgebra.logdet) and [`isposdef`](#LinearAlgebra.isposdef).
Iterating the decomposition produces the components `L` and `U`.
**Examples**
```
julia> A = [4. 12. -16.; 12. 37. -43.; -16. -43. 98.]
3×3 Matrix{Float64}:
4.0 12.0 -16.0
12.0 37.0 -43.0
-16.0 -43.0 98.0
julia> C = cholesky(A)
Cholesky{Float64, Matrix{Float64}}
U factor:
3×3 UpperTriangular{Float64, Matrix{Float64}}:
2.0 6.0 -8.0
⋅ 1.0 5.0
⋅ ⋅ 3.0
julia> C.U
3×3 UpperTriangular{Float64, Matrix{Float64}}:
2.0 6.0 -8.0
⋅ 1.0 5.0
⋅ ⋅ 3.0
julia> C.L
3×3 LowerTriangular{Float64, Matrix{Float64}}:
2.0 ⋅ ⋅
6.0 1.0 ⋅
-8.0 5.0 3.0
julia> C.L * C.U == A
true
julia> l, u = C; # destructuring via iteration
julia> l == C.L && u == C.U
true
```
###
`LinearAlgebra.CholeskyPivoted`Type
```
CholeskyPivoted
```
Matrix factorization type of the pivoted Cholesky factorization of a dense symmetric/Hermitian positive semi-definite matrix `A`. This is the return type of [`cholesky(_, ::RowMaximum)`](#LinearAlgebra.cholesky), the corresponding matrix factorization function.
The triangular Cholesky factor can be obtained from the factorization `F::CholeskyPivoted` via `F.L` and `F.U`, and the permutation via `F.p`, where `A[F.p, F.p] ≈ Ur' * Ur ≈ Lr * Lr'` with `Ur = F.U[1:F.rank, :]` and `Lr = F.L[:, 1:F.rank]`, or alternatively `A ≈ Up' * Up ≈ Lp * Lp'` with `Up = F.U[1:F.rank, invperm(F.p)]` and `Lp = F.L[invperm(F.p), 1:F.rank]`.
The following functions are available for `CholeskyPivoted` objects: [`size`](../../base/arrays/index#Base.size), [`\`](#), [`inv`](#), [`det`](#LinearAlgebra.det), and [`rank`](#LinearAlgebra.rank).
Iterating the decomposition produces the components `L` and `U`.
**Examples**
```
julia> X = [1.0, 2.0, 3.0, 4.0];
julia> A = X * X';
julia> C = cholesky(A, RowMaximum(), check = false)
CholeskyPivoted{Float64, Matrix{Float64}, Vector{Int64}}
U factor with rank 1:
4×4 UpperTriangular{Float64, Matrix{Float64}}:
4.0 2.0 3.0 1.0
⋅ 0.0 6.0 2.0
⋅ ⋅ 9.0 3.0
⋅ ⋅ ⋅ 1.0
permutation:
4-element Vector{Int64}:
4
2
3
1
julia> C.U[1:C.rank, :]' * C.U[1:C.rank, :] ≈ A[C.p, C.p]
true
julia> l, u = C; # destructuring via iteration
julia> l == C.L && u == C.U
true
```
###
`LinearAlgebra.cholesky`Function
```
cholesky(A, NoPivot(); check = true) -> Cholesky
```
Compute the Cholesky factorization of a dense symmetric positive definite matrix `A` and return a [`Cholesky`](#LinearAlgebra.Cholesky) factorization. The matrix `A` can either be a [`Symmetric`](#LinearAlgebra.Symmetric) or [`Hermitian`](#LinearAlgebra.Hermitian) [`AbstractMatrix`](../../base/arrays/index#Base.AbstractMatrix) or a *perfectly* symmetric or Hermitian `AbstractMatrix`.
The triangular Cholesky factor can be obtained from the factorization `F` via `F.L` and `F.U`, where `A ≈ F.U' * F.U ≈ F.L * F.L'`.
The following functions are available for `Cholesky` objects: [`size`](../../base/arrays/index#Base.size), [`\`](#), [`inv`](#), [`det`](#LinearAlgebra.det), [`logdet`](#LinearAlgebra.logdet) and [`isposdef`](#LinearAlgebra.isposdef).
If you have a matrix `A` that is slightly non-Hermitian due to roundoff errors in its construction, wrap it in `Hermitian(A)` before passing it to `cholesky` in order to treat it as perfectly Hermitian.
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
**Examples**
```
julia> A = [4. 12. -16.; 12. 37. -43.; -16. -43. 98.]
3×3 Matrix{Float64}:
4.0 12.0 -16.0
12.0 37.0 -43.0
-16.0 -43.0 98.0
julia> C = cholesky(A)
Cholesky{Float64, Matrix{Float64}}
U factor:
3×3 UpperTriangular{Float64, Matrix{Float64}}:
2.0 6.0 -8.0
⋅ 1.0 5.0
⋅ ⋅ 3.0
julia> C.U
3×3 UpperTriangular{Float64, Matrix{Float64}}:
2.0 6.0 -8.0
⋅ 1.0 5.0
⋅ ⋅ 3.0
julia> C.L
3×3 LowerTriangular{Float64, Matrix{Float64}}:
2.0 ⋅ ⋅
6.0 1.0 ⋅
-8.0 5.0 3.0
julia> C.L * C.U == A
true
```
```
cholesky(A, RowMaximum(); tol = 0.0, check = true) -> CholeskyPivoted
```
Compute the pivoted Cholesky factorization of a dense symmetric positive semi-definite matrix `A` and return a [`CholeskyPivoted`](#LinearAlgebra.CholeskyPivoted) factorization. The matrix `A` can either be a [`Symmetric`](#LinearAlgebra.Symmetric) or [`Hermitian`](#LinearAlgebra.Hermitian) [`AbstractMatrix`](../../base/arrays/index#Base.AbstractMatrix) or a *perfectly* symmetric or Hermitian `AbstractMatrix`.
The triangular Cholesky factor can be obtained from the factorization `F` via `F.L` and `F.U`, and the permutation via `F.p`, where `A[F.p, F.p] ≈ Ur' * Ur ≈ Lr * Lr'` with `Ur = F.U[1:F.rank, :]` and `Lr = F.L[:, 1:F.rank]`, or alternatively `A ≈ Up' * Up ≈ Lp * Lp'` with `Up = F.U[1:F.rank, invperm(F.p)]` and `Lp = F.L[invperm(F.p), 1:F.rank]`.
The following functions are available for `CholeskyPivoted` objects: [`size`](../../base/arrays/index#Base.size), [`\`](#), [`inv`](#), [`det`](#LinearAlgebra.det), and [`rank`](#LinearAlgebra.rank).
The argument `tol` determines the tolerance for determining the rank. For negative values, the tolerance is the machine precision.
If you have a matrix `A` that is slightly non-Hermitian due to roundoff errors in its construction, wrap it in `Hermitian(A)` before passing it to `cholesky` in order to treat it as perfectly Hermitian.
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
**Examples**
```
julia> X = [1.0, 2.0, 3.0, 4.0];
julia> A = X * X';
julia> C = cholesky(A, RowMaximum(), check = false)
CholeskyPivoted{Float64, Matrix{Float64}, Vector{Int64}}
U factor with rank 1:
4×4 UpperTriangular{Float64, Matrix{Float64}}:
4.0 2.0 3.0 1.0
⋅ 0.0 6.0 2.0
⋅ ⋅ 9.0 3.0
⋅ ⋅ ⋅ 1.0
permutation:
4-element Vector{Int64}:
4
2
3
1
julia> C.U[1:C.rank, :]' * C.U[1:C.rank, :] ≈ A[C.p, C.p]
true
julia> l, u = C; # destructuring via iteration
julia> l == C.L && u == C.U
true
```
```
cholesky(A::SparseMatrixCSC; shift = 0.0, check = true, perm = nothing) -> CHOLMOD.Factor
```
Compute the Cholesky factorization of a sparse positive definite matrix `A`. `A` must be a [`SparseMatrixCSC`](../sparsearrays/index#SparseArrays.SparseMatrixCSC) or a [`Symmetric`](#LinearAlgebra.Symmetric)/[`Hermitian`](#LinearAlgebra.Hermitian) view of a `SparseMatrixCSC`. Note that even if `A` doesn't have the type tag, it must still be symmetric or Hermitian. If `perm` is not given, a fill-reducing permutation is used. `F = cholesky(A)` is most frequently used to solve systems of equations with `F\b`, but also the methods [`diag`](#LinearAlgebra.diag), [`det`](#LinearAlgebra.det), and [`logdet`](#LinearAlgebra.logdet) are defined for `F`. You can also extract individual factors from `F`, using `F.L`. However, since pivoting is on by default, the factorization is internally represented as `A == P'*L*L'*P` with a permutation matrix `P`; using just `L` without accounting for `P` will give incorrect answers. To include the effects of permutation, it's typically preferable to extract "combined" factors like `PtL = F.PtL` (the equivalent of `P'*L`) and `LtP = F.UP` (the equivalent of `L'*P`).
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
Setting the optional `shift` keyword argument computes the factorization of `A+shift*I` instead of `A`. If the `perm` argument is provided, it should be a permutation of `1:size(A,1)` giving the ordering to use (instead of CHOLMOD's default AMD ordering).
**Examples**
In the following example, the fill-reducing permutation used is `[3, 2, 1]`. If `perm` is set to `1:3` to enforce no permutation, the number of nonzero elements in the factor is 6.
```
julia> A = [2 1 1; 1 2 0; 1 0 2]
3×3 Matrix{Int64}:
2 1 1
1 2 0
1 0 2
julia> C = cholesky(sparse(A))
SuiteSparse.CHOLMOD.Factor{Float64}
type: LLt
method: simplicial
maxnnz: 5
nnz: 5
success: true
julia> C.p
3-element Vector{Int64}:
3
2
1
julia> L = sparse(C.L);
julia> Matrix(L)
3×3 Matrix{Float64}:
1.41421 0.0 0.0
0.0 1.41421 0.0
0.707107 0.707107 1.0
julia> L * L' ≈ A[C.p, C.p]
true
julia> P = sparse(1:3, C.p, ones(3))
3×3 SparseMatrixCSC{Float64, Int64} with 3 stored entries:
⋅ ⋅ 1.0
⋅ 1.0 ⋅
1.0 ⋅ ⋅
julia> P' * L * L' * P ≈ A
true
julia> C = cholesky(sparse(A), perm=1:3)
SuiteSparse.CHOLMOD.Factor{Float64}
type: LLt
method: simplicial
maxnnz: 6
nnz: 6
success: true
julia> L = sparse(C.L);
julia> Matrix(L)
3×3 Matrix{Float64}:
1.41421 0.0 0.0
0.707107 1.22474 0.0
0.707107 -0.408248 1.1547
julia> L * L' ≈ A
true
```
This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
Many other functions from CHOLMOD are wrapped but not exported from the `Base.SparseArrays.CHOLMOD` module.
###
`LinearAlgebra.cholesky!`Function
```
cholesky!(A::AbstractMatrix, NoPivot(); check = true) -> Cholesky
```
The same as [`cholesky`](#LinearAlgebra.cholesky), but saves space by overwriting the input `A`, instead of creating a copy. An [`InexactError`](../../base/base/index#Core.InexactError) exception is thrown if the factorization produces a number not representable by the element type of `A`, e.g. for integer types.
**Examples**
```
julia> A = [1 2; 2 50]
2×2 Matrix{Int64}:
1 2
2 50
julia> cholesky!(A)
ERROR: InexactError: Int64(6.782329983125268)
Stacktrace:
[...]
```
```
cholesky!(A::AbstractMatrix, RowMaximum(); tol = 0.0, check = true) -> CholeskyPivoted
```
The same as [`cholesky`](#LinearAlgebra.cholesky), but saves space by overwriting the input `A`, instead of creating a copy. An [`InexactError`](../../base/base/index#Core.InexactError) exception is thrown if the factorization produces a number not representable by the element type of `A`, e.g. for integer types.
```
cholesky!(F::CHOLMOD.Factor, A::SparseMatrixCSC; shift = 0.0, check = true) -> CHOLMOD.Factor
```
Compute the Cholesky ($LL'$) factorization of `A`, reusing the symbolic factorization `F`. `A` must be a [`SparseMatrixCSC`](../sparsearrays/index#SparseArrays.SparseMatrixCSC) or a [`Symmetric`](#LinearAlgebra.Symmetric)/ [`Hermitian`](#LinearAlgebra.Hermitian) view of a `SparseMatrixCSC`. Note that even if `A` doesn't have the type tag, it must still be symmetric or Hermitian.
See also [`cholesky`](#LinearAlgebra.cholesky).
This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
###
`LinearAlgebra.lowrankupdate`Function
```
lowrankupdate(C::Cholesky, v::AbstractVector) -> CC::Cholesky
```
Update a Cholesky factorization `C` with the vector `v`. If `A = C.U'C.U` then `CC = cholesky(C.U'C.U + v*v')` but the computation of `CC` only uses `O(n^2)` operations.
###
`LinearAlgebra.lowrankdowndate`Function
```
lowrankdowndate(C::Cholesky, v::AbstractVector) -> CC::Cholesky
```
Downdate a Cholesky factorization `C` with the vector `v`. If `A = C.U'C.U` then `CC = cholesky(C.U'C.U - v*v')` but the computation of `CC` only uses `O(n^2)` operations.
###
`LinearAlgebra.lowrankupdate!`Function
```
lowrankupdate!(C::Cholesky, v::AbstractVector) -> CC::Cholesky
```
Update a Cholesky factorization `C` with the vector `v`. If `A = C.U'C.U` then `CC = cholesky(C.U'C.U + v*v')` but the computation of `CC` only uses `O(n^2)` operations. The input factorization `C` is updated in place such that on exit `C == CC`. The vector `v` is destroyed during the computation.
###
`LinearAlgebra.lowrankdowndate!`Function
```
lowrankdowndate!(C::Cholesky, v::AbstractVector) -> CC::Cholesky
```
Downdate a Cholesky factorization `C` with the vector `v`. If `A = C.U'C.U` then `CC = cholesky(C.U'C.U - v*v')` but the computation of `CC` only uses `O(n^2)` operations. The input factorization `C` is updated in place such that on exit `C == CC`. The vector `v` is destroyed during the computation.
###
`LinearAlgebra.LDLt`Type
```
LDLt <: Factorization
```
Matrix factorization type of the `LDLt` factorization of a real [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal) matrix `S` such that `S = L*Diagonal(d)*L'`, where `L` is a [`UnitLowerTriangular`](#LinearAlgebra.UnitLowerTriangular) matrix and `d` is a vector. The main use of an `LDLt` factorization `F = ldlt(S)` is to solve the linear system of equations `Sx = b` with `F\b`. This is the return type of [`ldlt`](#LinearAlgebra.ldlt), the corresponding matrix factorization function.
The individual components of the factorization `F::LDLt` can be accessed via `getproperty`:
| Component | Description |
| --- | --- |
| `F.L` | `L` (unit lower triangular) part of `LDLt` |
| `F.D` | `D` (diagonal) part of `LDLt` |
| `F.Lt` | `Lt` (unit upper triangular) part of `LDLt` |
| `F.d` | diagonal values of `D` as a `Vector` |
**Examples**
```
julia> S = SymTridiagonal([3., 4., 5.], [1., 2.])
3×3 SymTridiagonal{Float64, Vector{Float64}}:
3.0 1.0 ⋅
1.0 4.0 2.0
⋅ 2.0 5.0
julia> F = ldlt(S)
LDLt{Float64, SymTridiagonal{Float64, Vector{Float64}}}
L factor:
3×3 UnitLowerTriangular{Float64, SymTridiagonal{Float64, Vector{Float64}}}:
1.0 ⋅ ⋅
0.333333 1.0 ⋅
0.0 0.545455 1.0
D factor:
3×3 Diagonal{Float64, Vector{Float64}}:
3.0 ⋅ ⋅
⋅ 3.66667 ⋅
⋅ ⋅ 3.90909
```
###
`LinearAlgebra.ldlt`Function
```
ldlt(S::SymTridiagonal) -> LDLt
```
Compute an `LDLt` (i.e., $LDL^T$) factorization of the real symmetric tridiagonal matrix `S` such that `S = L*Diagonal(d)*L'` where `L` is a unit lower triangular matrix and `d` is a vector. The main use of an `LDLt` factorization `F = ldlt(S)` is to solve the linear system of equations `Sx = b` with `F\b`.
See also [`bunchkaufman`](#LinearAlgebra.bunchkaufman) for a similar, but pivoted, factorization of arbitrary symmetric or Hermitian matrices.
**Examples**
```
julia> S = SymTridiagonal([3., 4., 5.], [1., 2.])
3×3 SymTridiagonal{Float64, Vector{Float64}}:
3.0 1.0 ⋅
1.0 4.0 2.0
⋅ 2.0 5.0
julia> ldltS = ldlt(S);
julia> b = [6., 7., 8.];
julia> ldltS \ b
3-element Vector{Float64}:
1.7906976744186047
0.627906976744186
1.3488372093023255
julia> S \ b
3-element Vector{Float64}:
1.7906976744186047
0.627906976744186
1.3488372093023255
```
```
ldlt(A::SparseMatrixCSC; shift = 0.0, check = true, perm=nothing) -> CHOLMOD.Factor
```
Compute the $LDL'$ factorization of a sparse matrix `A`. `A` must be a [`SparseMatrixCSC`](../sparsearrays/index#SparseArrays.SparseMatrixCSC) or a [`Symmetric`](#LinearAlgebra.Symmetric)/[`Hermitian`](#LinearAlgebra.Hermitian) view of a `SparseMatrixCSC`. Note that even if `A` doesn't have the type tag, it must still be symmetric or Hermitian. A fill-reducing permutation is used. `F = ldlt(A)` is most frequently used to solve systems of equations `A*x = b` with `F\b`. The returned factorization object `F` also supports the methods [`diag`](#LinearAlgebra.diag), [`det`](#LinearAlgebra.det), [`logdet`](#LinearAlgebra.logdet), and [`inv`](#). You can extract individual factors from `F` using `F.L`. However, since pivoting is on by default, the factorization is internally represented as `A == P'*L*D*L'*P` with a permutation matrix `P`; using just `L` without accounting for `P` will give incorrect answers. To include the effects of permutation, it is typically preferable to extract "combined" factors like `PtL = F.PtL` (the equivalent of `P'*L`) and `LtP = F.UP` (the equivalent of `L'*P`). The complete list of supported factors is `:L, :PtL, :D, :UP, :U, :LD, :DU, :PtLD, :DUP`.
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
Setting the optional `shift` keyword argument computes the factorization of `A+shift*I` instead of `A`. If the `perm` argument is provided, it should be a permutation of `1:size(A,1)` giving the ordering to use (instead of CHOLMOD's default AMD ordering).
This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
Many other functions from CHOLMOD are wrapped but not exported from the `Base.SparseArrays.CHOLMOD` module.
###
`LinearAlgebra.ldlt!`Function
```
ldlt!(S::SymTridiagonal) -> LDLt
```
Same as [`ldlt`](#LinearAlgebra.ldlt), but saves space by overwriting the input `S`, instead of creating a copy.
**Examples**
```
julia> S = SymTridiagonal([3., 4., 5.], [1., 2.])
3×3 SymTridiagonal{Float64, Vector{Float64}}:
3.0 1.0 ⋅
1.0 4.0 2.0
⋅ 2.0 5.0
julia> ldltS = ldlt!(S);
julia> ldltS === S
false
julia> S
3×3 SymTridiagonal{Float64, Vector{Float64}}:
3.0 0.333333 ⋅
0.333333 3.66667 0.545455
⋅ 0.545455 3.90909
```
```
ldlt!(F::CHOLMOD.Factor, A::SparseMatrixCSC; shift = 0.0, check = true) -> CHOLMOD.Factor
```
Compute the $LDL'$ factorization of `A`, reusing the symbolic factorization `F`. `A` must be a [`SparseMatrixCSC`](../sparsearrays/index#SparseArrays.SparseMatrixCSC) or a [`Symmetric`](#LinearAlgebra.Symmetric)/[`Hermitian`](#LinearAlgebra.Hermitian) view of a `SparseMatrixCSC`. Note that even if `A` doesn't have the type tag, it must still be symmetric or Hermitian.
See also [`ldlt`](#LinearAlgebra.ldlt).
This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
###
`LinearAlgebra.QR`Type
```
QR <: Factorization
```
A QR matrix factorization stored in a packed format, typically obtained from [`qr`](#LinearAlgebra.qr). If $A$ is an `m`×`n` matrix, then
\[A = Q R\]
where $Q$ is an orthogonal/unitary matrix and $R$ is upper triangular. The matrix $Q$ is stored as a sequence of Householder reflectors $v\_i$ and coefficients $\tau\_i$ where:
\[Q = \prod\_{i=1}^{\min(m,n)} (I - \tau\_i v\_i v\_i^T).\]
Iterating the decomposition produces the components `Q` and `R`.
The object has two fields:
* `factors` is an `m`×`n` matrix.
+ The upper triangular part contains the elements of $R$, that is `R = triu(F.factors)` for a `QR` object `F`.
+ The subdiagonal part contains the reflectors $v\_i$ stored in a packed format where $v\_i$ is the $i$th column of the matrix `V = I + tril(F.factors, -1)`.
* `τ` is a vector of length `min(m,n)` containing the coefficients $au\_i$.
###
`LinearAlgebra.QRCompactWY`Type
```
QRCompactWY <: Factorization
```
A QR matrix factorization stored in a compact blocked format, typically obtained from [`qr`](#LinearAlgebra.qr). If $A$ is an `m`×`n` matrix, then
\[A = Q R\]
where $Q$ is an orthogonal/unitary matrix and $R$ is upper triangular. It is similar to the [`QR`](#LinearAlgebra.QR) format except that the orthogonal/unitary matrix $Q$ is stored in *Compact WY* format [[Schreiber1989]](#footnote-Schreiber1989). For the block size $n\_b$, it is stored as a `m`×`n` lower trapezoidal matrix $V$ and a matrix $T = (T\_1 \; T\_2 \; ... \; T\_{b-1} \; T\_b')$ composed of $b = \lceil \min(m,n) / n\_b \rceil$ upper triangular matrices $T\_j$ of size $n\_b$×$n\_b$ ($j = 1, ..., b-1$) and an upper trapezoidal $n\_b$×$\min(m,n) - (b-1) n\_b$ matrix $T\_b'$ ($j=b$) whose upper square part denoted with $T\_b$ satisfying
\[Q = \prod\_{i=1}^{\min(m,n)} (I - \tau\_i v\_i v\_i^T) = \prod\_{j=1}^{b} (I - V\_j T\_j V\_j^T)\]
such that $v\_i$ is the $i$th column of $V$, $\tau\_i$ is the $i$th element of `[diag(T_1); diag(T_2); …; diag(T_b)]`, and $(V\_1 \; V\_2 \; ... \; V\_b)$ is the left `m`×`min(m, n)` block of $V$. When constructed using [`qr`](#LinearAlgebra.qr), the block size is given by $n\_b = \min(m, n, 36)$.
Iterating the decomposition produces the components `Q` and `R`.
The object has two fields:
* `factors`, as in the [`QR`](#LinearAlgebra.QR) type, is an `m`×`n` matrix.
+ The upper triangular part contains the elements of $R$, that is `R = triu(F.factors)` for a `QR` object `F`.
+ The subdiagonal part contains the reflectors $v\_i$ stored in a packed format such that `V = I + tril(F.factors, -1)`.
* `T` is a $n\_b$-by-$\min(m,n)$ matrix as described above. The subdiagonal elements for each triangular matrix $T\_j$ are ignored.
This format should not to be confused with the older *WY* representation [[Bischof1987]](#footnote-Bischof1987).
###
`LinearAlgebra.QRPivoted`Type
```
QRPivoted <: Factorization
```
A QR matrix factorization with column pivoting in a packed format, typically obtained from [`qr`](#LinearAlgebra.qr). If $A$ is an `m`×`n` matrix, then
\[A P = Q R\]
where $P$ is a permutation matrix, $Q$ is an orthogonal/unitary matrix and $R$ is upper triangular. The matrix $Q$ is stored as a sequence of Householder reflectors:
\[Q = \prod\_{i=1}^{\min(m,n)} (I - \tau\_i v\_i v\_i^T).\]
Iterating the decomposition produces the components `Q`, `R`, and `p`.
The object has three fields:
* `factors` is an `m`×`n` matrix.
+ The upper triangular part contains the elements of $R$, that is `R = triu(F.factors)` for a `QR` object `F`.
+ The subdiagonal part contains the reflectors $v\_i$ stored in a packed format where $v\_i$ is the $i$th column of the matrix `V = I + tril(F.factors, -1)`.
* `τ` is a vector of length `min(m,n)` containing the coefficients $au\_i$.
* `jpvt` is an integer vector of length `n` corresponding to the permutation $P$.
###
`LinearAlgebra.qr`Function
```
qr(A, pivot = NoPivot(); blocksize) -> F
```
Compute the QR factorization of the matrix `A`: an orthogonal (or unitary if `A` is complex-valued) matrix `Q`, and an upper triangular matrix `R` such that
\[A = Q R\]
The returned object `F` stores the factorization in a packed format:
* if `pivot == ColumnNorm()` then `F` is a [`QRPivoted`](#LinearAlgebra.QRPivoted) object,
* otherwise if the element type of `A` is a BLAS type ([`Float32`](../../base/numbers/index#Core.Float32), [`Float64`](../../base/numbers/index#Core.Float64), `ComplexF32` or `ComplexF64`), then `F` is a [`QRCompactWY`](#LinearAlgebra.QRCompactWY) object,
* otherwise `F` is a [`QR`](#LinearAlgebra.QR) object.
The individual components of the decomposition `F` can be retrieved via property accessors:
* `F.Q`: the orthogonal/unitary matrix `Q`
* `F.R`: the upper triangular matrix `R`
* `F.p`: the permutation vector of the pivot ([`QRPivoted`](#LinearAlgebra.QRPivoted) only)
* `F.P`: the permutation matrix of the pivot ([`QRPivoted`](#LinearAlgebra.QRPivoted) only)
Iterating the decomposition produces the components `Q`, `R`, and if extant `p`.
The following functions are available for the `QR` objects: [`inv`](#), [`size`](../../base/arrays/index#Base.size), and [`\`](#). When `A` is rectangular, `\` will return a least squares solution and if the solution is not unique, the one with smallest norm is returned. When `A` is not full rank, factorization with (column) pivoting is required to obtain a minimum norm solution.
Multiplication with respect to either full/square or non-full/square `Q` is allowed, i.e. both `F.Q*F.R` and `F.Q*A` are supported. A `Q` matrix can be converted into a regular matrix with [`Matrix`](../../base/arrays/index#Base.Matrix). This operation returns the "thin" Q factor, i.e., if `A` is `m`×`n` with `m>=n`, then `Matrix(F.Q)` yields an `m`×`n` matrix with orthonormal columns. To retrieve the "full" Q factor, an `m`×`m` orthogonal matrix, use `F.Q*I`. If `m<=n`, then `Matrix(F.Q)` yields an `m`×`m` orthogonal matrix.
The block size for QR decomposition can be specified by keyword argument `blocksize :: Integer` when `pivot == NoPivot()` and `A isa StridedMatrix{<:BlasFloat}`. It is ignored when `blocksize > minimum(size(A))`. See [`QRCompactWY`](#LinearAlgebra.QRCompactWY).
The `blocksize` keyword argument requires Julia 1.4 or later.
**Examples**
```
julia> A = [3.0 -6.0; 4.0 -8.0; 0.0 1.0]
3×2 Matrix{Float64}:
3.0 -6.0
4.0 -8.0
0.0 1.0
julia> F = qr(A)
LinearAlgebra.QRCompactWY{Float64, Matrix{Float64}, Matrix{Float64}}
Q factor:
3×3 LinearAlgebra.QRCompactWYQ{Float64, Matrix{Float64}, Matrix{Float64}}:
-0.6 0.0 0.8
-0.8 0.0 -0.6
0.0 -1.0 0.0
R factor:
2×2 Matrix{Float64}:
-5.0 10.0
0.0 -1.0
julia> F.Q * F.R == A
true
```
`qr` returns multiple types because LAPACK uses several representations that minimize the memory storage requirements of products of Householder elementary reflectors, so that the `Q` and `R` matrices can be stored compactly rather as two separate dense matrices.
```
qr(A::SparseMatrixCSC; tol=_default_tol(A), ordering=ORDERING_DEFAULT) -> QRSparse
```
Compute the `QR` factorization of a sparse matrix `A`. Fill-reducing row and column permutations are used such that `F.R = F.Q'*A[F.prow,F.pcol]`. The main application of this type is to solve least squares or underdetermined problems with [`\`](#). The function calls the C library SPQR.
`qr(A::SparseMatrixCSC)` uses the SPQR library that is part of SuiteSparse. As this library only supports sparse matrices with [`Float64`](../../base/numbers/index#Core.Float64) or `ComplexF64` elements, as of Julia v1.4 `qr` converts `A` into a copy that is of type `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{ComplexF64}` as appropriate.
**Examples**
```
julia> A = sparse([1,2,3,4], [1,1,2,2], [1.0,1.0,1.0,1.0])
4×2 SparseMatrixCSC{Float64, Int64} with 4 stored entries:
1.0 ⋅
1.0 ⋅
⋅ 1.0
⋅ 1.0
julia> qr(A)
SuiteSparse.SPQR.QRSparse{Float64, Int64}
Q factor:
4×4 SuiteSparse.SPQR.QRSparseQ{Float64, Int64}:
-0.707107 0.0 0.0 -0.707107
0.0 -0.707107 -0.707107 0.0
0.0 -0.707107 0.707107 0.0
-0.707107 0.0 0.0 0.707107
R factor:
2×2 SparseMatrixCSC{Float64, Int64} with 2 stored entries:
-1.41421 ⋅
⋅ -1.41421
Row permutation:
4-element Vector{Int64}:
1
3
4
2
Column permutation:
2-element Vector{Int64}:
1
2
```
###
`LinearAlgebra.qr!`Function
```
qr!(A, pivot = NoPivot(); blocksize)
```
`qr!` is the same as [`qr`](#LinearAlgebra.qr) when `A` is a subtype of [`StridedMatrix`](../../base/arrays/index#Base.StridedMatrix), but saves space by overwriting the input `A`, instead of creating a copy. An [`InexactError`](../../base/base/index#Core.InexactError) exception is thrown if the factorization produces a number not representable by the element type of `A`, e.g. for integer types.
The `blocksize` keyword argument requires Julia 1.4 or later.
**Examples**
```
julia> a = [1. 2.; 3. 4.]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> qr!(a)
LinearAlgebra.QRCompactWY{Float64, Matrix{Float64}, Matrix{Float64}}
Q factor:
2×2 LinearAlgebra.QRCompactWYQ{Float64, Matrix{Float64}, Matrix{Float64}}:
-0.316228 -0.948683
-0.948683 0.316228
R factor:
2×2 Matrix{Float64}:
-3.16228 -4.42719
0.0 -0.632456
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> qr!(a)
ERROR: InexactError: Int64(3.1622776601683795)
Stacktrace:
[...]
```
###
`LinearAlgebra.LQ`Type
```
LQ <: Factorization
```
Matrix factorization type of the `LQ` factorization of a matrix `A`. The `LQ` decomposition is the [`QR`](#LinearAlgebra.QR) decomposition of `transpose(A)`. This is the return type of [`lq`](#LinearAlgebra.lq), the corresponding matrix factorization function.
If `S::LQ` is the factorization object, the lower triangular component can be obtained via `S.L`, and the orthogonal/unitary component via `S.Q`, such that `A ≈ S.L*S.Q`.
Iterating the decomposition produces the components `S.L` and `S.Q`.
**Examples**
```
julia> A = [5. 7.; -2. -4.]
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> S = lq(A)
LQ{Float64, Matrix{Float64}, Vector{Float64}}
L factor:
2×2 Matrix{Float64}:
-8.60233 0.0
4.41741 -0.697486
Q factor:
2×2 LinearAlgebra.LQPackedQ{Float64, Matrix{Float64}, Vector{Float64}}:
-0.581238 -0.813733
-0.813733 0.581238
julia> S.L * S.Q
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> l, q = S; # destructuring via iteration
julia> l == S.L && q == S.Q
true
```
###
`LinearAlgebra.lq`Function
```
lq(A) -> S::LQ
```
Compute the LQ decomposition of `A`. The decomposition's lower triangular component can be obtained from the [`LQ`](#LinearAlgebra.LQ) object `S` via `S.L`, and the orthogonal/unitary component via `S.Q`, such that `A ≈ S.L*S.Q`.
Iterating the decomposition produces the components `S.L` and `S.Q`.
The LQ decomposition is the QR decomposition of `transpose(A)`, and it is useful in order to compute the minimum-norm solution `lq(A) \ b` to an underdetermined system of equations (`A` has more columns than rows, but has full row rank).
**Examples**
```
julia> A = [5. 7.; -2. -4.]
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> S = lq(A)
LQ{Float64, Matrix{Float64}, Vector{Float64}}
L factor:
2×2 Matrix{Float64}:
-8.60233 0.0
4.41741 -0.697486
Q factor:
2×2 LinearAlgebra.LQPackedQ{Float64, Matrix{Float64}, Vector{Float64}}:
-0.581238 -0.813733
-0.813733 0.581238
julia> S.L * S.Q
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> l, q = S; # destructuring via iteration
julia> l == S.L && q == S.Q
true
```
###
`LinearAlgebra.lq!`Function
```
lq!(A) -> LQ
```
Compute the [`LQ`](#LinearAlgebra.LQ) factorization of `A`, using the input matrix as a workspace. See also [`lq`](#LinearAlgebra.lq).
###
`LinearAlgebra.BunchKaufman`Type
```
BunchKaufman <: Factorization
```
Matrix factorization type of the Bunch-Kaufman factorization of a symmetric or Hermitian matrix `A` as `P'UDU'P` or `P'LDL'P`, depending on whether the upper (the default) or the lower triangle is stored in `A`. If `A` is complex symmetric then `U'` and `L'` denote the unconjugated transposes, i.e. `transpose(U)` and `transpose(L)`, respectively. This is the return type of [`bunchkaufman`](#LinearAlgebra.bunchkaufman), the corresponding matrix factorization function.
If `S::BunchKaufman` is the factorization object, the components can be obtained via `S.D`, `S.U` or `S.L` as appropriate given `S.uplo`, and `S.p`.
Iterating the decomposition produces the components `S.D`, `S.U` or `S.L` as appropriate given `S.uplo`, and `S.p`.
**Examples**
```
julia> A = [1 2; 2 3]
2×2 Matrix{Int64}:
1 2
2 3
julia> S = bunchkaufman(A) # A gets wrapped internally by Symmetric(A)
BunchKaufman{Float64, Matrix{Float64}, Vector{Int64}}
D factor:
2×2 Tridiagonal{Float64, Vector{Float64}}:
-0.333333 0.0
0.0 3.0
U factor:
2×2 UnitUpperTriangular{Float64, Matrix{Float64}}:
1.0 0.666667
⋅ 1.0
permutation:
2-element Vector{Int64}:
1
2
julia> d, u, p = S; # destructuring via iteration
julia> d == S.D && u == S.U && p == S.p
true
julia> S = bunchkaufman(Symmetric(A, :L))
BunchKaufman{Float64, Matrix{Float64}, Vector{Int64}}
D factor:
2×2 Tridiagonal{Float64, Vector{Float64}}:
3.0 0.0
0.0 -0.333333
L factor:
2×2 UnitLowerTriangular{Float64, Matrix{Float64}}:
1.0 ⋅
0.666667 1.0
permutation:
2-element Vector{Int64}:
2
1
```
###
`LinearAlgebra.bunchkaufman`Function
```
bunchkaufman(A, rook::Bool=false; check = true) -> S::BunchKaufman
```
Compute the Bunch-Kaufman [[Bunch1977]](#footnote-Bunch1977) factorization of a symmetric or Hermitian matrix `A` as `P'*U*D*U'*P` or `P'*L*D*L'*P`, depending on which triangle is stored in `A`, and return a [`BunchKaufman`](#LinearAlgebra.BunchKaufman) object. Note that if `A` is complex symmetric then `U'` and `L'` denote the unconjugated transposes, i.e. `transpose(U)` and `transpose(L)`.
Iterating the decomposition produces the components `S.D`, `S.U` or `S.L` as appropriate given `S.uplo`, and `S.p`.
If `rook` is `true`, rook pivoting is used. If `rook` is false, rook pivoting is not used.
When `check = true`, an error is thrown if the decomposition fails. When `check = false`, responsibility for checking the decomposition's validity (via [`issuccess`](#LinearAlgebra.issuccess)) lies with the user.
The following functions are available for `BunchKaufman` objects: [`size`](../../base/arrays/index#Base.size), `\`, [`inv`](#), [`issymmetric`](#LinearAlgebra.issymmetric), [`ishermitian`](#LinearAlgebra.ishermitian), [`getindex`](../../base/collections/index#Base.getindex).
**Examples**
```
julia> A = [1 2; 2 3]
2×2 Matrix{Int64}:
1 2
2 3
julia> S = bunchkaufman(A) # A gets wrapped internally by Symmetric(A)
BunchKaufman{Float64, Matrix{Float64}, Vector{Int64}}
D factor:
2×2 Tridiagonal{Float64, Vector{Float64}}:
-0.333333 0.0
0.0 3.0
U factor:
2×2 UnitUpperTriangular{Float64, Matrix{Float64}}:
1.0 0.666667
⋅ 1.0
permutation:
2-element Vector{Int64}:
1
2
julia> d, u, p = S; # destructuring via iteration
julia> d == S.D && u == S.U && p == S.p
true
julia> S.U*S.D*S.U' - S.P*A*S.P'
2×2 Matrix{Float64}:
0.0 0.0
0.0 0.0
julia> S = bunchkaufman(Symmetric(A, :L))
BunchKaufman{Float64, Matrix{Float64}, Vector{Int64}}
D factor:
2×2 Tridiagonal{Float64, Vector{Float64}}:
3.0 0.0
0.0 -0.333333
L factor:
2×2 UnitLowerTriangular{Float64, Matrix{Float64}}:
1.0 ⋅
0.666667 1.0
permutation:
2-element Vector{Int64}:
2
1
julia> S.L*S.D*S.L' - A[S.p, S.p]
2×2 Matrix{Float64}:
0.0 0.0
0.0 0.0
```
###
`LinearAlgebra.bunchkaufman!`Function
```
bunchkaufman!(A, rook::Bool=false; check = true) -> BunchKaufman
```
`bunchkaufman!` is the same as [`bunchkaufman`](#LinearAlgebra.bunchkaufman), but saves space by overwriting the input `A`, instead of creating a copy.
###
`LinearAlgebra.Eigen`Type
```
Eigen <: Factorization
```
Matrix factorization type of the eigenvalue/spectral decomposition of a square matrix `A`. This is the return type of [`eigen`](#LinearAlgebra.eigen), the corresponding matrix factorization function.
If `F::Eigen` is the factorization object, the eigenvalues can be obtained via `F.values` and the eigenvectors as the columns of the matrix `F.vectors`. (The `k`th eigenvector can be obtained from the slice `F.vectors[:, k]`.)
Iterating the decomposition produces the components `F.values` and `F.vectors`.
**Examples**
```
julia> F = eigen([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
Eigen{Float64, Float64, Matrix{Float64}, Vector{Float64}}
values:
3-element Vector{Float64}:
1.0
3.0
18.0
vectors:
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> F.values
3-element Vector{Float64}:
1.0
3.0
18.0
julia> F.vectors
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> vals, vecs = F; # destructuring via iteration
julia> vals == F.values && vecs == F.vectors
true
```
###
`LinearAlgebra.GeneralizedEigen`Type
```
GeneralizedEigen <: Factorization
```
Matrix factorization type of the generalized eigenvalue/spectral decomposition of `A` and `B`. This is the return type of [`eigen`](#LinearAlgebra.eigen), the corresponding matrix factorization function, when called with two matrix arguments.
If `F::GeneralizedEigen` is the factorization object, the eigenvalues can be obtained via `F.values` and the eigenvectors as the columns of the matrix `F.vectors`. (The `k`th eigenvector can be obtained from the slice `F.vectors[:, k]`.)
Iterating the decomposition produces the components `F.values` and `F.vectors`.
**Examples**
```
julia> A = [1 0; 0 -1]
2×2 Matrix{Int64}:
1 0
0 -1
julia> B = [0 1; 1 0]
2×2 Matrix{Int64}:
0 1
1 0
julia> F = eigen(A, B)
GeneralizedEigen{ComplexF64, ComplexF64, Matrix{ComplexF64}, Vector{ComplexF64}}
values:
2-element Vector{ComplexF64}:
0.0 - 1.0im
0.0 + 1.0im
vectors:
2×2 Matrix{ComplexF64}:
0.0+1.0im 0.0-1.0im
-1.0+0.0im -1.0-0.0im
julia> F.values
2-element Vector{ComplexF64}:
0.0 - 1.0im
0.0 + 1.0im
julia> F.vectors
2×2 Matrix{ComplexF64}:
0.0+1.0im 0.0-1.0im
-1.0+0.0im -1.0-0.0im
julia> vals, vecs = F; # destructuring via iteration
julia> vals == F.values && vecs == F.vectors
true
```
###
`LinearAlgebra.eigvals`Function
```
eigvals(A; permute::Bool=true, scale::Bool=true, sortby) -> values
```
Return the eigenvalues of `A`.
For general non-symmetric matrices it is possible to specify how the matrix is balanced before the eigenvalue calculation. The `permute`, `scale`, and `sortby` keywords are the same as for [`eigen`](#LinearAlgebra.eigen).
**Examples**
```
julia> diag_matrix = [1 0; 0 4]
2×2 Matrix{Int64}:
1 0
0 4
julia> eigvals(diag_matrix)
2-element Vector{Float64}:
1.0
4.0
```
For a scalar input, `eigvals` will return a scalar.
**Example**
```
julia> eigvals(-2)
-2
```
```
eigvals(A, B) -> values
```
Compute the generalized eigenvalues of `A` and `B`.
**Examples**
```
julia> A = [1 0; 0 -1]
2×2 Matrix{Int64}:
1 0
0 -1
julia> B = [0 1; 1 0]
2×2 Matrix{Int64}:
0 1
1 0
julia> eigvals(A,B)
2-element Vector{ComplexF64}:
0.0 - 1.0im
0.0 + 1.0im
```
```
eigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values
```
Return the eigenvalues of `A`. It is possible to calculate only a subset of the eigenvalues by specifying a [`UnitRange`](../../base/collections/index#Base.UnitRange) `irange` covering indices of the sorted eigenvalues, e.g. the 2nd to 8th eigenvalues.
**Examples**
```
julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])
3×3 SymTridiagonal{Float64, Vector{Float64}}:
1.0 2.0 ⋅
2.0 2.0 3.0
⋅ 3.0 1.0
julia> eigvals(A, 2:2)
1-element Vector{Float64}:
0.9999999999999996
julia> eigvals(A)
3-element Vector{Float64}:
-2.1400549446402604
1.0000000000000002
5.140054944640259
```
```
eigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values
```
Return the eigenvalues of `A`. It is possible to calculate only a subset of the eigenvalues by specifying a pair `vl` and `vu` for the lower and upper boundaries of the eigenvalues.
**Examples**
```
julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])
3×3 SymTridiagonal{Float64, Vector{Float64}}:
1.0 2.0 ⋅
2.0 2.0 3.0
⋅ 3.0 1.0
julia> eigvals(A, -1, 2)
1-element Vector{Float64}:
1.0000000000000009
julia> eigvals(A)
3-element Vector{Float64}:
-2.1400549446402604
1.0000000000000002
5.140054944640259
```
###
`LinearAlgebra.eigvals!`Function
```
eigvals!(A; permute::Bool=true, scale::Bool=true, sortby) -> values
```
Same as [`eigvals`](#LinearAlgebra.eigvals), but saves space by overwriting the input `A`, instead of creating a copy. The `permute`, `scale`, and `sortby` keywords are the same as for [`eigen`](#LinearAlgebra.eigen).
The input matrix `A` will not contain its eigenvalues after `eigvals!` is called on it - `A` is used as a workspace.
**Examples**
```
julia> A = [1. 2.; 3. 4.]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> eigvals!(A)
2-element Vector{Float64}:
-0.3722813232690143
5.372281323269014
julia> A
2×2 Matrix{Float64}:
-0.372281 -1.0
0.0 5.37228
```
```
eigvals!(A, B; sortby) -> values
```
Same as [`eigvals`](#LinearAlgebra.eigvals), but saves space by overwriting the input `A` (and `B`), instead of creating copies.
The input matrices `A` and `B` will not contain their eigenvalues after `eigvals!` is called. They are used as workspaces.
**Examples**
```
julia> A = [1. 0.; 0. -1.]
2×2 Matrix{Float64}:
1.0 0.0
0.0 -1.0
julia> B = [0. 1.; 1. 0.]
2×2 Matrix{Float64}:
0.0 1.0
1.0 0.0
julia> eigvals!(A, B)
2-element Vector{ComplexF64}:
0.0 - 1.0im
0.0 + 1.0im
julia> A
2×2 Matrix{Float64}:
-0.0 -1.0
1.0 -0.0
julia> B
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
```
```
eigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values
```
Same as [`eigvals`](#LinearAlgebra.eigvals), but saves space by overwriting the input `A`, instead of creating a copy. `irange` is a range of eigenvalue *indices* to search for - for instance, the 2nd to 8th eigenvalues.
```
eigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values
```
Same as [`eigvals`](#LinearAlgebra.eigvals), but saves space by overwriting the input `A`, instead of creating a copy. `vl` is the lower bound of the interval to search for eigenvalues, and `vu` is the upper bound.
###
`LinearAlgebra.eigmax`Function
```
eigmax(A; permute::Bool=true, scale::Bool=true)
```
Return the largest eigenvalue of `A`. The option `permute=true` permutes the matrix to become closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to make rows and columns more equal in norm. Note that if the eigenvalues of `A` are complex, this method will fail, since complex numbers cannot be sorted.
**Examples**
```
julia> A = [0 im; -im 0]
2×2 Matrix{Complex{Int64}}:
0+0im 0+1im
0-1im 0+0im
julia> eigmax(A)
1.0
julia> A = [0 im; -1 0]
2×2 Matrix{Complex{Int64}}:
0+0im 0+1im
-1+0im 0+0im
julia> eigmax(A)
ERROR: DomainError with Complex{Int64}[0+0im 0+1im; -1+0im 0+0im]:
`A` cannot have complex eigenvalues.
Stacktrace:
[...]
```
###
`LinearAlgebra.eigmin`Function
```
eigmin(A; permute::Bool=true, scale::Bool=true)
```
Return the smallest eigenvalue of `A`. The option `permute=true` permutes the matrix to become closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to make rows and columns more equal in norm. Note that if the eigenvalues of `A` are complex, this method will fail, since complex numbers cannot be sorted.
**Examples**
```
julia> A = [0 im; -im 0]
2×2 Matrix{Complex{Int64}}:
0+0im 0+1im
0-1im 0+0im
julia> eigmin(A)
-1.0
julia> A = [0 im; -1 0]
2×2 Matrix{Complex{Int64}}:
0+0im 0+1im
-1+0im 0+0im
julia> eigmin(A)
ERROR: DomainError with Complex{Int64}[0+0im 0+1im; -1+0im 0+0im]:
`A` cannot have complex eigenvalues.
Stacktrace:
[...]
```
###
`LinearAlgebra.eigvecs`Function
```
eigvecs(A::SymTridiagonal[, eigvals]) -> Matrix
```
Return a matrix `M` whose columns are the eigenvectors of `A`. (The `k`th eigenvector can be obtained from the slice `M[:, k]`.)
If the optional vector of eigenvalues `eigvals` is specified, `eigvecs` returns the specific corresponding eigenvectors.
**Examples**
```
julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])
3×3 SymTridiagonal{Float64, Vector{Float64}}:
1.0 2.0 ⋅
2.0 2.0 3.0
⋅ 3.0 1.0
julia> eigvals(A)
3-element Vector{Float64}:
-2.1400549446402604
1.0000000000000002
5.140054944640259
julia> eigvecs(A)
3×3 Matrix{Float64}:
0.418304 -0.83205 0.364299
-0.656749 -7.39009e-16 0.754109
0.627457 0.5547 0.546448
julia> eigvecs(A, [1.])
3×1 Matrix{Float64}:
0.8320502943378438
4.263514128092366e-17
-0.5547001962252291
```
```
eigvecs(A; permute::Bool=true, scale::Bool=true, `sortby`) -> Matrix
```
Return a matrix `M` whose columns are the eigenvectors of `A`. (The `k`th eigenvector can be obtained from the slice `M[:, k]`.) The `permute`, `scale`, and `sortby` keywords are the same as for [`eigen`](#LinearAlgebra.eigen).
**Examples**
```
julia> eigvecs([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
```
```
eigvecs(A, B) -> Matrix
```
Return a matrix `M` whose columns are the generalized eigenvectors of `A` and `B`. (The `k`th eigenvector can be obtained from the slice `M[:, k]`.)
**Examples**
```
julia> A = [1 0; 0 -1]
2×2 Matrix{Int64}:
1 0
0 -1
julia> B = [0 1; 1 0]
2×2 Matrix{Int64}:
0 1
1 0
julia> eigvecs(A, B)
2×2 Matrix{ComplexF64}:
0.0+1.0im 0.0-1.0im
-1.0+0.0im -1.0-0.0im
```
###
`LinearAlgebra.eigen`Function
```
eigen(A; permute::Bool=true, scale::Bool=true, sortby) -> Eigen
```
Compute the eigenvalue decomposition of `A`, returning an [`Eigen`](#LinearAlgebra.Eigen) factorization object `F` which contains the eigenvalues in `F.values` and the eigenvectors in the columns of the matrix `F.vectors`. (The `k`th eigenvector can be obtained from the slice `F.vectors[:, k]`.)
Iterating the decomposition produces the components `F.values` and `F.vectors`.
The following functions are available for `Eigen` objects: [`inv`](#), [`det`](#LinearAlgebra.det), and [`isposdef`](#LinearAlgebra.isposdef).
For general nonsymmetric matrices it is possible to specify how the matrix is balanced before the eigenvector calculation. The option `permute=true` permutes the matrix to become closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to make rows and columns more equal in norm. The default is `true` for both options.
By default, the eigenvalues and vectors are sorted lexicographically by `(real(λ),imag(λ))`. A different comparison function `by(λ)` can be passed to `sortby`, or you can pass `sortby=nothing` to leave the eigenvalues in an arbitrary order. Some special matrix types (e.g. [`Diagonal`](#LinearAlgebra.Diagonal) or [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal)) may implement their own sorting convention and not accept a `sortby` keyword.
**Examples**
```
julia> F = eigen([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
Eigen{Float64, Float64, Matrix{Float64}, Vector{Float64}}
values:
3-element Vector{Float64}:
1.0
3.0
18.0
vectors:
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> F.values
3-element Vector{Float64}:
1.0
3.0
18.0
julia> F.vectors
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> vals, vecs = F; # destructuring via iteration
julia> vals == F.values && vecs == F.vectors
true
```
```
eigen(A, B; sortby) -> GeneralizedEigen
```
Compute the generalized eigenvalue decomposition of `A` and `B`, returning a [`GeneralizedEigen`](#LinearAlgebra.GeneralizedEigen) factorization object `F` which contains the generalized eigenvalues in `F.values` and the generalized eigenvectors in the columns of the matrix `F.vectors`. (The `k`th generalized eigenvector can be obtained from the slice `F.vectors[:, k]`.)
Iterating the decomposition produces the components `F.values` and `F.vectors`.
By default, the eigenvalues and vectors are sorted lexicographically by `(real(λ),imag(λ))`. A different comparison function `by(λ)` can be passed to `sortby`, or you can pass `sortby=nothing` to leave the eigenvalues in an arbitrary order.
**Examples**
```
julia> A = [1 0; 0 -1]
2×2 Matrix{Int64}:
1 0
0 -1
julia> B = [0 1; 1 0]
2×2 Matrix{Int64}:
0 1
1 0
julia> F = eigen(A, B);
julia> F.values
2-element Vector{ComplexF64}:
0.0 - 1.0im
0.0 + 1.0im
julia> F.vectors
2×2 Matrix{ComplexF64}:
0.0+1.0im 0.0-1.0im
-1.0+0.0im -1.0-0.0im
julia> vals, vecs = F; # destructuring via iteration
julia> vals == F.values && vecs == F.vectors
true
```
```
eigen(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> Eigen
```
Compute the eigenvalue decomposition of `A`, returning an [`Eigen`](#LinearAlgebra.Eigen) factorization object `F` which contains the eigenvalues in `F.values` and the eigenvectors in the columns of the matrix `F.vectors`. (The `k`th eigenvector can be obtained from the slice `F.vectors[:, k]`.)
Iterating the decomposition produces the components `F.values` and `F.vectors`.
The following functions are available for `Eigen` objects: [`inv`](#), [`det`](#LinearAlgebra.det), and [`isposdef`](#LinearAlgebra.isposdef).
The [`UnitRange`](../../base/collections/index#Base.UnitRange) `irange` specifies indices of the sorted eigenvalues to search for.
If `irange` is not `1:n`, where `n` is the dimension of `A`, then the returned factorization will be a *truncated* factorization.
```
eigen(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> Eigen
```
Compute the eigenvalue decomposition of `A`, returning an [`Eigen`](#LinearAlgebra.Eigen) factorization object `F` which contains the eigenvalues in `F.values` and the eigenvectors in the columns of the matrix `F.vectors`. (The `k`th eigenvector can be obtained from the slice `F.vectors[:, k]`.)
Iterating the decomposition produces the components `F.values` and `F.vectors`.
The following functions are available for `Eigen` objects: [`inv`](#), [`det`](#LinearAlgebra.det), and [`isposdef`](#LinearAlgebra.isposdef).
`vl` is the lower bound of the window of eigenvalues to search for, and `vu` is the upper bound.
If [`vl`, `vu`] does not contain all eigenvalues of `A`, then the returned factorization will be a *truncated* factorization.
###
`LinearAlgebra.eigen!`Function
```
eigen!(A; permute, scale, sortby)
eigen!(A, B; sortby)
```
Same as [`eigen`](#LinearAlgebra.eigen), but saves space by overwriting the input `A` (and `B`), instead of creating a copy.
###
`LinearAlgebra.Hessenberg`Type
```
Hessenberg <: Factorization
```
A `Hessenberg` object represents the Hessenberg factorization `QHQ'` of a square matrix, or a shift `Q(H+μI)Q'` thereof, which is produced by the [`hessenberg`](#LinearAlgebra.hessenberg) function.
###
`LinearAlgebra.hessenberg`Function
```
hessenberg(A) -> Hessenberg
```
Compute the Hessenberg decomposition of `A` and return a `Hessenberg` object. If `F` is the factorization object, the unitary matrix can be accessed with `F.Q` (of type `LinearAlgebra.HessenbergQ`) and the Hessenberg matrix with `F.H` (of type [`UpperHessenberg`](#LinearAlgebra.UpperHessenberg)), either of which may be converted to a regular matrix with `Matrix(F.H)` or `Matrix(F.Q)`.
If `A` is [`Hermitian`](#LinearAlgebra.Hermitian) or real-[`Symmetric`](#LinearAlgebra.Symmetric), then the Hessenberg decomposition produces a real-symmetric tridiagonal matrix and `F.H` is of type [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal).
Note that the shifted factorization `A+μI = Q (H+μI) Q'` can be constructed efficiently by `F + μ*I` using the [`UniformScaling`](#LinearAlgebra.UniformScaling) object [`I`](#LinearAlgebra.I), which creates a new `Hessenberg` object with shared storage and a modified shift. The shift of a given `F` is obtained by `F.μ`. This is useful because multiple shifted solves `(F + μ*I) \ b` (for different `μ` and/or `b`) can be performed efficiently once `F` is created.
Iterating the decomposition produces the factors `F.Q, F.H, F.μ`.
**Examples**
```
julia> A = [4. 9. 7.; 4. 4. 1.; 4. 3. 2.]
3×3 Matrix{Float64}:
4.0 9.0 7.0
4.0 4.0 1.0
4.0 3.0 2.0
julia> F = hessenberg(A)
Hessenberg{Float64, UpperHessenberg{Float64, Matrix{Float64}}, Matrix{Float64}, Vector{Float64}, Bool}
Q factor:
3×3 LinearAlgebra.HessenbergQ{Float64, Matrix{Float64}, Vector{Float64}, false}:
1.0 0.0 0.0
0.0 -0.707107 -0.707107
0.0 -0.707107 0.707107
H factor:
3×3 UpperHessenberg{Float64, Matrix{Float64}}:
4.0 -11.3137 -1.41421
-5.65685 5.0 2.0
⋅ -8.88178e-16 1.0
julia> F.Q * F.H * F.Q'
3×3 Matrix{Float64}:
4.0 9.0 7.0
4.0 4.0 1.0
4.0 3.0 2.0
julia> q, h = F; # destructuring via iteration
julia> q == F.Q && h == F.H
true
```
###
`LinearAlgebra.hessenberg!`Function
```
hessenberg!(A) -> Hessenberg
```
`hessenberg!` is the same as [`hessenberg`](#LinearAlgebra.hessenberg), but saves space by overwriting the input `A`, instead of creating a copy.
###
`LinearAlgebra.Schur`Type
```
Schur <: Factorization
```
Matrix factorization type of the Schur factorization of a matrix `A`. This is the return type of [`schur(_)`](#LinearAlgebra.schur), the corresponding matrix factorization function.
If `F::Schur` is the factorization object, the (quasi) triangular Schur factor can be obtained via either `F.Schur` or `F.T` and the orthogonal/unitary Schur vectors via `F.vectors` or `F.Z` such that `A = F.vectors * F.Schur * F.vectors'`. The eigenvalues of `A` can be obtained with `F.values`.
Iterating the decomposition produces the components `F.T`, `F.Z`, and `F.values`.
**Examples**
```
julia> A = [5. 7.; -2. -4.]
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> F = schur(A)
Schur{Float64, Matrix{Float64}, Vector{Float64}}
T factor:
2×2 Matrix{Float64}:
3.0 9.0
0.0 -2.0
Z factor:
2×2 Matrix{Float64}:
0.961524 0.274721
-0.274721 0.961524
eigenvalues:
2-element Vector{Float64}:
3.0
-2.0
julia> F.vectors * F.Schur * F.vectors'
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> t, z, vals = F; # destructuring via iteration
julia> t == F.T && z == F.Z && vals == F.values
true
```
###
`LinearAlgebra.GeneralizedSchur`Type
```
GeneralizedSchur <: Factorization
```
Matrix factorization type of the generalized Schur factorization of two matrices `A` and `B`. This is the return type of [`schur(_, _)`](#LinearAlgebra.schur), the corresponding matrix factorization function.
If `F::GeneralizedSchur` is the factorization object, the (quasi) triangular Schur factors can be obtained via `F.S` and `F.T`, the left unitary/orthogonal Schur vectors via `F.left` or `F.Q`, and the right unitary/orthogonal Schur vectors can be obtained with `F.right` or `F.Z` such that `A=F.left*F.S*F.right'` and `B=F.left*F.T*F.right'`. The generalized eigenvalues of `A` and `B` can be obtained with `F.α./F.β`.
Iterating the decomposition produces the components `F.S`, `F.T`, `F.Q`, `F.Z`, `F.α`, and `F.β`.
###
`LinearAlgebra.schur`Function
```
schur(A) -> F::Schur
```
Computes the Schur factorization of the matrix `A`. The (quasi) triangular Schur factor can be obtained from the `Schur` object `F` with either `F.Schur` or `F.T` and the orthogonal/unitary Schur vectors can be obtained with `F.vectors` or `F.Z` such that `A = F.vectors * F.Schur * F.vectors'`. The eigenvalues of `A` can be obtained with `F.values`.
For real `A`, the Schur factorization is "quasitriangular", which means that it is upper-triangular except with 2×2 diagonal blocks for any conjugate pair of complex eigenvalues; this allows the factorization to be purely real even when there are complex eigenvalues. To obtain the (complex) purely upper-triangular Schur factorization from a real quasitriangular factorization, you can use `Schur{Complex}(schur(A))`.
Iterating the decomposition produces the components `F.T`, `F.Z`, and `F.values`.
**Examples**
```
julia> A = [5. 7.; -2. -4.]
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> F = schur(A)
Schur{Float64, Matrix{Float64}, Vector{Float64}}
T factor:
2×2 Matrix{Float64}:
3.0 9.0
0.0 -2.0
Z factor:
2×2 Matrix{Float64}:
0.961524 0.274721
-0.274721 0.961524
eigenvalues:
2-element Vector{Float64}:
3.0
-2.0
julia> F.vectors * F.Schur * F.vectors'
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> t, z, vals = F; # destructuring via iteration
julia> t == F.T && z == F.Z && vals == F.values
true
```
```
schur(A, B) -> F::GeneralizedSchur
```
Computes the Generalized Schur (or QZ) factorization of the matrices `A` and `B`. The (quasi) triangular Schur factors can be obtained from the `Schur` object `F` with `F.S` and `F.T`, the left unitary/orthogonal Schur vectors can be obtained with `F.left` or `F.Q` and the right unitary/orthogonal Schur vectors can be obtained with `F.right` or `F.Z` such that `A=F.left*F.S*F.right'` and `B=F.left*F.T*F.right'`. The generalized eigenvalues of `A` and `B` can be obtained with `F.α./F.β`.
Iterating the decomposition produces the components `F.S`, `F.T`, `F.Q`, `F.Z`, `F.α`, and `F.β`.
###
`LinearAlgebra.schur!`Function
```
schur!(A::StridedMatrix) -> F::Schur
```
Same as [`schur`](#LinearAlgebra.schur) but uses the input argument `A` as workspace.
**Examples**
```
julia> A = [5. 7.; -2. -4.]
2×2 Matrix{Float64}:
5.0 7.0
-2.0 -4.0
julia> F = schur!(A)
Schur{Float64, Matrix{Float64}, Vector{Float64}}
T factor:
2×2 Matrix{Float64}:
3.0 9.0
0.0 -2.0
Z factor:
2×2 Matrix{Float64}:
0.961524 0.274721
-0.274721 0.961524
eigenvalues:
2-element Vector{Float64}:
3.0
-2.0
julia> A
2×2 Matrix{Float64}:
3.0 9.0
0.0 -2.0
```
```
schur!(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur
```
Same as [`schur`](#LinearAlgebra.schur) but uses the input matrices `A` and `B` as workspace.
###
`LinearAlgebra.ordschur`Function
```
ordschur(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur
```
Reorders the Schur factorization `F` of a matrix `A = Z*T*Z'` according to the logical array `select` returning the reordered factorization `F` object. The selected eigenvalues appear in the leading diagonal of `F.Schur` and the corresponding leading columns of `F.vectors` form an orthogonal/unitary basis of the corresponding right invariant subspace. In the real case, a complex conjugate pair of eigenvalues must be either both included or both excluded via `select`.
```
ordschur(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur
```
Reorders the Generalized Schur factorization `F` of a matrix pair `(A, B) = (Q*S*Z', Q*T*Z')` according to the logical array `select` and returns a GeneralizedSchur object `F`. The selected eigenvalues appear in the leading diagonal of both `F.S` and `F.T`, and the left and right orthogonal/unitary Schur vectors are also reordered such that `(A, B) = F.Q*(F.S, F.T)*F.Z'` still holds and the generalized eigenvalues of `A` and `B` can still be obtained with `F.α./F.β`.
###
`LinearAlgebra.ordschur!`Function
```
ordschur!(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur
```
Same as [`ordschur`](#LinearAlgebra.ordschur) but overwrites the factorization `F`.
```
ordschur!(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur
```
Same as `ordschur` but overwrites the factorization `F`.
###
`LinearAlgebra.SVD`Type
```
SVD <: Factorization
```
Matrix factorization type of the singular value decomposition (SVD) of a matrix `A`. This is the return type of [`svd(_)`](#LinearAlgebra.svd), the corresponding matrix factorization function.
If `F::SVD` is the factorization object, `U`, `S`, `V` and `Vt` can be obtained via `F.U`, `F.S`, `F.V` and `F.Vt`, such that `A = U * Diagonal(S) * Vt`. The singular values in `S` are sorted in descending order.
Iterating the decomposition produces the components `U`, `S`, and `V`.
**Examples**
```
julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]
4×5 Matrix{Float64}:
1.0 0.0 0.0 0.0 2.0
0.0 0.0 3.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 2.0 0.0 0.0 0.0
julia> F = svd(A)
SVD{Float64, Float64, Matrix{Float64}, Vector{Float64}}
U factor:
4×4 Matrix{Float64}:
0.0 1.0 0.0 0.0
1.0 0.0 0.0 0.0
0.0 0.0 0.0 -1.0
0.0 0.0 1.0 0.0
singular values:
4-element Vector{Float64}:
3.0
2.23606797749979
2.0
0.0
Vt factor:
4×5 Matrix{Float64}:
-0.0 0.0 1.0 -0.0 0.0
0.447214 0.0 0.0 0.0 0.894427
-0.0 1.0 0.0 -0.0 0.0
0.0 0.0 0.0 1.0 0.0
julia> F.U * Diagonal(F.S) * F.Vt
4×5 Matrix{Float64}:
1.0 0.0 0.0 0.0 2.0
0.0 0.0 3.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 2.0 0.0 0.0 0.0
julia> u, s, v = F; # destructuring via iteration
julia> u == F.U && s == F.S && v == F.V
true
```
###
`LinearAlgebra.GeneralizedSVD`Type
```
GeneralizedSVD <: Factorization
```
Matrix factorization type of the generalized singular value decomposition (SVD) of two matrices `A` and `B`, such that `A = F.U*F.D1*F.R0*F.Q'` and `B = F.V*F.D2*F.R0*F.Q'`. This is the return type of [`svd(_, _)`](#LinearAlgebra.svd), the corresponding matrix factorization function.
For an M-by-N matrix `A` and P-by-N matrix `B`,
* `U` is a M-by-M orthogonal matrix,
* `V` is a P-by-P orthogonal matrix,
* `Q` is a N-by-N orthogonal matrix,
* `D1` is a M-by-(K+L) diagonal matrix with 1s in the first K entries,
* `D2` is a P-by-(K+L) matrix whose top right L-by-L block is diagonal,
* `R0` is a (K+L)-by-N matrix whose rightmost (K+L)-by-(K+L) block is nonsingular upper block triangular,
`K+L` is the effective numerical rank of the matrix `[A; B]`.
Iterating the decomposition produces the components `U`, `V`, `Q`, `D1`, `D2`, and `R0`.
The entries of `F.D1` and `F.D2` are related, as explained in the LAPACK documentation for the [generalized SVD](http://www.netlib.org/lapack/lug/node36.html) and the [xGGSVD3](http://www.netlib.org/lapack/explore-html/d6/db3/dggsvd3_8f.html) routine which is called underneath (in LAPACK 3.6.0 and newer).
**Examples**
```
julia> A = [1. 0.; 0. -1.]
2×2 Matrix{Float64}:
1.0 0.0
0.0 -1.0
julia> B = [0. 1.; 1. 0.]
2×2 Matrix{Float64}:
0.0 1.0
1.0 0.0
julia> F = svd(A, B)
GeneralizedSVD{Float64, Matrix{Float64}, Float64, Vector{Float64}}
U factor:
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
V factor:
2×2 Matrix{Float64}:
-0.0 -1.0
1.0 0.0
Q factor:
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
D1 factor:
2×2 Matrix{Float64}:
0.707107 0.0
0.0 0.707107
D2 factor:
2×2 Matrix{Float64}:
0.707107 0.0
0.0 0.707107
R0 factor:
2×2 Matrix{Float64}:
1.41421 0.0
0.0 -1.41421
julia> F.U*F.D1*F.R0*F.Q'
2×2 Matrix{Float64}:
1.0 0.0
0.0 -1.0
julia> F.V*F.D2*F.R0*F.Q'
2×2 Matrix{Float64}:
-0.0 1.0
1.0 0.0
```
###
`LinearAlgebra.svd`Function
```
svd(A; full::Bool = false, alg::Algorithm = default_svd_alg(A)) -> SVD
```
Compute the singular value decomposition (SVD) of `A` and return an `SVD` object.
`U`, `S`, `V` and `Vt` can be obtained from the factorization `F` with `F.U`, `F.S`, `F.V` and `F.Vt`, such that `A = U * Diagonal(S) * Vt`. The algorithm produces `Vt` and hence `Vt` is more efficient to extract than `V`. The singular values in `S` are sorted in descending order.
Iterating the decomposition produces the components `U`, `S`, and `V`.
If `full = false` (default), a "thin" SVD is returned. For an $M \times N$ matrix `A`, in the full factorization `U` is $M \times M$ and `V` is $N \times N$, while in the thin factorization `U` is $M \times K$ and `V` is $N \times K$, where $K = \min(M,N)$ is the number of singular values.
If `alg = DivideAndConquer()` a divide-and-conquer algorithm is used to calculate the SVD. Another (typically slower but more accurate) option is `alg = QRIteration()`.
The `alg` keyword argument requires Julia 1.3 or later.
**Examples**
```
julia> A = rand(4,3);
julia> F = svd(A); # Store the Factorization Object
julia> A ≈ F.U * Diagonal(F.S) * F.Vt
true
julia> U, S, V = F; # destructuring via iteration
julia> A ≈ U * Diagonal(S) * V'
true
julia> Uonly, = svd(A); # Store U only
julia> Uonly == U
true
```
```
svd(A, B) -> GeneralizedSVD
```
Compute the generalized SVD of `A` and `B`, returning a `GeneralizedSVD` factorization object `F` such that `[A;B] = [F.U * F.D1; F.V * F.D2] * F.R0 * F.Q'`
* `U` is a M-by-M orthogonal matrix,
* `V` is a P-by-P orthogonal matrix,
* `Q` is a N-by-N orthogonal matrix,
* `D1` is a M-by-(K+L) diagonal matrix with 1s in the first K entries,
* `D2` is a P-by-(K+L) matrix whose top right L-by-L block is diagonal,
* `R0` is a (K+L)-by-N matrix whose rightmost (K+L)-by-(K+L) block is nonsingular upper block triangular,
`K+L` is the effective numerical rank of the matrix `[A; B]`.
Iterating the decomposition produces the components `U`, `V`, `Q`, `D1`, `D2`, and `R0`.
The generalized SVD is used in applications such as when one wants to compare how much belongs to `A` vs. how much belongs to `B`, as in human vs yeast genome, or signal vs noise, or between clusters vs within clusters. (See Edelman and Wang for discussion: https://arxiv.org/abs/1901.00485)
It decomposes `[A; B]` into `[UC; VS]H`, where `[UC; VS]` is a natural orthogonal basis for the column space of `[A; B]`, and `H = RQ'` is a natural non-orthogonal basis for the rowspace of `[A;B]`, where the top rows are most closely attributed to the `A` matrix, and the bottom to the `B` matrix. The multi-cosine/sine matrices `C` and `S` provide a multi-measure of how much `A` vs how much `B`, and `U` and `V` provide directions in which these are measured.
**Examples**
```
julia> A = randn(3,2); B=randn(4,2);
julia> F = svd(A, B);
julia> U,V,Q,C,S,R = F;
julia> H = R*Q';
julia> [A; B] ≈ [U*C; V*S]*H
true
julia> [A; B] ≈ [F.U*F.D1; F.V*F.D2]*F.R0*F.Q'
true
julia> Uonly, = svd(A,B);
julia> U == Uonly
true
```
###
`LinearAlgebra.svd!`Function
```
svd!(A; full::Bool = false, alg::Algorithm = default_svd_alg(A)) -> SVD
```
`svd!` is the same as [`svd`](#LinearAlgebra.svd), but saves space by overwriting the input `A`, instead of creating a copy. See documentation of [`svd`](#LinearAlgebra.svd) for details.
```
svd!(A, B) -> GeneralizedSVD
```
`svd!` is the same as [`svd`](#LinearAlgebra.svd), but modifies the arguments `A` and `B` in-place, instead of making copies. See documentation of [`svd`](#LinearAlgebra.svd) for details.
###
`LinearAlgebra.svdvals`Function
```
svdvals(A)
```
Return the singular values of `A` in descending order.
**Examples**
```
julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]
4×5 Matrix{Float64}:
1.0 0.0 0.0 0.0 2.0
0.0 0.0 3.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 2.0 0.0 0.0 0.0
julia> svdvals(A)
4-element Vector{Float64}:
3.0
2.23606797749979
2.0
0.0
```
```
svdvals(A, B)
```
Return the generalized singular values from the generalized singular value decomposition of `A` and `B`. See also [`svd`](#LinearAlgebra.svd).
**Examples**
```
julia> A = [1. 0.; 0. -1.]
2×2 Matrix{Float64}:
1.0 0.0
0.0 -1.0
julia> B = [0. 1.; 1. 0.]
2×2 Matrix{Float64}:
0.0 1.0
1.0 0.0
julia> svdvals(A, B)
2-element Vector{Float64}:
1.0
1.0
```
###
`LinearAlgebra.svdvals!`Function
```
svdvals!(A)
```
Return the singular values of `A`, saving space by overwriting the input. See also [`svdvals`](#LinearAlgebra.svdvals) and [`svd`](#LinearAlgebra.svd). ```
```
svdvals!(A, B)
```
Return the generalized singular values from the generalized singular value decomposition of `A` and `B`, saving space by overwriting `A` and `B`. See also [`svd`](#LinearAlgebra.svd) and [`svdvals`](#LinearAlgebra.svdvals).
###
`LinearAlgebra.Givens`Type
```
LinearAlgebra.Givens(i1,i2,c,s) -> G
```
A Givens rotation linear operator. The fields `c` and `s` represent the cosine and sine of the rotation angle, respectively. The `Givens` type supports left multiplication `G*A` and conjugated transpose right multiplication `A*G'`. The type doesn't have a `size` and can therefore be multiplied with matrices of arbitrary size as long as `i2<=size(A,2)` for `G*A` or `i2<=size(A,1)` for `A*G'`.
See also [`givens`](#LinearAlgebra.givens).
###
`LinearAlgebra.givens`Function
```
givens(f::T, g::T, i1::Integer, i2::Integer) where {T} -> (G::Givens, r::T)
```
Computes the Givens rotation `G` and scalar `r` such that for any vector `x` where
```
x[i1] = f
x[i2] = g
```
the result of the multiplication
```
y = G*x
```
has the property that
```
y[i1] = r
y[i2] = 0
```
See also [`LinearAlgebra.Givens`](#LinearAlgebra.Givens).
```
givens(A::AbstractArray, i1::Integer, i2::Integer, j::Integer) -> (G::Givens, r)
```
Computes the Givens rotation `G` and scalar `r` such that the result of the multiplication
```
B = G*A
```
has the property that
```
B[i1,j] = r
B[i2,j] = 0
```
See also [`LinearAlgebra.Givens`](#LinearAlgebra.Givens).
```
givens(x::AbstractVector, i1::Integer, i2::Integer) -> (G::Givens, r)
```
Computes the Givens rotation `G` and scalar `r` such that the result of the multiplication
```
B = G*x
```
has the property that
```
B[i1] = r
B[i2] = 0
```
See also [`LinearAlgebra.Givens`](#LinearAlgebra.Givens).
###
`LinearAlgebra.triu`Function
```
triu(M)
```
Upper triangle of a matrix.
**Examples**
```
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a)
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
0.0 1.0 1.0 1.0
0.0 0.0 1.0 1.0
0.0 0.0 0.0 1.0
```
```
triu(M, k::Integer)
```
Returns the upper triangle of `M` starting from the `k`th superdiagonal.
**Examples**
```
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a,3)
4×4 Matrix{Float64}:
0.0 0.0 0.0 1.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
julia> triu(a,-3)
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
```
###
`LinearAlgebra.triu!`Function
```
triu!(M)
```
Upper triangle of a matrix, overwriting `M` in the process. See also [`triu`](#LinearAlgebra.triu).
```
triu!(M, k::Integer)
```
Return the upper triangle of `M` starting from the `k`th superdiagonal, overwriting `M` in the process.
**Examples**
```
julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
5×5 Matrix{Int64}:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
julia> triu!(M, 1)
5×5 Matrix{Int64}:
0 2 3 4 5
0 0 3 4 5
0 0 0 4 5
0 0 0 0 5
0 0 0 0 0
```
###
`LinearAlgebra.tril`Function
```
tril(M)
```
Lower triangle of a matrix.
**Examples**
```
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a)
4×4 Matrix{Float64}:
1.0 0.0 0.0 0.0
1.0 1.0 0.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 1.0 1.0
```
```
tril(M, k::Integer)
```
Returns the lower triangle of `M` starting from the `k`th superdiagonal.
**Examples**
```
julia> a = fill(1.0, (4,4))
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,3)
4×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,-3)
4×4 Matrix{Float64}:
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
1.0 0.0 0.0 0.0
```
###
`LinearAlgebra.tril!`Function
```
tril!(M)
```
Lower triangle of a matrix, overwriting `M` in the process. See also [`tril`](#LinearAlgebra.tril).
```
tril!(M, k::Integer)
```
Return the lower triangle of `M` starting from the `k`th superdiagonal, overwriting `M` in the process.
**Examples**
```
julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
5×5 Matrix{Int64}:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
julia> tril!(M, 2)
5×5 Matrix{Int64}:
1 2 3 0 0
1 2 3 4 0
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
```
###
`LinearAlgebra.diagind`Function
```
diagind(M, k::Integer=0)
```
An `AbstractRange` giving the indices of the `k`th diagonal of the matrix `M`.
See also: [`diag`](#LinearAlgebra.diag), [`diagm`](#LinearAlgebra.diagm), [`Diagonal`](#LinearAlgebra.Diagonal).
**Examples**
```
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> diagind(A,-1)
2:4:6
```
###
`LinearAlgebra.diag`Function
```
diag(M, k::Integer=0)
```
The `k`th diagonal of a matrix, as a vector.
See also [`diagm`](#LinearAlgebra.diagm), [`diagind`](#LinearAlgebra.diagind), [`Diagonal`](#LinearAlgebra.Diagonal), [`isdiag`](#LinearAlgebra.isdiag).
**Examples**
```
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> diag(A,1)
2-element Vector{Int64}:
2
6
```
###
`LinearAlgebra.diagm`Function
```
diagm(kv::Pair{<:Integer,<:AbstractVector}...)
diagm(m::Integer, n::Integer, kv::Pair{<:Integer,<:AbstractVector}...)
```
Construct a matrix from `Pair`s of diagonals and vectors. Vector `kv.second` will be placed on the `kv.first` diagonal. By default the matrix is square and its size is inferred from `kv`, but a non-square size `m`×`n` (padded with zeros as needed) can be specified by passing `m,n` as the first arguments. For repeated diagonal indices `kv.first` the values in the corresponding vectors `kv.second` will be added.
`diagm` constructs a full matrix; if you want storage-efficient versions with fast arithmetic, see [`Diagonal`](#LinearAlgebra.Diagonal), [`Bidiagonal`](#LinearAlgebra.Bidiagonal) [`Tridiagonal`](#LinearAlgebra.Tridiagonal) and [`SymTridiagonal`](#LinearAlgebra.SymTridiagonal).
**Examples**
```
julia> diagm(1 => [1,2,3])
4×4 Matrix{Int64}:
0 1 0 0
0 0 2 0
0 0 0 3
0 0 0 0
julia> diagm(1 => [1,2,3], -1 => [4,5])
4×4 Matrix{Int64}:
0 1 0 0
4 0 2 0
0 5 0 3
0 0 0 0
julia> diagm(1 => [1,2,3], 1 => [1,2,3])
4×4 Matrix{Int64}:
0 2 0 0
0 0 4 0
0 0 0 6
0 0 0 0
```
```
diagm(v::AbstractVector)
diagm(m::Integer, n::Integer, v::AbstractVector)
```
Construct a matrix with elements of the vector as diagonal elements. By default, the matrix is square and its size is given by `length(v)`, but a non-square size `m`×`n` can be specified by passing `m,n` as the first arguments.
**Examples**
```
julia> diagm([1,2,3])
3×3 Matrix{Int64}:
1 0 0
0 2 0
0 0 3
```
###
`LinearAlgebra.rank`Function
```
rank(A::AbstractMatrix; atol::Real=0, rtol::Real=atol>0 ? 0 : n*ϵ)
rank(A::AbstractMatrix, rtol::Real)
```
Compute the rank of a matrix by counting how many singular values of `A` have magnitude greater than `max(atol, rtol*σ₁)` where `σ₁` is `A`'s largest singular value. `atol` and `rtol` are the absolute and relative tolerances, respectively. The default relative tolerance is `n*ϵ`, where `n` is the size of the smallest dimension of `A`, and `ϵ` is the [`eps`](#) of the element type of `A`.
The `atol` and `rtol` keyword arguments requires at least Julia 1.1. In Julia 1.0 `rtol` is available as a positional argument, but this will be deprecated in Julia 2.0.
**Examples**
```
julia> rank(Matrix(I, 3, 3))
3
julia> rank(diagm(0 => [1, 0, 2]))
2
julia> rank(diagm(0 => [1, 0.001, 2]), rtol=0.1)
2
julia> rank(diagm(0 => [1, 0.001, 2]), rtol=0.00001)
3
julia> rank(diagm(0 => [1, 0.001, 2]), atol=1.5)
1
```
###
`LinearAlgebra.norm`Function
```
norm(A, p::Real=2)
```
For any iterable container `A` (including arrays of any dimension) of numbers (or any element type for which `norm` is defined), compute the `p`-norm (defaulting to `p=2`) as if `A` were a vector of the corresponding length.
The `p`-norm is defined as
\[\|A\|\_p = \left( \sum\_{i=1}^n | a\_i | ^p \right)^{1/p}\]
with $a\_i$ the entries of $A$, $| a\_i |$ the [`norm`](#LinearAlgebra.norm) of $a\_i$, and $n$ the length of $A$. Since the `p`-norm is computed using the [`norm`](#LinearAlgebra.norm)s of the entries of `A`, the `p`-norm of a vector of vectors is not compatible with the interpretation of it as a block vector in general if `p != 2`.
`p` can assume any numeric value (even though not all values produce a mathematically valid vector norm). In particular, `norm(A, Inf)` returns the largest value in `abs.(A)`, whereas `norm(A, -Inf)` returns the smallest. If `A` is a matrix and `p=2`, then this is equivalent to the Frobenius norm.
The second argument `p` is not necessarily a part of the interface for `norm`, i.e. a custom type may only implement `norm(A)` without second argument.
Use [`opnorm`](#LinearAlgebra.opnorm) to compute the operator norm of a matrix.
**Examples**
```
julia> v = [3, -2, 6]
3-element Vector{Int64}:
3
-2
6
julia> norm(v)
7.0
julia> norm(v, 1)
11.0
julia> norm(v, Inf)
6.0
julia> norm([1 2 3; 4 5 6; 7 8 9])
16.881943016134134
julia> norm([1 2 3 4 5 6 7 8 9])
16.881943016134134
julia> norm(1:9)
16.881943016134134
julia> norm(hcat(v,v), 1) == norm(vcat(v,v), 1) != norm([v,v], 1)
true
julia> norm(hcat(v,v), 2) == norm(vcat(v,v), 2) == norm([v,v], 2)
true
julia> norm(hcat(v,v), Inf) == norm(vcat(v,v), Inf) != norm([v,v], Inf)
true
```
```
norm(x::Number, p::Real=2)
```
For numbers, return $\left( |x|^p \right)^{1/p}$.
**Examples**
```
julia> norm(2, 1)
2.0
julia> norm(-2, 1)
2.0
julia> norm(2, 2)
2.0
julia> norm(-2, 2)
2.0
julia> norm(2, Inf)
2.0
julia> norm(-2, Inf)
2.0
```
###
`LinearAlgebra.opnorm`Function
```
opnorm(A::AbstractMatrix, p::Real=2)
```
Compute the operator norm (or matrix norm) induced by the vector `p`-norm, where valid values of `p` are `1`, `2`, or `Inf`. (Note that for sparse matrices, `p=2` is currently not implemented.) Use [`norm`](#LinearAlgebra.norm) to compute the Frobenius norm.
When `p=1`, the operator norm is the maximum absolute column sum of `A`:
\[\|A\|\_1 = \max\_{1 ≤ j ≤ n} \sum\_{i=1}^m | a\_{ij} |\]
with $a\_{ij}$ the entries of $A$, and $m$ and $n$ its dimensions.
When `p=2`, the operator norm is the spectral norm, equal to the largest singular value of `A`.
When `p=Inf`, the operator norm is the maximum absolute row sum of `A`:
\[\|A\|\_\infty = \max\_{1 ≤ i ≤ m} \sum \_{j=1}^n | a\_{ij} |\]
**Examples**
```
julia> A = [1 -2 -3; 2 3 -1]
2×3 Matrix{Int64}:
1 -2 -3
2 3 -1
julia> opnorm(A, Inf)
6.0
julia> opnorm(A, 1)
5.0
```
```
opnorm(x::Number, p::Real=2)
```
For numbers, return $\left( |x|^p \right)^{1/p}$. This is equivalent to [`norm`](#LinearAlgebra.norm).
```
opnorm(A::Adjoint{<:Any,<:AbstracVector}, q::Real=2)
opnorm(A::Transpose{<:Any,<:AbstracVector}, q::Real=2)
```
For Adjoint/Transpose-wrapped vectors, return the operator $q$-norm of `A`, which is equivalent to the `p`-norm with value `p = q/(q-1)`. They coincide at `p = q = 2`. Use [`norm`](#LinearAlgebra.norm) to compute the `p` norm of `A` as a vector.
The difference in norm between a vector space and its dual arises to preserve the relationship between duality and the dot product, and the result is consistent with the operator `p`-norm of a `1 × n` matrix.
**Examples**
```
julia> v = [1; im];
julia> vc = v';
julia> opnorm(vc, 1)
1.0
julia> norm(vc, 1)
2.0
julia> norm(v, 1)
2.0
julia> opnorm(vc, 2)
1.4142135623730951
julia> norm(vc, 2)
1.4142135623730951
julia> norm(v, 2)
1.4142135623730951
julia> opnorm(vc, Inf)
2.0
julia> norm(vc, Inf)
1.0
julia> norm(v, Inf)
1.0
```
###
`LinearAlgebra.normalize!`Function
```
normalize!(a::AbstractArray, p::Real=2)
```
Normalize the array `a` in-place so that its `p`-norm equals unity, i.e. `norm(a, p) == 1`. See also [`normalize`](#LinearAlgebra.normalize) and [`norm`](#LinearAlgebra.norm).
###
`LinearAlgebra.normalize`Function
```
normalize(a::AbstractArray, p::Real=2)
```
Normalize the array `a` so that its `p`-norm equals unity, i.e. `norm(a, p) == 1`. See also [`normalize!`](#LinearAlgebra.normalize!) and [`norm`](#LinearAlgebra.norm).
**Examples**
```
julia> a = [1,2,4];
julia> b = normalize(a)
3-element Vector{Float64}:
0.2182178902359924
0.4364357804719848
0.8728715609439696
julia> norm(b)
1.0
julia> c = normalize(a, 1)
3-element Vector{Float64}:
0.14285714285714285
0.2857142857142857
0.5714285714285714
julia> norm(c, 1)
1.0
julia> a = [1 2 4 ; 1 2 4]
2×3 Matrix{Int64}:
1 2 4
1 2 4
julia> norm(a)
6.48074069840786
julia> normalize(a)
2×3 Matrix{Float64}:
0.154303 0.308607 0.617213
0.154303 0.308607 0.617213
```
###
`LinearAlgebra.cond`Function
```
cond(M, p::Real=2)
```
Condition number of the matrix `M`, computed using the operator `p`-norm. Valid values for `p` are `1`, `2` (default), or `Inf`.
###
`LinearAlgebra.condskeel`Function
```
condskeel(M, [x, p::Real=Inf])
```
\[\kappa\_S(M, p) = \left\Vert \left\vert M \right\vert \left\vert M^{-1} \right\vert \right\Vert\_p \\ \kappa\_S(M, x, p) = \frac{\left\Vert \left\vert M \right\vert \left\vert M^{-1} \right\vert \left\vert x \right\vert \right\Vert\_p}{\left \Vert x \right \Vert\_p}\]
Skeel condition number $\kappa\_S$ of the matrix `M`, optionally with respect to the vector `x`, as computed using the operator `p`-norm. $\left\vert M \right\vert$ denotes the matrix of (entry wise) absolute values of $M$; $\left\vert M \right\vert\_{ij} = \left\vert M\_{ij} \right\vert$. Valid values for `p` are `1`, `2` and `Inf` (default).
This quantity is also known in the literature as the Bauer condition number, relative condition number, or componentwise relative condition number.
###
`LinearAlgebra.tr`Function
```
tr(M)
```
Matrix trace. Sums the diagonal elements of `M`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> tr(A)
5
```
###
`LinearAlgebra.det`Function
```
det(M)
```
Matrix determinant.
See also: [`logdet`](#LinearAlgebra.logdet) and [`logabsdet`](#LinearAlgebra.logabsdet).
**Examples**
```
julia> M = [1 0; 2 2]
2×2 Matrix{Int64}:
1 0
2 2
julia> det(M)
2.0
```
###
`LinearAlgebra.logdet`Function
```
logdet(M)
```
Log of matrix determinant. Equivalent to `log(det(M))`, but may provide increased accuracy and/or speed.
**Examples**
```
julia> M = [1 0; 2 2]
2×2 Matrix{Int64}:
1 0
2 2
julia> logdet(M)
0.6931471805599453
julia> logdet(Matrix(I, 3, 3))
0.0
```
###
`LinearAlgebra.logabsdet`Function
```
logabsdet(M)
```
Log of absolute value of matrix determinant. Equivalent to `(log(abs(det(M))), sign(det(M)))`, but may provide increased accuracy and/or speed.
**Examples**
```
julia> A = [-1. 0.; 0. 1.]
2×2 Matrix{Float64}:
-1.0 0.0
0.0 1.0
julia> det(A)
-1.0
julia> logabsdet(A)
(0.0, -1.0)
julia> B = [2. 0.; 0. 1.]
2×2 Matrix{Float64}:
2.0 0.0
0.0 1.0
julia> det(B)
2.0
julia> logabsdet(B)
(0.6931471805599453, 1.0)
```
###
`Base.inv`Method
```
inv(M)
```
Matrix inverse. Computes matrix `N` such that `M * N = I`, where `I` is the identity matrix. Computed by solving the left-division `N = M \ I`.
**Examples**
```
julia> M = [2 5; 1 3]
2×2 Matrix{Int64}:
2 5
1 3
julia> N = inv(M)
2×2 Matrix{Float64}:
3.0 -5.0
-1.0 2.0
julia> M*N == N*M == Matrix(I, 2, 2)
true
```
###
`LinearAlgebra.pinv`Function
```
pinv(M; atol::Real=0, rtol::Real=atol>0 ? 0 : n*ϵ)
pinv(M, rtol::Real) = pinv(M; rtol=rtol) # to be deprecated in Julia 2.0
```
Computes the Moore-Penrose pseudoinverse.
For matrices `M` with floating point elements, it is convenient to compute the pseudoinverse by inverting only singular values greater than `max(atol, rtol*σ₁)` where `σ₁` is the largest singular value of `M`.
The optimal choice of absolute (`atol`) and relative tolerance (`rtol`) varies both with the value of `M` and the intended application of the pseudoinverse. The default relative tolerance is `n*ϵ`, where `n` is the size of the smallest dimension of `M`, and `ϵ` is the [`eps`](#) of the element type of `M`.
For inverting dense ill-conditioned matrices in a least-squares sense, `rtol = sqrt(eps(real(float(one(eltype(M))))))` is recommended.
For more information, see [[issue8859]](#footnote-issue8859), [[B96]](#footnote-B96), [[S84]](#footnote-S84), [[KY88]](#footnote-KY88).
**Examples**
```
julia> M = [1.5 1.3; 1.2 1.9]
2×2 Matrix{Float64}:
1.5 1.3
1.2 1.9
julia> N = pinv(M)
2×2 Matrix{Float64}:
1.47287 -1.00775
-0.930233 1.16279
julia> M * N
2×2 Matrix{Float64}:
1.0 -2.22045e-16
4.44089e-16 1.0
```
###
`LinearAlgebra.nullspace`Function
```
nullspace(M; atol::Real=0, rtol::Real=atol>0 ? 0 : n*ϵ)
nullspace(M, rtol::Real) = nullspace(M; rtol=rtol) # to be deprecated in Julia 2.0
```
Computes a basis for the nullspace of `M` by including the singular vectors of `M` whose singular values have magnitudes smaller than `max(atol, rtol*σ₁)`, where `σ₁` is `M`'s largest singular value.
By default, the relative tolerance `rtol` is `n*ϵ`, where `n` is the size of the smallest dimension of `M`, and `ϵ` is the [`eps`](#) of the element type of `M`.
**Examples**
```
julia> M = [1 0 0; 0 1 0; 0 0 0]
3×3 Matrix{Int64}:
1 0 0
0 1 0
0 0 0
julia> nullspace(M)
3×1 Matrix{Float64}:
0.0
0.0
1.0
julia> nullspace(M, rtol=3)
3×3 Matrix{Float64}:
0.0 1.0 0.0
1.0 0.0 0.0
0.0 0.0 1.0
julia> nullspace(M, atol=0.95)
3×1 Matrix{Float64}:
0.0
0.0
1.0
```
###
`Base.kron`Function
```
kron(A, B)
```
Kronecker tensor product of two vectors or two matrices.
For real vectors `v` and `w`, the Kronecker product is related to the outer product by `kron(v,w) == vec(w * transpose(v))` or `w * transpose(v) == reshape(kron(v,w), (length(w), length(v)))`. Note how the ordering of `v` and `w` differs on the left and right of these expressions (due to column-major storage). For complex vectors, the outer product `w * v'` also differs by conjugation of `v`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> B = [im 1; 1 -im]
2×2 Matrix{Complex{Int64}}:
0+1im 1+0im
1+0im 0-1im
julia> kron(A, B)
4×4 Matrix{Complex{Int64}}:
0+1im 1+0im 0+2im 2+0im
1+0im 0-1im 2+0im 0-2im
0+3im 3+0im 0+4im 4+0im
3+0im 0-3im 4+0im 0-4im
julia> v = [1, 2]; w = [3, 4, 5];
julia> w*transpose(v)
3×2 Matrix{Int64}:
3 6
4 8
5 10
julia> reshape(kron(v,w), (length(w), length(v)))
3×2 Matrix{Int64}:
3 6
4 8
5 10
```
###
`Base.kron!`Function
```
kron!(C, A, B)
```
`kron!` is the in-place version of [`kron`](#Base.kron). Computes `kron(A, B)` and stores the result in `C` overwriting the existing value of `C`.
Bounds checking can be disabled by [`@inbounds`](../../base/base/index#Base.@inbounds), but you need to take care of the shape of `C`, `A`, `B` yourself.
This function requires Julia 1.6 or later.
###
`Base.exp`Method
```
exp(A::AbstractMatrix)
```
Compute the matrix exponential of `A`, defined by
\[e^A = \sum\_{n=0}^{\infty} \frac{A^n}{n!}.\]
For symmetric or Hermitian `A`, an eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used, otherwise the scaling and squaring algorithm (see [[H05]](#footnote-H05)) is chosen.
**Examples**
```
julia> A = Matrix(1.0I, 2, 2)
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
julia> exp(A)
2×2 Matrix{Float64}:
2.71828 0.0
0.0 2.71828
```
###
`Base.cis`Method
```
cis(A::AbstractMatrix)
```
More efficient method for `exp(im*A)` of square matrix `A` (especially if `A` is `Hermitian` or real-`Symmetric`).
See also [`cispi`](../../base/math/index#Base.cispi), [`sincos`](#), [`exp`](#).
Support for using `cis` with matrices was added in Julia 1.7.
**Examples**
```
julia> cis([π 0; 0 π]) ≈ -I
true
```
###
`Base.:^`Method
```
^(A::AbstractMatrix, p::Number)
```
Matrix power, equivalent to $\exp(p\log(A))$
**Examples**
```
julia> [1 2; 0 3]^3
2×2 Matrix{Int64}:
1 26
0 27
```
###
`Base.:^`Method
```
^(b::Number, A::AbstractMatrix)
```
Matrix exponential, equivalent to $\exp(\log(b)A)$.
Support for raising `Irrational` numbers (like `ℯ`) to a matrix was added in Julia 1.1.
**Examples**
```
julia> 2^[1 2; 0 3]
2×2 Matrix{Float64}:
2.0 6.0
0.0 8.0
julia> ℯ^[1 2; 0 3]
2×2 Matrix{Float64}:
2.71828 17.3673
0.0 20.0855
```
###
`Base.log`Method
```
log(A::StridedMatrix)
```
If `A` has no negative real eigenvalue, compute the principal matrix logarithm of `A`, i.e. the unique matrix $X$ such that $e^X = A$ and $-\pi < Im(\lambda) < \pi$ for all the eigenvalues $\lambda$ of $X$. If `A` has nonpositive eigenvalues, a nonprincipal matrix function is returned whenever possible.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used, if `A` is triangular an improved version of the inverse scaling and squaring method is employed (see [[AH12]](#footnote-AH12) and [[AHR13]](#footnote-AHR13)). If `A` is real with no negative eigenvalues, then the real Schur form is computed. Otherwise, the complex Schur form is computed. Then the upper (quasi-)triangular algorithm in [[AHR13]](#footnote-AHR13) is used on the upper (quasi-)triangular factor.
**Examples**
```
julia> A = Matrix(2.7182818*I, 2, 2)
2×2 Matrix{Float64}:
2.71828 0.0
0.0 2.71828
julia> log(A)
2×2 Matrix{Float64}:
1.0 0.0
0.0 1.0
```
###
`Base.sqrt`Method
```
sqrt(A::AbstractMatrix)
```
If `A` has no negative real eigenvalues, compute the principal matrix square root of `A`, that is the unique matrix $X$ with eigenvalues having positive real part such that $X^2 = A$. Otherwise, a nonprincipal square root is returned.
If `A` is real-symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the square root. For such matrices, eigenvalues λ that appear to be slightly negative due to roundoff errors are treated as if they were zero. More precisely, matrices with all eigenvalues `≥ -rtol*(max |λ|)` are treated as semidefinite (yielding a Hermitian square root), with negative eigenvalues taken to be zero. `rtol` is a keyword argument to `sqrt` (in the Hermitian/real-symmetric case only) that defaults to machine precision scaled by `size(A,1)`.
Otherwise, the square root is determined by means of the Björck-Hammarling method [[BH83]](#footnote-BH83), which computes the complex Schur form ([`schur`](#LinearAlgebra.schur)) and then the complex square root of the triangular factor. If a real square root exists, then an extension of this method [[H87]](#footnote-H87) that computes the real Schur form and then the real square root of the quasi-triangular factor is instead used.
**Examples**
```
julia> A = [4 0; 0 4]
2×2 Matrix{Int64}:
4 0
0 4
julia> sqrt(A)
2×2 Matrix{Float64}:
2.0 0.0
0.0 2.0
```
###
`Base.cos`Method
```
cos(A::AbstractMatrix)
```
Compute the matrix cosine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the cosine. Otherwise, the cosine is determined by calling [`exp`](#).
**Examples**
```
julia> cos(fill(1.0, (2,2)))
2×2 Matrix{Float64}:
0.291927 -0.708073
-0.708073 0.291927
```
###
`Base.sin`Method
```
sin(A::AbstractMatrix)
```
Compute the matrix sine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the sine. Otherwise, the sine is determined by calling [`exp`](#).
**Examples**
```
julia> sin(fill(1.0, (2,2)))
2×2 Matrix{Float64}:
0.454649 0.454649
0.454649 0.454649
```
###
`Base.Math.sincos`Method
```
sincos(A::AbstractMatrix)
```
Compute the matrix sine and cosine of a square matrix `A`.
**Examples**
```
julia> S, C = sincos(fill(1.0, (2,2)));
julia> S
2×2 Matrix{Float64}:
0.454649 0.454649
0.454649 0.454649
julia> C
2×2 Matrix{Float64}:
0.291927 -0.708073
-0.708073 0.291927
```
###
`Base.tan`Method
```
tan(A::AbstractMatrix)
```
Compute the matrix tangent of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the tangent. Otherwise, the tangent is determined by calling [`exp`](#).
**Examples**
```
julia> tan(fill(1.0, (2,2)))
2×2 Matrix{Float64}:
-1.09252 -1.09252
-1.09252 -1.09252
```
###
`Base.Math.sec`Method
```
sec(A::AbstractMatrix)
```
Compute the matrix secant of a square matrix `A`.
###
`Base.Math.csc`Method
```
csc(A::AbstractMatrix)
```
Compute the matrix cosecant of a square matrix `A`.
###
`Base.Math.cot`Method
```
cot(A::AbstractMatrix)
```
Compute the matrix cotangent of a square matrix `A`.
###
`Base.cosh`Method
```
cosh(A::AbstractMatrix)
```
Compute the matrix hyperbolic cosine of a square matrix `A`.
###
`Base.sinh`Method
```
sinh(A::AbstractMatrix)
```
Compute the matrix hyperbolic sine of a square matrix `A`.
###
`Base.tanh`Method
```
tanh(A::AbstractMatrix)
```
Compute the matrix hyperbolic tangent of a square matrix `A`.
###
`Base.Math.sech`Method
```
sech(A::AbstractMatrix)
```
Compute the matrix hyperbolic secant of square matrix `A`.
###
`Base.Math.csch`Method
```
csch(A::AbstractMatrix)
```
Compute the matrix hyperbolic cosecant of square matrix `A`.
###
`Base.Math.coth`Method
```
coth(A::AbstractMatrix)
```
Compute the matrix hyperbolic cotangent of square matrix `A`.
###
`Base.acos`Method
```
acos(A::AbstractMatrix)
```
Compute the inverse matrix cosine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the inverse cosine. Otherwise, the inverse cosine is determined by using [`log`](#) and [`sqrt`](#). For the theory and logarithmic formulas used to compute this function, see [[AH16\_1]](#footnote-AH16_1).
**Examples**
```
julia> acos(cos([0.5 0.1; -0.2 0.3]))
2×2 Matrix{ComplexF64}:
0.5-8.32667e-17im 0.1+0.0im
-0.2+2.63678e-16im 0.3-3.46945e-16im
```
###
`Base.asin`Method
```
asin(A::AbstractMatrix)
```
Compute the inverse matrix sine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the inverse sine. Otherwise, the inverse sine is determined by using [`log`](#) and [`sqrt`](#). For the theory and logarithmic formulas used to compute this function, see [[AH16\_2]](#footnote-AH16_2).
**Examples**
```
julia> asin(sin([0.5 0.1; -0.2 0.3]))
2×2 Matrix{ComplexF64}:
0.5-4.16334e-17im 0.1-5.55112e-17im
-0.2+9.71445e-17im 0.3-1.249e-16im
```
###
`Base.atan`Method
```
atan(A::AbstractMatrix)
```
Compute the inverse matrix tangent of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#LinearAlgebra.eigen)) is used to compute the inverse tangent. Otherwise, the inverse tangent is determined by using [`log`](#). For the theory and logarithmic formulas used to compute this function, see [[AH16\_3]](#footnote-AH16_3).
**Examples**
```
julia> atan(tan([0.5 0.1; -0.2 0.3]))
2×2 Matrix{ComplexF64}:
0.5+1.38778e-17im 0.1-2.77556e-17im
-0.2+6.93889e-17im 0.3-4.16334e-17im
```
###
`Base.Math.asec`Method
```
asec(A::AbstractMatrix)
```
Compute the inverse matrix secant of `A`.
###
`Base.Math.acsc`Method
```
acsc(A::AbstractMatrix)
```
Compute the inverse matrix cosecant of `A`.
###
`Base.Math.acot`Method
```
acot(A::AbstractMatrix)
```
Compute the inverse matrix cotangent of `A`.
###
`Base.acosh`Method
```
acosh(A::AbstractMatrix)
```
Compute the inverse hyperbolic matrix cosine of a square matrix `A`. For the theory and logarithmic formulas used to compute this function, see [[AH16\_4]](#footnote-AH16_4).
###
`Base.asinh`Method
```
asinh(A::AbstractMatrix)
```
Compute the inverse hyperbolic matrix sine of a square matrix `A`. For the theory and logarithmic formulas used to compute this function, see [[AH16\_5]](#footnote-AH16_5).
###
`Base.atanh`Method
```
atanh(A::AbstractMatrix)
```
Compute the inverse hyperbolic matrix tangent of a square matrix `A`. For the theory and logarithmic formulas used to compute this function, see [[AH16\_6]](#footnote-AH16_6).
###
`Base.Math.asech`Method
```
asech(A::AbstractMatrix)
```
Compute the inverse matrix hyperbolic secant of `A`.
###
`Base.Math.acsch`Method
```
acsch(A::AbstractMatrix)
```
Compute the inverse matrix hyperbolic cosecant of `A`.
###
`Base.Math.acoth`Method
```
acoth(A::AbstractMatrix)
```
Compute the inverse matrix hyperbolic cotangent of `A`.
###
`LinearAlgebra.lyap`Function
```
lyap(A, C)
```
Computes the solution `X` to the continuous Lyapunov equation `AX + XA' + C = 0`, where no eigenvalue of `A` has a zero real part and no two eigenvalues are negative complex conjugates of each other.
**Examples**
```
julia> A = [3. 4.; 5. 6]
2×2 Matrix{Float64}:
3.0 4.0
5.0 6.0
julia> B = [1. 1.; 1. 2.]
2×2 Matrix{Float64}:
1.0 1.0
1.0 2.0
julia> X = lyap(A, B)
2×2 Matrix{Float64}:
0.5 -0.5
-0.5 0.25
julia> A*X + X*A' + B
2×2 Matrix{Float64}:
0.0 6.66134e-16
6.66134e-16 8.88178e-16
```
###
`LinearAlgebra.sylvester`Function
```
sylvester(A, B, C)
```
Computes the solution `X` to the Sylvester equation `AX + XB + C = 0`, where `A`, `B` and `C` have compatible dimensions and `A` and `-B` have no eigenvalues with equal real part.
**Examples**
```
julia> A = [3. 4.; 5. 6]
2×2 Matrix{Float64}:
3.0 4.0
5.0 6.0
julia> B = [1. 1.; 1. 2.]
2×2 Matrix{Float64}:
1.0 1.0
1.0 2.0
julia> C = [1. 2.; -2. 1]
2×2 Matrix{Float64}:
1.0 2.0
-2.0 1.0
julia> X = sylvester(A, B, C)
2×2 Matrix{Float64}:
-4.46667 1.93333
3.73333 -1.8
julia> A*X + X*B + C
2×2 Matrix{Float64}:
2.66454e-15 1.77636e-15
-3.77476e-15 4.44089e-16
```
###
`LinearAlgebra.issuccess`Function
```
issuccess(F::Factorization)
```
Test that a factorization of a matrix succeeded.
`issuccess(::CholeskyPivoted)` requires Julia 1.6 or later.
```
julia> F = cholesky([1 0; 0 1]);
julia> LinearAlgebra.issuccess(F)
true
julia> F = lu([1 0; 0 0]; check = false);
julia> LinearAlgebra.issuccess(F)
false
```
###
`LinearAlgebra.issymmetric`Function
```
issymmetric(A) -> Bool
```
Test whether a matrix is symmetric.
**Examples**
```
julia> a = [1 2; 2 -1]
2×2 Matrix{Int64}:
1 2
2 -1
julia> issymmetric(a)
true
julia> b = [1 im; -im 1]
2×2 Matrix{Complex{Int64}}:
1+0im 0+1im
0-1im 1+0im
julia> issymmetric(b)
false
```
###
`LinearAlgebra.isposdef`Function
```
isposdef(A) -> Bool
```
Test whether a matrix is positive definite (and Hermitian) by trying to perform a Cholesky factorization of `A`.
See also [`isposdef!`](#LinearAlgebra.isposdef!), [`cholesky`](#LinearAlgebra.cholesky).
**Examples**
```
julia> A = [1 2; 2 50]
2×2 Matrix{Int64}:
1 2
2 50
julia> isposdef(A)
true
```
###
`LinearAlgebra.isposdef!`Function
```
isposdef!(A) -> Bool
```
Test whether a matrix is positive definite (and Hermitian) by trying to perform a Cholesky factorization of `A`, overwriting `A` in the process. See also [`isposdef`](#LinearAlgebra.isposdef).
**Examples**
```
julia> A = [1. 2.; 2. 50.];
julia> isposdef!(A)
true
julia> A
2×2 Matrix{Float64}:
1.0 2.0
2.0 6.78233
```
###
`LinearAlgebra.istril`Function
```
istril(A::AbstractMatrix, k::Integer = 0) -> Bool
```
Test whether `A` is lower triangular starting from the `k`th superdiagonal.
**Examples**
```
julia> a = [1 2; 2 -1]
2×2 Matrix{Int64}:
1 2
2 -1
julia> istril(a)
false
julia> istril(a, 1)
true
julia> b = [1 0; -im -1]
2×2 Matrix{Complex{Int64}}:
1+0im 0+0im
0-1im -1+0im
julia> istril(b)
true
julia> istril(b, -1)
false
```
###
`LinearAlgebra.istriu`Function
```
istriu(A::AbstractMatrix, k::Integer = 0) -> Bool
```
Test whether `A` is upper triangular starting from the `k`th superdiagonal.
**Examples**
```
julia> a = [1 2; 2 -1]
2×2 Matrix{Int64}:
1 2
2 -1
julia> istriu(a)
false
julia> istriu(a, -1)
true
julia> b = [1 im; 0 -1]
2×2 Matrix{Complex{Int64}}:
1+0im 0+1im
0+0im -1+0im
julia> istriu(b)
true
julia> istriu(b, 1)
false
```
###
`LinearAlgebra.isdiag`Function
```
isdiag(A) -> Bool
```
Test whether a matrix is diagonal.
**Examples**
```
julia> a = [1 2; 2 -1]
2×2 Matrix{Int64}:
1 2
2 -1
julia> isdiag(a)
false
julia> b = [im 0; 0 -im]
2×2 Matrix{Complex{Int64}}:
0+1im 0+0im
0+0im 0-1im
julia> isdiag(b)
true
```
###
`LinearAlgebra.ishermitian`Function
```
ishermitian(A) -> Bool
```
Test whether a matrix is Hermitian.
**Examples**
```
julia> a = [1 2; 2 -1]
2×2 Matrix{Int64}:
1 2
2 -1
julia> ishermitian(a)
true
julia> b = [1 im; -im 1]
2×2 Matrix{Complex{Int64}}:
1+0im 0+1im
0-1im 1+0im
julia> ishermitian(b)
true
```
###
`Base.transpose`Function
```
transpose(A)
```
Lazy transpose. Mutating the returned object should appropriately mutate `A`. Often, but not always, yields `Transpose(A)`, where `Transpose` is a lazy transpose wrapper. Note that this operation is recursive.
This operation is intended for linear algebra usage - for general data manipulation see [`permutedims`](../../base/arrays/index#Base.permutedims), which is non-recursive.
**Examples**
```
julia> A = [3+2im 9+2im; 8+7im 4+6im]
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
julia> transpose(A)
2×2 transpose(::Matrix{Complex{Int64}}) with eltype Complex{Int64}:
3+2im 8+7im
9+2im 4+6im
```
###
`LinearAlgebra.transpose!`Function
```
transpose!(dest,src)
```
Transpose array `src` and store the result in the preallocated array `dest`, which should have a size corresponding to `(size(src,2),size(src,1))`. No in-place transposition is supported and unexpected results will happen if `src` and `dest` have overlapping memory regions.
**Examples**
```
julia> A = [3+2im 9+2im; 8+7im 4+6im]
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
julia> B = zeros(Complex{Int64}, 2, 2)
2×2 Matrix{Complex{Int64}}:
0+0im 0+0im
0+0im 0+0im
julia> transpose!(B, A);
julia> B
2×2 Matrix{Complex{Int64}}:
3+2im 8+7im
9+2im 4+6im
julia> A
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
```
###
`LinearAlgebra.Transpose`Type
```
Transpose
```
Lazy wrapper type for a transpose view of the underlying linear algebra object, usually an `AbstractVector`/`AbstractMatrix`, but also some `Factorization`, for instance. Usually, the `Transpose` constructor should not be called directly, use [`transpose`](#Base.transpose) instead. To materialize the view use [`copy`](../../base/base/index#Base.copy).
This type is intended for linear algebra usage - for general data manipulation see [`permutedims`](../../base/arrays/index#Base.permutedims).
**Examples**
```
julia> A = [3+2im 9+2im; 8+7im 4+6im]
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
julia> transpose(A)
2×2 transpose(::Matrix{Complex{Int64}}) with eltype Complex{Int64}:
3+2im 8+7im
9+2im 4+6im
```
###
`Base.adjoint`Function
```
A'
adjoint(A)
```
Lazy adjoint (conjugate transposition). Note that `adjoint` is applied recursively to elements.
For number types, `adjoint` returns the complex conjugate, and therefore it is equivalent to the identity function for real numbers.
This operation is intended for linear algebra usage - for general data manipulation see [`permutedims`](../../base/arrays/index#Base.permutedims).
**Examples**
```
julia> A = [3+2im 9+2im; 8+7im 4+6im]
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
julia> adjoint(A)
2×2 adjoint(::Matrix{Complex{Int64}}) with eltype Complex{Int64}:
3-2im 8-7im
9-2im 4-6im
julia> x = [3, 4im]
2-element Vector{Complex{Int64}}:
3 + 0im
0 + 4im
julia> x'x
25 + 0im
```
###
`LinearAlgebra.adjoint!`Function
```
adjoint!(dest,src)
```
Conjugate transpose array `src` and store the result in the preallocated array `dest`, which should have a size corresponding to `(size(src,2),size(src,1))`. No in-place transposition is supported and unexpected results will happen if `src` and `dest` have overlapping memory regions.
**Examples**
```
julia> A = [3+2im 9+2im; 8+7im 4+6im]
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
julia> B = zeros(Complex{Int64}, 2, 2)
2×2 Matrix{Complex{Int64}}:
0+0im 0+0im
0+0im 0+0im
julia> adjoint!(B, A);
julia> B
2×2 Matrix{Complex{Int64}}:
3-2im 8-7im
9-2im 4-6im
julia> A
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
```
###
`LinearAlgebra.Adjoint`Type
```
Adjoint
```
Lazy wrapper type for an adjoint view of the underlying linear algebra object, usually an `AbstractVector`/`AbstractMatrix`, but also some `Factorization`, for instance. Usually, the `Adjoint` constructor should not be called directly, use [`adjoint`](#Base.adjoint) instead. To materialize the view use [`copy`](../../base/base/index#Base.copy).
This type is intended for linear algebra usage - for general data manipulation see [`permutedims`](../../base/arrays/index#Base.permutedims).
**Examples**
```
julia> A = [3+2im 9+2im; 8+7im 4+6im]
2×2 Matrix{Complex{Int64}}:
3+2im 9+2im
8+7im 4+6im
julia> adjoint(A)
2×2 adjoint(::Matrix{Complex{Int64}}) with eltype Complex{Int64}:
3-2im 8-7im
9-2im 4-6im
```
###
`Base.copy`Method
```
copy(A::Transpose)
copy(A::Adjoint)
```
Eagerly evaluate the lazy matrix transpose/adjoint. Note that the transposition is applied recursively to elements.
This operation is intended for linear algebra usage - for general data manipulation see [`permutedims`](../../base/arrays/index#Base.permutedims), which is non-recursive.
**Examples**
```
julia> A = [1 2im; -3im 4]
2×2 Matrix{Complex{Int64}}:
1+0im 0+2im
0-3im 4+0im
julia> T = transpose(A)
2×2 transpose(::Matrix{Complex{Int64}}) with eltype Complex{Int64}:
1+0im 0-3im
0+2im 4+0im
julia> copy(T)
2×2 Matrix{Complex{Int64}}:
1+0im 0-3im
0+2im 4+0im
```
###
`LinearAlgebra.stride1`Function
```
stride1(A) -> Int
```
Return the distance between successive array elements in dimension 1 in units of element size.
**Examples**
```
julia> A = [1,2,3,4]
4-element Vector{Int64}:
1
2
3
4
julia> LinearAlgebra.stride1(A)
1
julia> B = view(A, 2:2:4)
2-element view(::Vector{Int64}, 2:2:4) with eltype Int64:
2
4
julia> LinearAlgebra.stride1(B)
2
```
###
`LinearAlgebra.checksquare`Function
```
LinearAlgebra.checksquare(A)
```
Check that a matrix is square, then return its common dimension. For multiple arguments, return a vector.
**Examples**
```
julia> A = fill(1, (4,4)); B = fill(1, (5,5));
julia> LinearAlgebra.checksquare(A, B)
2-element Vector{Int64}:
4
5
```
###
`LinearAlgebra.peakflops`Function
```
LinearAlgebra.peakflops(n::Integer=2000; parallel::Bool=false)
```
`peakflops` computes the peak flop rate of the computer by using double precision [`gemm!`](#LinearAlgebra.BLAS.gemm!). By default, if no arguments are specified, it multiplies a matrix of size `n x n`, where `n = 2000`. If the underlying BLAS is using multiple threads, higher flop rates are realized. The number of BLAS threads can be set with [`BLAS.set_num_threads(n)`](#LinearAlgebra.BLAS.set_num_threads).
If the keyword argument `parallel` is set to `true`, `peakflops` is run in parallel on all the worker processors. The flop rate of the entire parallel computer is returned. When running in parallel, only 1 BLAS thread is used. The argument `n` still refers to the size of the problem that is solved on each processor.
This function requires at least Julia 1.1. In Julia 1.0 it is available from the standard library `InteractiveUtils`.
[Low-level matrix operations](#Low-level-matrix-operations)
------------------------------------------------------------
In many cases there are in-place versions of matrix operations that allow you to supply a pre-allocated output vector or matrix. This is useful when optimizing critical code in order to avoid the overhead of repeated allocations. These in-place operations are suffixed with `!` below (e.g. `mul!`) according to the usual Julia convention.
###
`LinearAlgebra.mul!`Function
```
mul!(Y, A, B) -> Y
```
Calculates the matrix-matrix or matrix-vector product $AB$ and stores the result in `Y`, overwriting the existing value of `Y`. Note that `Y` must not be aliased with either `A` or `B`.
**Examples**
```
julia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; Y = similar(B); mul!(Y, A, B);
julia> Y
2×2 Matrix{Float64}:
3.0 3.0
7.0 7.0
```
**Implementation**
For custom matrix and vector types, it is recommended to implement 5-argument `mul!` rather than implementing 3-argument `mul!` directly if possible.
```
mul!(C, A, B, α, β) -> C
```
Combined inplace matrix-matrix or matrix-vector multiply-add $A B α + C β$. The result is stored in `C` by overwriting it. Note that `C` must not be aliased with either `A` or `B`.
Five-argument `mul!` requires at least Julia 1.3.
**Examples**
```
julia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; C=[1.0 2.0; 3.0 4.0];
julia> mul!(C, A, B, 100.0, 10.0) === C
true
julia> C
2×2 Matrix{Float64}:
310.0 320.0
730.0 740.0
```
###
`LinearAlgebra.lmul!`Function
```
lmul!(a::Number, B::AbstractArray)
```
Scale an array `B` by a scalar `a` overwriting `B` in-place. Use [`rmul!`](#LinearAlgebra.rmul!) to multiply scalar from right. The scaling operation respects the semantics of the multiplication [`*`](#) between `a` and an element of `B`. In particular, this also applies to multiplication involving non-finite numbers such as `NaN` and `±Inf`.
Prior to Julia 1.1, `NaN` and `±Inf` entries in `B` were treated inconsistently.
**Examples**
```
julia> B = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> lmul!(2, B)
2×2 Matrix{Int64}:
2 4
6 8
julia> lmul!(0.0, [Inf])
1-element Vector{Float64}:
NaN
```
```
lmul!(A, B)
```
Calculate the matrix-matrix product $AB$, overwriting `B`, and return the result. Here, `A` must be of special matrix type, like, e.g., [`Diagonal`](#LinearAlgebra.Diagonal), [`UpperTriangular`](#LinearAlgebra.UpperTriangular) or [`LowerTriangular`](#LinearAlgebra.LowerTriangular), or of some orthogonal type, see [`QR`](#LinearAlgebra.QR).
**Examples**
```
julia> B = [0 1; 1 0];
julia> A = LinearAlgebra.UpperTriangular([1 2; 0 3]);
julia> LinearAlgebra.lmul!(A, B);
julia> B
2×2 Matrix{Int64}:
2 1
3 0
julia> B = [1.0 2.0; 3.0 4.0];
julia> F = qr([0 1; -1 0]);
julia> lmul!(F.Q, B)
2×2 Matrix{Float64}:
3.0 4.0
1.0 2.0
```
###
`LinearAlgebra.rmul!`Function
```
rmul!(A::AbstractArray, b::Number)
```
Scale an array `A` by a scalar `b` overwriting `A` in-place. Use [`lmul!`](#LinearAlgebra.lmul!) to multiply scalar from left. The scaling operation respects the semantics of the multiplication [`*`](#) between an element of `A` and `b`. In particular, this also applies to multiplication involving non-finite numbers such as `NaN` and `±Inf`.
Prior to Julia 1.1, `NaN` and `±Inf` entries in `A` were treated inconsistently.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rmul!(A, 2)
2×2 Matrix{Int64}:
2 4
6 8
julia> rmul!([NaN], 0.0)
1-element Vector{Float64}:
NaN
```
```
rmul!(A, B)
```
Calculate the matrix-matrix product $AB$, overwriting `A`, and return the result. Here, `B` must be of special matrix type, like, e.g., [`Diagonal`](#LinearAlgebra.Diagonal), [`UpperTriangular`](#LinearAlgebra.UpperTriangular) or [`LowerTriangular`](#LinearAlgebra.LowerTriangular), or of some orthogonal type, see [`QR`](#LinearAlgebra.QR).
**Examples**
```
julia> A = [0 1; 1 0];
julia> B = LinearAlgebra.UpperTriangular([1 2; 0 3]);
julia> LinearAlgebra.rmul!(A, B);
julia> A
2×2 Matrix{Int64}:
0 3
1 2
julia> A = [1.0 2.0; 3.0 4.0];
julia> F = qr([0 1; -1 0]);
julia> rmul!(A, F.Q)
2×2 Matrix{Float64}:
2.0 1.0
4.0 3.0
```
###
`LinearAlgebra.ldiv!`Function
```
ldiv!(Y, A, B) -> Y
```
Compute `A \ B` in-place and store the result in `Y`, returning the result.
The argument `A` should *not* be a matrix. Rather, instead of matrices it should be a factorization object (e.g. produced by [`factorize`](#LinearAlgebra.factorize) or [`cholesky`](#LinearAlgebra.cholesky)). The reason for this is that factorization itself is both expensive and typically allocates memory (although it can also be done in-place via, e.g., [`lu!`](#LinearAlgebra.lu!)), and performance-critical situations requiring `ldiv!` usually also require fine-grained control over the factorization of `A`.
**Examples**
```
julia> A = [1 2.2 4; 3.1 0.2 3; 4 1 2];
julia> X = [1; 2.5; 3];
julia> Y = zero(X);
julia> ldiv!(Y, qr(A), X);
julia> Y
3-element Vector{Float64}:
0.7128099173553719
-0.051652892561983674
0.10020661157024757
julia> A\X
3-element Vector{Float64}:
0.7128099173553719
-0.05165289256198333
0.10020661157024785
```
```
ldiv!(A, B)
```
Compute `A \ B` in-place and overwriting `B` to store the result.
The argument `A` should *not* be a matrix. Rather, instead of matrices it should be a factorization object (e.g. produced by [`factorize`](#LinearAlgebra.factorize) or [`cholesky`](#LinearAlgebra.cholesky)). The reason for this is that factorization itself is both expensive and typically allocates memory (although it can also be done in-place via, e.g., [`lu!`](#LinearAlgebra.lu!)), and performance-critical situations requiring `ldiv!` usually also require fine-grained control over the factorization of `A`.
**Examples**
```
julia> A = [1 2.2 4; 3.1 0.2 3; 4 1 2];
julia> X = [1; 2.5; 3];
julia> Y = copy(X);
julia> ldiv!(qr(A), X);
julia> X
3-element Vector{Float64}:
0.7128099173553719
-0.051652892561983674
0.10020661157024757
julia> A\Y
3-element Vector{Float64}:
0.7128099173553719
-0.05165289256198333
0.10020661157024785
```
```
ldiv!(a::Number, B::AbstractArray)
```
Divide each entry in an array `B` by a scalar `a` overwriting `B` in-place. Use [`rdiv!`](#LinearAlgebra.rdiv!) to divide scalar from right.
**Examples**
```
julia> B = [1.0 2.0; 3.0 4.0]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> ldiv!(2.0, B)
2×2 Matrix{Float64}:
0.5 1.0
1.5 2.0
```
###
`LinearAlgebra.rdiv!`Function
```
rdiv!(A, B)
```
Compute `A / B` in-place and overwriting `A` to store the result.
The argument `B` should *not* be a matrix. Rather, instead of matrices it should be a factorization object (e.g. produced by [`factorize`](#LinearAlgebra.factorize) or [`cholesky`](#LinearAlgebra.cholesky)). The reason for this is that factorization itself is both expensive and typically allocates memory (although it can also be done in-place via, e.g., [`lu!`](#LinearAlgebra.lu!)), and performance-critical situations requiring `rdiv!` usually also require fine-grained control over the factorization of `B`.
```
rdiv!(A::AbstractArray, b::Number)
```
Divide each entry in an array `A` by a scalar `b` overwriting `A` in-place. Use [`ldiv!`](#LinearAlgebra.ldiv!) to divide scalar from left.
**Examples**
```
julia> A = [1.0 2.0; 3.0 4.0]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> rdiv!(A, 2.0)
2×2 Matrix{Float64}:
0.5 1.0
1.5 2.0
```
[BLAS functions](#BLAS-functions)
----------------------------------
In Julia (as in much of scientific computation), dense linear-algebra operations are based on the [LAPACK library](http://www.netlib.org/lapack/), which in turn is built on top of basic linear-algebra building-blocks known as the [BLAS](http://www.netlib.org/blas/). There are highly optimized implementations of BLAS available for every computer architecture, and sometimes in high-performance linear algebra routines it is useful to call the BLAS functions directly.
`LinearAlgebra.BLAS` provides wrappers for some of the BLAS functions. Those BLAS functions that overwrite one of the input arrays have names ending in `'!'`. Usually, a BLAS function has four methods defined, for [`Float64`](../../base/numbers/index#Core.Float64), [`Float32`](../../base/numbers/index#Core.Float32), `ComplexF64`, and `ComplexF32` arrays.
###
[BLAS character arguments](#stdlib-blas-chars)
Many BLAS functions accept arguments that determine whether to transpose an argument (`trans`), which triangle of a matrix to reference (`uplo` or `ul`), whether the diagonal of a triangular matrix can be assumed to be all ones (`dA`) or which side of a matrix multiplication the input argument belongs on (`side`). The possibilities are:
####
[Multiplication order](#stdlib-blas-side)
| `side` | Meaning |
| --- | --- |
| `'L'` | The argument goes on the *left* side of a matrix-matrix operation. |
| `'R'` | The argument goes on the *right* side of a matrix-matrix operation. |
####
[Triangle referencing](#stdlib-blas-uplo)
| `uplo`/`ul` | Meaning |
| --- | --- |
| `'U'` | Only the *upper* triangle of the matrix will be used. |
| `'L'` | Only the *lower* triangle of the matrix will be used. |
####
[Transposition operation](#stdlib-blas-trans)
| `trans`/`tX` | Meaning |
| --- | --- |
| `'N'` | The input matrix `X` is not transposed or conjugated. |
| `'T'` | The input matrix `X` will be transposed. |
| `'C'` | The input matrix `X` will be conjugated and transposed. |
####
[Unit diagonal](#stdlib-blas-diag)
| `diag`/`dX` | Meaning |
| --- | --- |
| `'N'` | The diagonal values of the matrix `X` will be read. |
| `'U'` | The diagonal of the matrix `X` is assumed to be all ones. |
###
`LinearAlgebra.BLAS`Module
Interface to BLAS subroutines.
###
`LinearAlgebra.BLAS.dot`Function
```
dot(n, X, incx, Y, incy)
```
Dot product of two vectors consisting of `n` elements of array `X` with stride `incx` and `n` elements of array `Y` with stride `incy`.
**Examples**
```
julia> BLAS.dot(10, fill(1.0, 10), 1, fill(1.0, 20), 2)
10.0
```
###
`LinearAlgebra.BLAS.dotu`Function
```
dotu(n, X, incx, Y, incy)
```
Dot function for two complex vectors consisting of `n` elements of array `X` with stride `incx` and `n` elements of array `Y` with stride `incy`.
**Examples**
```
julia> BLAS.dotu(10, fill(1.0im, 10), 1, fill(1.0+im, 20), 2)
-10.0 + 10.0im
```
###
`LinearAlgebra.BLAS.dotc`Function
```
dotc(n, X, incx, U, incy)
```
Dot function for two complex vectors, consisting of `n` elements of array `X` with stride `incx` and `n` elements of array `U` with stride `incy`, conjugating the first vector.
**Examples**
```
julia> BLAS.dotc(10, fill(1.0im, 10), 1, fill(1.0+im, 20), 2)
10.0 - 10.0im
```
###
`LinearAlgebra.BLAS.blascopy!`Function
```
blascopy!(n, X, incx, Y, incy)
```
Copy `n` elements of array `X` with stride `incx` to array `Y` with stride `incy`. Returns `Y`.
###
`LinearAlgebra.BLAS.nrm2`Function
```
nrm2(n, X, incx)
```
2-norm of a vector consisting of `n` elements of array `X` with stride `incx`.
**Examples**
```
julia> BLAS.nrm2(4, fill(1.0, 8), 2)
2.0
julia> BLAS.nrm2(1, fill(1.0, 8), 2)
1.0
```
###
`LinearAlgebra.BLAS.asum`Function
```
asum(n, X, incx)
```
Sum of the magnitudes of the first `n` elements of array `X` with stride `incx`.
For a real array, the magnitude is the absolute value. For a complex array, the magnitude is the sum of the absolute value of the real part and the absolute value of the imaginary part.
**Examples**
```
julia> BLAS.asum(5, fill(1.0im, 10), 2)
5.0
julia> BLAS.asum(2, fill(1.0im, 10), 5)
2.0
```
###
`LinearAlgebra.axpy!`Function
```
axpy!(a, X, Y)
```
Overwrite `Y` with `X*a + Y`, where `a` is a scalar. Return `Y`.
**Examples**
```
julia> x = [1; 2; 3];
julia> y = [4; 5; 6];
julia> BLAS.axpy!(2, x, y)
3-element Vector{Int64}:
6
9
12
```
###
`LinearAlgebra.axpby!`Function
```
axpby!(a, X, b, Y)
```
Overwrite `Y` with `X*a + Y*b`, where `a` and `b` are scalars. Return `Y`.
**Examples**
```
julia> x = [1., 2, 3];
julia> y = [4., 5, 6];
julia> BLAS.axpby!(2., x, 3., y)
3-element Vector{Float64}:
14.0
19.0
24.0
```
###
`LinearAlgebra.BLAS.scal!`Function
```
scal!(n, a, X, incx)
scal!(a, X)
```
Overwrite `X` with `a*X` for the first `n` elements of array `X` with stride `incx`. Returns `X`.
If `n` and `incx` are not provided, `length(X)` and `stride(X,1)` are used.
###
`LinearAlgebra.BLAS.scal`Function
```
scal(n, a, X, incx)
scal(a, X)
```
Return `X` scaled by `a` for the first `n` elements of array `X` with stride `incx`.
If `n` and `incx` are not provided, `length(X)` and `stride(X,1)` are used.
###
`LinearAlgebra.BLAS.iamax`Function
```
iamax(n, dx, incx)
iamax(dx)
```
Find the index of the element of `dx` with the maximum absolute value. `n` is the length of `dx`, and `incx` is the stride. If `n` and `incx` are not provided, they assume default values of `n=length(dx)` and `incx=stride1(dx)`.
###
`LinearAlgebra.BLAS.ger!`Function
```
ger!(alpha, x, y, A)
```
Rank-1 update of the matrix `A` with vectors `x` and `y` as `alpha*x*y' + A`.
###
`LinearAlgebra.BLAS.syr!`Function
```
syr!(uplo, alpha, x, A)
```
Rank-1 update of the symmetric matrix `A` with vector `x` as `alpha*x*transpose(x) + A`. [`uplo`](#stdlib-blas-uplo) controls which triangle of `A` is updated. Returns `A`.
###
`LinearAlgebra.BLAS.syrk!`Function
```
syrk!(uplo, trans, alpha, A, beta, C)
```
Rank-k update of the symmetric matrix `C` as `alpha*A*transpose(A) + beta*C` or `alpha*transpose(A)*A + beta*C` according to [`trans`](#stdlib-blas-trans). Only the [`uplo`](#stdlib-blas-uplo) triangle of `C` is used. Returns `C`.
###
`LinearAlgebra.BLAS.syrk`Function
```
syrk(uplo, trans, alpha, A)
```
Returns either the upper triangle or the lower triangle of `A`, according to [`uplo`](#stdlib-blas-uplo), of `alpha*A*transpose(A)` or `alpha*transpose(A)*A`, according to [`trans`](#stdlib-blas-trans).
###
`LinearAlgebra.BLAS.syr2k!`Function
```
syr2k!(uplo, trans, alpha, A, B, beta, C)
```
Rank-2k update of the symmetric matrix `C` as `alpha*A*transpose(B) + alpha*B*transpose(A) + beta*C` or `alpha*transpose(A)*B + alpha*transpose(B)*A + beta*C` according to [`trans`](#stdlib-blas-trans). Only the [`uplo`](#stdlib-blas-uplo) triangle of `C` is used. Returns `C`.
###
`LinearAlgebra.BLAS.syr2k`Function
```
syr2k(uplo, trans, alpha, A, B)
```
Returns the [`uplo`](#stdlib-blas-uplo) triangle of `alpha*A*transpose(B) + alpha*B*transpose(A)` or `alpha*transpose(A)*B + alpha*transpose(B)*A`, according to [`trans`](#stdlib-blas-trans).
```
syr2k(uplo, trans, A, B)
```
Returns the [`uplo`](#stdlib-blas-uplo) triangle of `A*transpose(B) + B*transpose(A)` or `transpose(A)*B + transpose(B)*A`, according to [`trans`](#stdlib-blas-trans).
###
`LinearAlgebra.BLAS.her!`Function
```
her!(uplo, alpha, x, A)
```
Methods for complex arrays only. Rank-1 update of the Hermitian matrix `A` with vector `x` as `alpha*x*x' + A`. [`uplo`](#stdlib-blas-uplo) controls which triangle of `A` is updated. Returns `A`.
###
`LinearAlgebra.BLAS.herk!`Function
```
herk!(uplo, trans, alpha, A, beta, C)
```
Methods for complex arrays only. Rank-k update of the Hermitian matrix `C` as `alpha*A*A' + beta*C` or `alpha*A'*A + beta*C` according to [`trans`](#stdlib-blas-trans). Only the [`uplo`](#stdlib-blas-uplo) triangle of `C` is updated. Returns `C`.
###
`LinearAlgebra.BLAS.herk`Function
```
herk(uplo, trans, alpha, A)
```
Methods for complex arrays only. Returns the [`uplo`](#stdlib-blas-uplo) triangle of `alpha*A*A'` or `alpha*A'*A`, according to [`trans`](#stdlib-blas-trans).
###
`LinearAlgebra.BLAS.her2k!`Function
```
her2k!(uplo, trans, alpha, A, B, beta, C)
```
Rank-2k update of the Hermitian matrix `C` as `alpha*A*B' + alpha*B*A' + beta*C` or `alpha*A'*B + alpha*B'*A + beta*C` according to [`trans`](#stdlib-blas-trans). The scalar `beta` has to be real. Only the [`uplo`](#stdlib-blas-uplo) triangle of `C` is used. Returns `C`.
###
`LinearAlgebra.BLAS.her2k`Function
```
her2k(uplo, trans, alpha, A, B)
```
Returns the [`uplo`](#stdlib-blas-uplo) triangle of `alpha*A*B' + alpha*B*A'` or `alpha*A'*B + alpha*B'*A`, according to [`trans`](#stdlib-blas-trans).
```
her2k(uplo, trans, A, B)
```
Returns the [`uplo`](#stdlib-blas-uplo) triangle of `A*B' + B*A'` or `A'*B + B'*A`, according to [`trans`](#stdlib-blas-trans).
###
`LinearAlgebra.BLAS.gbmv!`Function
```
gbmv!(trans, m, kl, ku, alpha, A, x, beta, y)
```
Update vector `y` as `alpha*A*x + beta*y` or `alpha*A'*x + beta*y` according to [`trans`](#stdlib-blas-trans). The matrix `A` is a general band matrix of dimension `m` by `size(A,2)` with `kl` sub-diagonals and `ku` super-diagonals. `alpha` and `beta` are scalars. Return the updated `y`.
###
`LinearAlgebra.BLAS.gbmv`Function
```
gbmv(trans, m, kl, ku, alpha, A, x)
```
Return `alpha*A*x` or `alpha*A'*x` according to [`trans`](#stdlib-blas-trans). The matrix `A` is a general band matrix of dimension `m` by `size(A,2)` with `kl` sub-diagonals and `ku` super-diagonals, and `alpha` is a scalar.
###
`LinearAlgebra.BLAS.sbmv!`Function
```
sbmv!(uplo, k, alpha, A, x, beta, y)
```
Update vector `y` as `alpha*A*x + beta*y` where `A` is a symmetric band matrix of order `size(A,2)` with `k` super-diagonals stored in the argument `A`. The storage layout for `A` is described the reference BLAS module, level-2 BLAS at <http://www.netlib.org/lapack/explore-html/>. Only the [`uplo`](#stdlib-blas-uplo) triangle of `A` is used.
Return the updated `y`.
###
`LinearAlgebra.BLAS.sbmv`Method
```
sbmv(uplo, k, alpha, A, x)
```
Return `alpha*A*x` where `A` is a symmetric band matrix of order `size(A,2)` with `k` super-diagonals stored in the argument `A`. Only the [`uplo`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.sbmv`Method
```
sbmv(uplo, k, A, x)
```
Return `A*x` where `A` is a symmetric band matrix of order `size(A,2)` with `k` super-diagonals stored in the argument `A`. Only the [`uplo`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.gemm!`Function
```
gemm!(tA, tB, alpha, A, B, beta, C)
```
Update `C` as `alpha*A*B + beta*C` or the other three variants according to [`tA`](#stdlib-blas-trans) and `tB`. Return the updated `C`.
###
`LinearAlgebra.BLAS.gemm`Method
```
gemm(tA, tB, alpha, A, B)
```
Return `alpha*A*B` or the other three variants according to [`tA`](#stdlib-blas-trans) and `tB`.
###
`LinearAlgebra.BLAS.gemm`Method
```
gemm(tA, tB, A, B)
```
Return `A*B` or the other three variants according to [`tA`](#stdlib-blas-trans) and `tB`.
###
`LinearAlgebra.BLAS.gemv!`Function
```
gemv!(tA, alpha, A, x, beta, y)
```
Update the vector `y` as `alpha*A*x + beta*y` or `alpha*A'x + beta*y` according to [`tA`](#stdlib-blas-trans). `alpha` and `beta` are scalars. Return the updated `y`.
###
`LinearAlgebra.BLAS.gemv`Method
```
gemv(tA, alpha, A, x)
```
Return `alpha*A*x` or `alpha*A'x` according to [`tA`](#stdlib-blas-trans). `alpha` is a scalar.
###
`LinearAlgebra.BLAS.gemv`Method
```
gemv(tA, A, x)
```
Return `A*x` or `A'x` according to [`tA`](#stdlib-blas-trans).
###
`LinearAlgebra.BLAS.symm!`Function
```
symm!(side, ul, alpha, A, B, beta, C)
```
Update `C` as `alpha*A*B + beta*C` or `alpha*B*A + beta*C` according to [`side`](#stdlib-blas-side). `A` is assumed to be symmetric. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. Return the updated `C`.
###
`LinearAlgebra.BLAS.symm`Method
```
symm(side, ul, alpha, A, B)
```
Return `alpha*A*B` or `alpha*B*A` according to [`side`](#stdlib-blas-side). `A` is assumed to be symmetric. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.symm`Method
```
symm(side, ul, A, B)
```
Return `A*B` or `B*A` according to [`side`](#stdlib-blas-side). `A` is assumed to be symmetric. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.symv!`Function
```
symv!(ul, alpha, A, x, beta, y)
```
Update the vector `y` as `alpha*A*x + beta*y`. `A` is assumed to be symmetric. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. `alpha` and `beta` are scalars. Return the updated `y`.
###
`LinearAlgebra.BLAS.symv`Method
```
symv(ul, alpha, A, x)
```
Return `alpha*A*x`. `A` is assumed to be symmetric. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. `alpha` is a scalar.
###
`LinearAlgebra.BLAS.symv`Method
```
symv(ul, A, x)
```
Return `A*x`. `A` is assumed to be symmetric. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.hemm!`Function
```
hemm!(side, ul, alpha, A, B, beta, C)
```
Update `C` as `alpha*A*B + beta*C` or `alpha*B*A + beta*C` according to [`side`](#stdlib-blas-side). `A` is assumed to be Hermitian. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. Return the updated `C`.
###
`LinearAlgebra.BLAS.hemm`Method
```
hemm(side, ul, alpha, A, B)
```
Return `alpha*A*B` or `alpha*B*A` according to [`side`](#stdlib-blas-side). `A` is assumed to be Hermitian. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.hemm`Method
```
hemm(side, ul, A, B)
```
Return `A*B` or `B*A` according to [`side`](#stdlib-blas-side). `A` is assumed to be Hermitian. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.hemv!`Function
```
hemv!(ul, alpha, A, x, beta, y)
```
Update the vector `y` as `alpha*A*x + beta*y`. `A` is assumed to be Hermitian. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. `alpha` and `beta` are scalars. Return the updated `y`.
###
`LinearAlgebra.BLAS.hemv`Method
```
hemv(ul, alpha, A, x)
```
Return `alpha*A*x`. `A` is assumed to be Hermitian. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. `alpha` is a scalar.
###
`LinearAlgebra.BLAS.hemv`Method
```
hemv(ul, A, x)
```
Return `A*x`. `A` is assumed to be Hermitian. Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used.
###
`LinearAlgebra.BLAS.trmm!`Function
```
trmm!(side, ul, tA, dA, alpha, A, B)
```
Update `B` as `alpha*A*B` or one of the other three variants determined by [`side`](#stdlib-blas-side) and [`tA`](#stdlib-blas-trans). Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones. Returns the updated `B`.
###
`LinearAlgebra.BLAS.trmm`Function
```
trmm(side, ul, tA, dA, alpha, A, B)
```
Returns `alpha*A*B` or one of the other three variants determined by [`side`](#stdlib-blas-side) and [`tA`](#stdlib-blas-trans). Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones.
###
`LinearAlgebra.BLAS.trsm!`Function
```
trsm!(side, ul, tA, dA, alpha, A, B)
```
Overwrite `B` with the solution to `A*X = alpha*B` or one of the other three variants determined by [`side`](#stdlib-blas-side) and [`tA`](#stdlib-blas-trans). Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones. Returns the updated `B`.
###
`LinearAlgebra.BLAS.trsm`Function
```
trsm(side, ul, tA, dA, alpha, A, B)
```
Return the solution to `A*X = alpha*B` or one of the other three variants determined by determined by [`side`](#stdlib-blas-side) and [`tA`](#stdlib-blas-trans). Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones.
###
`LinearAlgebra.BLAS.trmv!`Function
```
trmv!(ul, tA, dA, A, b)
```
Return `op(A)*b`, where `op` is determined by [`tA`](#stdlib-blas-trans). Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones. The multiplication occurs in-place on `b`.
###
`LinearAlgebra.BLAS.trmv`Function
```
trmv(ul, tA, dA, A, b)
```
Return `op(A)*b`, where `op` is determined by [`tA`](#stdlib-blas-trans). Only the [`ul`](#stdlib-blas-uplo) triangle of `A` is used. [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones.
###
`LinearAlgebra.BLAS.trsv!`Function
```
trsv!(ul, tA, dA, A, b)
```
Overwrite `b` with the solution to `A*x = b` or one of the other two variants determined by [`tA`](#stdlib-blas-trans) and [`ul`](#stdlib-blas-uplo). [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones. Return the updated `b`.
###
`LinearAlgebra.BLAS.trsv`Function
```
trsv(ul, tA, dA, A, b)
```
Return the solution to `A*x = b` or one of the other two variants determined by [`tA`](#stdlib-blas-trans) and [`ul`](#stdlib-blas-uplo). [`dA`](#stdlib-blas-diag) determines if the diagonal values are read or are assumed to be all ones.
###
`LinearAlgebra.BLAS.set_num_threads`Function
```
set_num_threads(n::Integer)
set_num_threads(::Nothing)
```
Set the number of threads the BLAS library should use equal to `n::Integer`.
Also accepts `nothing`, in which case julia tries to guess the default number of threads. Passing `nothing` is discouraged and mainly exists for historical reasons.
###
`LinearAlgebra.BLAS.get_num_threads`Function
```
get_num_threads()
```
Get the number of threads the BLAS library is using.
`get_num_threads` requires at least Julia 1.6.
[LAPACK functions](#LAPACK-functions)
--------------------------------------
`LinearAlgebra.LAPACK` provides wrappers for some of the LAPACK functions for linear algebra. Those functions that overwrite one of the input arrays have names ending in `'!'`.
Usually a function has 4 methods defined, one each for [`Float64`](../../base/numbers/index#Core.Float64), [`Float32`](../../base/numbers/index#Core.Float32), `ComplexF64` and `ComplexF32` arrays.
Note that the LAPACK API provided by Julia can and will change in the future. Since this API is not user-facing, there is no commitment to support/deprecate this specific set of functions in future releases.
###
`LinearAlgebra.LAPACK`Module
Interfaces to LAPACK subroutines.
###
`LinearAlgebra.LAPACK.gbtrf!`Function
```
gbtrf!(kl, ku, m, AB) -> (AB, ipiv)
```
Compute the LU factorization of a banded matrix `AB`. `kl` is the first subdiagonal containing a nonzero band, `ku` is the last superdiagonal containing one, and `m` is the first dimension of the matrix `AB`. Returns the LU factorization in-place and `ipiv`, the vector of pivots used.
###
`LinearAlgebra.LAPACK.gbtrs!`Function
```
gbtrs!(trans, kl, ku, m, AB, ipiv, B)
```
Solve the equation `AB * X = B`. `trans` determines the orientation of `AB`. It may be `N` (no transpose), `T` (transpose), or `C` (conjugate transpose). `kl` is the first subdiagonal containing a nonzero band, `ku` is the last superdiagonal containing one, and `m` is the first dimension of the matrix `AB`. `ipiv` is the vector of pivots returned from `gbtrf!`. Returns the vector or matrix `X`, overwriting `B` in-place.
###
`LinearAlgebra.LAPACK.gebal!`Function
```
gebal!(job, A) -> (ilo, ihi, scale)
```
Balance the matrix `A` before computing its eigensystem or Schur factorization. `job` can be one of `N` (`A` will not be permuted or scaled), `P` (`A` will only be permuted), `S` (`A` will only be scaled), or `B` (`A` will be both permuted and scaled). Modifies `A` in-place and returns `ilo`, `ihi`, and `scale`. If permuting was turned on, `A[i,j] = 0` if `j > i` and `1 < j < ilo` or `j > ihi`. `scale` contains information about the scaling/permutations performed.
###
`LinearAlgebra.LAPACK.gebak!`Function
```
gebak!(job, side, ilo, ihi, scale, V)
```
Transform the eigenvectors `V` of a matrix balanced using `gebal!` to the unscaled/unpermuted eigenvectors of the original matrix. Modifies `V` in-place. `side` can be `L` (left eigenvectors are transformed) or `R` (right eigenvectors are transformed).
###
`LinearAlgebra.LAPACK.gebrd!`Function
```
gebrd!(A) -> (A, d, e, tauq, taup)
```
Reduce `A` in-place to bidiagonal form `A = QBP'`. Returns `A`, containing the bidiagonal matrix `B`; `d`, containing the diagonal elements of `B`; `e`, containing the off-diagonal elements of `B`; `tauq`, containing the elementary reflectors representing `Q`; and `taup`, containing the elementary reflectors representing `P`.
###
`LinearAlgebra.LAPACK.gelqf!`Function
```
gelqf!(A, tau)
```
Compute the `LQ` factorization of `A`, `A = LQ`. `tau` contains scalars which parameterize the elementary reflectors of the factorization. `tau` must have length greater than or equal to the smallest dimension of `A`.
Returns `A` and `tau` modified in-place.
```
gelqf!(A) -> (A, tau)
```
Compute the `LQ` factorization of `A`, `A = LQ`.
Returns `A`, modified in-place, and `tau`, which contains scalars which parameterize the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.geqlf!`Function
```
geqlf!(A, tau)
```
Compute the `QL` factorization of `A`, `A = QL`. `tau` contains scalars which parameterize the elementary reflectors of the factorization. `tau` must have length greater than or equal to the smallest dimension of `A`.
Returns `A` and `tau` modified in-place.
```
geqlf!(A) -> (A, tau)
```
Compute the `QL` factorization of `A`, `A = QL`.
Returns `A`, modified in-place, and `tau`, which contains scalars which parameterize the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.geqrf!`Function
```
geqrf!(A, tau)
```
Compute the `QR` factorization of `A`, `A = QR`. `tau` contains scalars which parameterize the elementary reflectors of the factorization. `tau` must have length greater than or equal to the smallest dimension of `A`.
Returns `A` and `tau` modified in-place.
```
geqrf!(A) -> (A, tau)
```
Compute the `QR` factorization of `A`, `A = QR`.
Returns `A`, modified in-place, and `tau`, which contains scalars which parameterize the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.geqp3!`Function
```
geqp3!(A, [jpvt, tau]) -> (A, tau, jpvt)
```
Compute the pivoted `QR` factorization of `A`, `AP = QR` using BLAS level 3. `P` is a pivoting matrix, represented by `jpvt`. `tau` stores the elementary reflectors. The arguments `jpvt` and `tau` are optional and allow for passing preallocated arrays. When passed, `jpvt` must have length greater than or equal to `n` if `A` is an `(m x n)` matrix and `tau` must have length greater than or equal to the smallest dimension of `A`.
`A`, `jpvt`, and `tau` are modified in-place.
###
`LinearAlgebra.LAPACK.gerqf!`Function
```
gerqf!(A, tau)
```
Compute the `RQ` factorization of `A`, `A = RQ`. `tau` contains scalars which parameterize the elementary reflectors of the factorization. `tau` must have length greater than or equal to the smallest dimension of `A`.
Returns `A` and `tau` modified in-place.
```
gerqf!(A) -> (A, tau)
```
Compute the `RQ` factorization of `A`, `A = RQ`.
Returns `A`, modified in-place, and `tau`, which contains scalars which parameterize the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.geqrt!`Function
```
geqrt!(A, T)
```
Compute the blocked `QR` factorization of `A`, `A = QR`. `T` contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization. The first dimension of `T` sets the block size and it must be between 1 and `n`. The second dimension of `T` must equal the smallest dimension of `A`.
Returns `A` and `T` modified in-place.
```
geqrt!(A, nb) -> (A, T)
```
Compute the blocked `QR` factorization of `A`, `A = QR`. `nb` sets the block size and it must be between 1 and `n`, the second dimension of `A`.
Returns `A`, modified in-place, and `T`, which contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.geqrt3!`Function
```
geqrt3!(A, T)
```
Recursively computes the blocked `QR` factorization of `A`, `A = QR`. `T` contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization. The first dimension of `T` sets the block size and it must be between 1 and `n`. The second dimension of `T` must equal the smallest dimension of `A`.
Returns `A` and `T` modified in-place.
```
geqrt3!(A) -> (A, T)
```
Recursively computes the blocked `QR` factorization of `A`, `A = QR`.
Returns `A`, modified in-place, and `T`, which contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.getrf!`Function
```
getrf!(A) -> (A, ipiv, info)
```
Compute the pivoted `LU` factorization of `A`, `A = LU`.
Returns `A`, modified in-place, `ipiv`, the pivoting information, and an `info` code which indicates success (`info = 0`), a singular value in `U` (`info = i`, in which case `U[i,i]` is singular), or an error code (`info < 0`).
###
`LinearAlgebra.LAPACK.tzrzf!`Function
```
tzrzf!(A) -> (A, tau)
```
Transforms the upper trapezoidal matrix `A` to upper triangular form in-place. Returns `A` and `tau`, the scalar parameters for the elementary reflectors of the transformation.
###
`LinearAlgebra.LAPACK.ormrz!`Function
```
ormrz!(side, trans, A, tau, C)
```
Multiplies the matrix `C` by `Q` from the transformation supplied by `tzrzf!`. Depending on `side` or `trans` the multiplication can be left-sided (`side = L, Q*C`) or right-sided (`side = R, C*Q`) and `Q` can be unmodified (`trans = N`), transposed (`trans = T`), or conjugate transposed (`trans = C`). Returns matrix `C` which is modified in-place with the result of the multiplication.
###
`LinearAlgebra.LAPACK.gels!`Function
```
gels!(trans, A, B) -> (F, B, ssr)
```
Solves the linear equation `A * X = B`, `transpose(A) * X = B`, or `adjoint(A) * X = B` using a QR or LQ factorization. Modifies the matrix/vector `B` in place with the solution. `A` is overwritten with its `QR` or `LQ` factorization. `trans` may be one of `N` (no modification), `T` (transpose), or `C` (conjugate transpose). `gels!` searches for the minimum norm/least squares solution. `A` may be under or over determined. The solution is returned in `B`.
###
`LinearAlgebra.LAPACK.gesv!`Function
```
gesv!(A, B) -> (B, A, ipiv)
```
Solves the linear equation `A * X = B` where `A` is a square matrix using the `LU` factorization of `A`. `A` is overwritten with its `LU` factorization and `B` is overwritten with the solution `X`. `ipiv` contains the pivoting information for the `LU` factorization of `A`.
###
`LinearAlgebra.LAPACK.getrs!`Function
```
getrs!(trans, A, ipiv, B)
```
Solves the linear equation `A * X = B`, `transpose(A) * X = B`, or `adjoint(A) * X = B` for square `A`. Modifies the matrix/vector `B` in place with the solution. `A` is the `LU` factorization from `getrf!`, with `ipiv` the pivoting information. `trans` may be one of `N` (no modification), `T` (transpose), or `C` (conjugate transpose).
###
`LinearAlgebra.LAPACK.getri!`Function
```
getri!(A, ipiv)
```
Computes the inverse of `A`, using its `LU` factorization found by `getrf!`. `ipiv` is the pivot information output and `A` contains the `LU` factorization of `getrf!`. `A` is overwritten with its inverse.
###
`LinearAlgebra.LAPACK.gesvx!`Function
```
gesvx!(fact, trans, A, AF, ipiv, equed, R, C, B) -> (X, equed, R, C, B, rcond, ferr, berr, work)
```
Solves the linear equation `A * X = B` (`trans = N`), `transpose(A) * X = B` (`trans = T`), or `adjoint(A) * X = B` (`trans = C`) using the `LU` factorization of `A`. `fact` may be `E`, in which case `A` will be equilibrated and copied to `AF`; `F`, in which case `AF` and `ipiv` from a previous `LU` factorization are inputs; or `N`, in which case `A` will be copied to `AF` and then factored. If `fact = F`, `equed` may be `N`, meaning `A` has not been equilibrated; `R`, meaning `A` was multiplied by `Diagonal(R)` from the left; `C`, meaning `A` was multiplied by `Diagonal(C)` from the right; or `B`, meaning `A` was multiplied by `Diagonal(R)` from the left and `Diagonal(C)` from the right. If `fact = F` and `equed = R` or `B` the elements of `R` must all be positive. If `fact = F` and `equed = C` or `B` the elements of `C` must all be positive.
Returns the solution `X`; `equed`, which is an output if `fact` is not `N`, and describes the equilibration that was performed; `R`, the row equilibration diagonal; `C`, the column equilibration diagonal; `B`, which may be overwritten with its equilibrated form `Diagonal(R)*B` (if `trans = N` and `equed = R,B`) or `Diagonal(C)*B` (if `trans = T,C` and `equed = C,B`); `rcond`, the reciprocal condition number of `A` after equilbrating; `ferr`, the forward error bound for each solution vector in `X`; `berr`, the forward error bound for each solution vector in `X`; and `work`, the reciprocal pivot growth factor.
```
gesvx!(A, B)
```
The no-equilibration, no-transpose simplification of `gesvx!`.
###
`LinearAlgebra.LAPACK.gelsd!`Function
```
gelsd!(A, B, rcond) -> (B, rnk)
```
Computes the least norm solution of `A * X = B` by finding the `SVD` factorization of `A`, then dividing-and-conquering the problem. `B` is overwritten with the solution `X`. Singular values below `rcond` will be treated as zero. Returns the solution in `B` and the effective rank of `A` in `rnk`.
###
`LinearAlgebra.LAPACK.gelsy!`Function
```
gelsy!(A, B, rcond) -> (B, rnk)
```
Computes the least norm solution of `A * X = B` by finding the full `QR` factorization of `A`, then dividing-and-conquering the problem. `B` is overwritten with the solution `X`. Singular values below `rcond` will be treated as zero. Returns the solution in `B` and the effective rank of `A` in `rnk`.
###
`LinearAlgebra.LAPACK.gglse!`Function
```
gglse!(A, c, B, d) -> (X,res)
```
Solves the equation `A * x = c` where `x` is subject to the equality constraint `B * x = d`. Uses the formula `||c - A*x||^2 = 0` to solve. Returns `X` and the residual sum-of-squares.
###
`LinearAlgebra.LAPACK.geev!`Function
```
geev!(jobvl, jobvr, A) -> (W, VL, VR)
```
Finds the eigensystem of `A`. If `jobvl = N`, the left eigenvectors of `A` aren't computed. If `jobvr = N`, the right eigenvectors of `A` aren't computed. If `jobvl = V` or `jobvr = V`, the corresponding eigenvectors are computed. Returns the eigenvalues in `W`, the right eigenvectors in `VR`, and the left eigenvectors in `VL`.
###
`LinearAlgebra.LAPACK.gesdd!`Function
```
gesdd!(job, A) -> (U, S, VT)
```
Finds the singular value decomposition of `A`, `A = U * S * V'`, using a divide and conquer approach. If `job = A`, all the columns of `U` and the rows of `V'` are computed. If `job = N`, no columns of `U` or rows of `V'` are computed. If `job = O`, `A` is overwritten with the columns of (thin) `U` and the rows of (thin) `V'`. If `job = S`, the columns of (thin) `U` and the rows of (thin) `V'` are computed and returned separately.
###
`LinearAlgebra.LAPACK.gesvd!`Function
```
gesvd!(jobu, jobvt, A) -> (U, S, VT)
```
Finds the singular value decomposition of `A`, `A = U * S * V'`. If `jobu = A`, all the columns of `U` are computed. If `jobvt = A` all the rows of `V'` are computed. If `jobu = N`, no columns of `U` are computed. If `jobvt = N` no rows of `V'` are computed. If `jobu = O`, `A` is overwritten with the columns of (thin) `U`. If `jobvt = O`, `A` is overwritten with the rows of (thin) `V'`. If `jobu = S`, the columns of (thin) `U` are computed and returned separately. If `jobvt = S` the rows of (thin) `V'` are computed and returned separately. `jobu` and `jobvt` can't both be `O`.
Returns `U`, `S`, and `Vt`, where `S` are the singular values of `A`.
###
`LinearAlgebra.LAPACK.ggsvd!`Function
```
ggsvd!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R)
```
Finds the generalized singular value decomposition of `A` and `B`, `U'*A*Q = D1*R` and `V'*B*Q = D2*R`. `D1` has `alpha` on its diagonal and `D2` has `beta` on its diagonal. If `jobu = U`, the orthogonal/unitary matrix `U` is computed. If `jobv = V` the orthogonal/unitary matrix `V` is computed. If `jobq = Q`, the orthogonal/unitary matrix `Q` is computed. If `jobu`, `jobv` or `jobq` is `N`, that matrix is not computed. This function is only available in LAPACK versions prior to 3.6.0.
###
`LinearAlgebra.LAPACK.ggsvd3!`Function
```
ggsvd3!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R)
```
Finds the generalized singular value decomposition of `A` and `B`, `U'*A*Q = D1*R` and `V'*B*Q = D2*R`. `D1` has `alpha` on its diagonal and `D2` has `beta` on its diagonal. If `jobu = U`, the orthogonal/unitary matrix `U` is computed. If `jobv = V` the orthogonal/unitary matrix `V` is computed. If `jobq = Q`, the orthogonal/unitary matrix `Q` is computed. If `jobu`, `jobv`, or `jobq` is `N`, that matrix is not computed. This function requires LAPACK 3.6.0.
###
`LinearAlgebra.LAPACK.geevx!`Function
```
geevx!(balanc, jobvl, jobvr, sense, A) -> (A, w, VL, VR, ilo, ihi, scale, abnrm, rconde, rcondv)
```
Finds the eigensystem of `A` with matrix balancing. If `jobvl = N`, the left eigenvectors of `A` aren't computed. If `jobvr = N`, the right eigenvectors of `A` aren't computed. If `jobvl = V` or `jobvr = V`, the corresponding eigenvectors are computed. If `balanc = N`, no balancing is performed. If `balanc = P`, `A` is permuted but not scaled. If `balanc = S`, `A` is scaled but not permuted. If `balanc = B`, `A` is permuted and scaled. If `sense = N`, no reciprocal condition numbers are computed. If `sense = E`, reciprocal condition numbers are computed for the eigenvalues only. If `sense = V`, reciprocal condition numbers are computed for the right eigenvectors only. If `sense = B`, reciprocal condition numbers are computed for the right eigenvectors and the eigenvectors. If `sense = E,B`, the right and left eigenvectors must be computed.
###
`LinearAlgebra.LAPACK.ggev!`Function
```
ggev!(jobvl, jobvr, A, B) -> (alpha, beta, vl, vr)
```
Finds the generalized eigendecomposition of `A` and `B`. If `jobvl = N`, the left eigenvectors aren't computed. If `jobvr = N`, the right eigenvectors aren't computed. If `jobvl = V` or `jobvr = V`, the corresponding eigenvectors are computed.
###
`LinearAlgebra.LAPACK.gtsv!`Function
```
gtsv!(dl, d, du, B)
```
Solves the equation `A * X = B` where `A` is a tridiagonal matrix with `dl` on the subdiagonal, `d` on the diagonal, and `du` on the superdiagonal.
Overwrites `B` with the solution `X` and returns it.
###
`LinearAlgebra.LAPACK.gttrf!`Function
```
gttrf!(dl, d, du) -> (dl, d, du, du2, ipiv)
```
Finds the `LU` factorization of a tridiagonal matrix with `dl` on the subdiagonal, `d` on the diagonal, and `du` on the superdiagonal.
Modifies `dl`, `d`, and `du` in-place and returns them and the second superdiagonal `du2` and the pivoting vector `ipiv`.
###
`LinearAlgebra.LAPACK.gttrs!`Function
```
gttrs!(trans, dl, d, du, du2, ipiv, B)
```
Solves the equation `A * X = B` (`trans = N`), `transpose(A) * X = B` (`trans = T`), or `adjoint(A) * X = B` (`trans = C`) using the `LU` factorization computed by `gttrf!`. `B` is overwritten with the solution `X`.
###
`LinearAlgebra.LAPACK.orglq!`Function
```
orglq!(A, tau, k = length(tau))
```
Explicitly finds the matrix `Q` of a `LQ` factorization after calling `gelqf!` on `A`. Uses the output of `gelqf!`. `A` is overwritten by `Q`.
###
`LinearAlgebra.LAPACK.orgqr!`Function
```
orgqr!(A, tau, k = length(tau))
```
Explicitly finds the matrix `Q` of a `QR` factorization after calling `geqrf!` on `A`. Uses the output of `geqrf!`. `A` is overwritten by `Q`.
###
`LinearAlgebra.LAPACK.orgql!`Function
```
orgql!(A, tau, k = length(tau))
```
Explicitly finds the matrix `Q` of a `QL` factorization after calling `geqlf!` on `A`. Uses the output of `geqlf!`. `A` is overwritten by `Q`.
###
`LinearAlgebra.LAPACK.orgrq!`Function
```
orgrq!(A, tau, k = length(tau))
```
Explicitly finds the matrix `Q` of a `RQ` factorization after calling `gerqf!` on `A`. Uses the output of `gerqf!`. `A` is overwritten by `Q`.
###
`LinearAlgebra.LAPACK.ormlq!`Function
```
ormlq!(side, trans, A, tau, C)
```
Computes `Q * C` (`trans = N`), `transpose(Q) * C` (`trans = T`), `adjoint(Q) * C` (`trans = C`) for `side = L` or the equivalent right-sided multiplication for `side = R` using `Q` from a `LQ` factorization of `A` computed using `gelqf!`. `C` is overwritten.
###
`LinearAlgebra.LAPACK.ormqr!`Function
```
ormqr!(side, trans, A, tau, C)
```
Computes `Q * C` (`trans = N`), `transpose(Q) * C` (`trans = T`), `adjoint(Q) * C` (`trans = C`) for `side = L` or the equivalent right-sided multiplication for `side = R` using `Q` from a `QR` factorization of `A` computed using `geqrf!`. `C` is overwritten.
###
`LinearAlgebra.LAPACK.ormql!`Function
```
ormql!(side, trans, A, tau, C)
```
Computes `Q * C` (`trans = N`), `transpose(Q) * C` (`trans = T`), `adjoint(Q) * C` (`trans = C`) for `side = L` or the equivalent right-sided multiplication for `side = R` using `Q` from a `QL` factorization of `A` computed using `geqlf!`. `C` is overwritten.
###
`LinearAlgebra.LAPACK.ormrq!`Function
```
ormrq!(side, trans, A, tau, C)
```
Computes `Q * C` (`trans = N`), `transpose(Q) * C` (`trans = T`), `adjoint(Q) * C` (`trans = C`) for `side = L` or the equivalent right-sided multiplication for `side = R` using `Q` from a `RQ` factorization of `A` computed using `gerqf!`. `C` is overwritten.
###
`LinearAlgebra.LAPACK.gemqrt!`Function
```
gemqrt!(side, trans, V, T, C)
```
Computes `Q * C` (`trans = N`), `transpose(Q) * C` (`trans = T`), `adjoint(Q) * C` (`trans = C`) for `side = L` or the equivalent right-sided multiplication for `side = R` using `Q` from a `QR` factorization of `A` computed using `geqrt!`. `C` is overwritten.
###
`LinearAlgebra.LAPACK.posv!`Function
```
posv!(uplo, A, B) -> (A, B)
```
Finds the solution to `A * X = B` where `A` is a symmetric or Hermitian positive definite matrix. If `uplo = U` the upper Cholesky decomposition of `A` is computed. If `uplo = L` the lower Cholesky decomposition of `A` is computed. `A` is overwritten by its Cholesky decomposition. `B` is overwritten with the solution `X`.
###
`LinearAlgebra.LAPACK.potrf!`Function
```
potrf!(uplo, A)
```
Computes the Cholesky (upper if `uplo = U`, lower if `uplo = L`) decomposition of positive-definite matrix `A`. `A` is overwritten and returned with an info code.
###
`LinearAlgebra.LAPACK.potri!`Function
```
potri!(uplo, A)
```
Computes the inverse of positive-definite matrix `A` after calling `potrf!` to find its (upper if `uplo = U`, lower if `uplo = L`) Cholesky decomposition.
`A` is overwritten by its inverse and returned.
###
`LinearAlgebra.LAPACK.potrs!`Function
```
potrs!(uplo, A, B)
```
Finds the solution to `A * X = B` where `A` is a symmetric or Hermitian positive definite matrix whose Cholesky decomposition was computed by `potrf!`. If `uplo = U` the upper Cholesky decomposition of `A` was computed. If `uplo = L` the lower Cholesky decomposition of `A` was computed. `B` is overwritten with the solution `X`.
###
`LinearAlgebra.LAPACK.pstrf!`Function
```
pstrf!(uplo, A, tol) -> (A, piv, rank, info)
```
Computes the (upper if `uplo = U`, lower if `uplo = L`) pivoted Cholesky decomposition of positive-definite matrix `A` with a user-set tolerance `tol`. `A` is overwritten by its Cholesky decomposition.
Returns `A`, the pivots `piv`, the rank of `A`, and an `info` code. If `info = 0`, the factorization succeeded. If `info = i > 0`, then `A` is indefinite or rank-deficient.
###
`LinearAlgebra.LAPACK.ptsv!`Function
```
ptsv!(D, E, B)
```
Solves `A * X = B` for positive-definite tridiagonal `A`. `D` is the diagonal of `A` and `E` is the off-diagonal. `B` is overwritten with the solution `X` and returned.
###
`LinearAlgebra.LAPACK.pttrf!`Function
```
pttrf!(D, E)
```
Computes the LDLt factorization of a positive-definite tridiagonal matrix with `D` as diagonal and `E` as off-diagonal. `D` and `E` are overwritten and returned.
###
`LinearAlgebra.LAPACK.pttrs!`Function
```
pttrs!(D, E, B)
```
Solves `A * X = B` for positive-definite tridiagonal `A` with diagonal `D` and off-diagonal `E` after computing `A`'s LDLt factorization using `pttrf!`. `B` is overwritten with the solution `X`.
###
`LinearAlgebra.LAPACK.trtri!`Function
```
trtri!(uplo, diag, A)
```
Finds the inverse of (upper if `uplo = U`, lower if `uplo = L`) triangular matrix `A`. If `diag = N`, `A` has non-unit diagonal elements. If `diag = U`, all diagonal elements of `A` are one. `A` is overwritten with its inverse.
###
`LinearAlgebra.LAPACK.trtrs!`Function
```
trtrs!(uplo, trans, diag, A, B)
```
Solves `A * X = B` (`trans = N`), `transpose(A) * X = B` (`trans = T`), or `adjoint(A) * X = B` (`trans = C`) for (upper if `uplo = U`, lower if `uplo = L`) triangular matrix `A`. If `diag = N`, `A` has non-unit diagonal elements. If `diag = U`, all diagonal elements of `A` are one. `B` is overwritten with the solution `X`.
###
`LinearAlgebra.LAPACK.trcon!`Function
```
trcon!(norm, uplo, diag, A)
```
Finds the reciprocal condition number of (upper if `uplo = U`, lower if `uplo = L`) triangular matrix `A`. If `diag = N`, `A` has non-unit diagonal elements. If `diag = U`, all diagonal elements of `A` are one. If `norm = I`, the condition number is found in the infinity norm. If `norm = O` or `1`, the condition number is found in the one norm.
###
`LinearAlgebra.LAPACK.trevc!`Function
```
trevc!(side, howmny, select, T, VL = similar(T), VR = similar(T))
```
Finds the eigensystem of an upper triangular matrix `T`. If `side = R`, the right eigenvectors are computed. If `side = L`, the left eigenvectors are computed. If `side = B`, both sets are computed. If `howmny = A`, all eigenvectors are found. If `howmny = B`, all eigenvectors are found and backtransformed using `VL` and `VR`. If `howmny = S`, only the eigenvectors corresponding to the values in `select` are computed.
###
`LinearAlgebra.LAPACK.trrfs!`Function
```
trrfs!(uplo, trans, diag, A, B, X, Ferr, Berr) -> (Ferr, Berr)
```
Estimates the error in the solution to `A * X = B` (`trans = N`), `transpose(A) * X = B` (`trans = T`), `adjoint(A) * X = B` (`trans = C`) for `side = L`, or the equivalent equations a right-handed `side = R` `X * A` after computing `X` using `trtrs!`. If `uplo = U`, `A` is upper triangular. If `uplo = L`, `A` is lower triangular. If `diag = N`, `A` has non-unit diagonal elements. If `diag = U`, all diagonal elements of `A` are one. `Ferr` and `Berr` are optional inputs. `Ferr` is the forward error and `Berr` is the backward error, each component-wise.
###
`LinearAlgebra.LAPACK.stev!`Function
```
stev!(job, dv, ev) -> (dv, Zmat)
```
Computes the eigensystem for a symmetric tridiagonal matrix with `dv` as diagonal and `ev` as off-diagonal. If `job = N` only the eigenvalues are found and returned in `dv`. If `job = V` then the eigenvectors are also found and returned in `Zmat`.
###
`LinearAlgebra.LAPACK.stebz!`Function
```
stebz!(range, order, vl, vu, il, iu, abstol, dv, ev) -> (dv, iblock, isplit)
```
Computes the eigenvalues for a symmetric tridiagonal matrix with `dv` as diagonal and `ev` as off-diagonal. If `range = A`, all the eigenvalues are found. If `range = V`, the eigenvalues in the half-open interval `(vl, vu]` are found. If `range = I`, the eigenvalues with indices between `il` and `iu` are found. If `order = B`, eigvalues are ordered within a block. If `order = E`, they are ordered across all the blocks. `abstol` can be set as a tolerance for convergence.
###
`LinearAlgebra.LAPACK.stegr!`Function
```
stegr!(jobz, range, dv, ev, vl, vu, il, iu) -> (w, Z)
```
Computes the eigenvalues (`jobz = N`) or eigenvalues and eigenvectors (`jobz = V`) for a symmetric tridiagonal matrix with `dv` as diagonal and `ev` as off-diagonal. If `range = A`, all the eigenvalues are found. If `range = V`, the eigenvalues in the half-open interval `(vl, vu]` are found. If `range = I`, the eigenvalues with indices between `il` and `iu` are found. The eigenvalues are returned in `w` and the eigenvectors in `Z`.
###
`LinearAlgebra.LAPACK.stein!`Function
```
stein!(dv, ev_in, w_in, iblock_in, isplit_in)
```
Computes the eigenvectors for a symmetric tridiagonal matrix with `dv` as diagonal and `ev_in` as off-diagonal. `w_in` specifies the input eigenvalues for which to find corresponding eigenvectors. `iblock_in` specifies the submatrices corresponding to the eigenvalues in `w_in`. `isplit_in` specifies the splitting points between the submatrix blocks.
###
`LinearAlgebra.LAPACK.syconv!`Function
```
syconv!(uplo, A, ipiv) -> (A, work)
```
Converts a symmetric matrix `A` (which has been factorized into a triangular matrix) into two matrices `L` and `D`. If `uplo = U`, `A` is upper triangular. If `uplo = L`, it is lower triangular. `ipiv` is the pivot vector from the triangular factorization. `A` is overwritten by `L` and `D`.
###
`LinearAlgebra.LAPACK.sysv!`Function
```
sysv!(uplo, A, B) -> (B, A, ipiv)
```
Finds the solution to `A * X = B` for symmetric matrix `A`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored. `B` is overwritten by the solution `X`. `A` is overwritten by its Bunch-Kaufman factorization. `ipiv` contains pivoting information about the factorization.
###
`LinearAlgebra.LAPACK.sytrf!`Function
```
sytrf!(uplo, A) -> (A, ipiv, info)
```
Computes the Bunch-Kaufman factorization of a symmetric matrix `A`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored.
Returns `A`, overwritten by the factorization, a pivot vector `ipiv`, and the error code `info` which is a non-negative integer. If `info` is positive the matrix is singular and the diagonal part of the factorization is exactly zero at position `info`.
###
`LinearAlgebra.LAPACK.sytri!`Function
```
sytri!(uplo, A, ipiv)
```
Computes the inverse of a symmetric matrix `A` using the results of `sytrf!`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored. `A` is overwritten by its inverse.
###
`LinearAlgebra.LAPACK.sytrs!`Function
```
sytrs!(uplo, A, ipiv, B)
```
Solves the equation `A * X = B` for a symmetric matrix `A` using the results of `sytrf!`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored. `B` is overwritten by the solution `X`.
###
`LinearAlgebra.LAPACK.hesv!`Function
```
hesv!(uplo, A, B) -> (B, A, ipiv)
```
Finds the solution to `A * X = B` for Hermitian matrix `A`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored. `B` is overwritten by the solution `X`. `A` is overwritten by its Bunch-Kaufman factorization. `ipiv` contains pivoting information about the factorization.
###
`LinearAlgebra.LAPACK.hetrf!`Function
```
hetrf!(uplo, A) -> (A, ipiv, info)
```
Computes the Bunch-Kaufman factorization of a Hermitian matrix `A`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored.
Returns `A`, overwritten by the factorization, a pivot vector `ipiv`, and the error code `info` which is a non-negative integer. If `info` is positive the matrix is singular and the diagonal part of the factorization is exactly zero at position `info`.
###
`LinearAlgebra.LAPACK.hetri!`Function
```
hetri!(uplo, A, ipiv)
```
Computes the inverse of a Hermitian matrix `A` using the results of `sytrf!`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored. `A` is overwritten by its inverse.
###
`LinearAlgebra.LAPACK.hetrs!`Function
```
hetrs!(uplo, A, ipiv, B)
```
Solves the equation `A * X = B` for a Hermitian matrix `A` using the results of `sytrf!`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower half is stored. `B` is overwritten by the solution `X`.
###
`LinearAlgebra.LAPACK.syev!`Function
```
syev!(jobz, uplo, A)
```
Finds the eigenvalues (`jobz = N`) or eigenvalues and eigenvectors (`jobz = V`) of a symmetric matrix `A`. If `uplo = U`, the upper triangle of `A` is used. If `uplo = L`, the lower triangle of `A` is used.
###
`LinearAlgebra.LAPACK.syevr!`Function
```
syevr!(jobz, range, uplo, A, vl, vu, il, iu, abstol) -> (W, Z)
```
Finds the eigenvalues (`jobz = N`) or eigenvalues and eigenvectors (`jobz = V`) of a symmetric matrix `A`. If `uplo = U`, the upper triangle of `A` is used. If `uplo = L`, the lower triangle of `A` is used. If `range = A`, all the eigenvalues are found. If `range = V`, the eigenvalues in the half-open interval `(vl, vu]` are found. If `range = I`, the eigenvalues with indices between `il` and `iu` are found. `abstol` can be set as a tolerance for convergence.
The eigenvalues are returned in `W` and the eigenvectors in `Z`.
###
`LinearAlgebra.LAPACK.sygvd!`Function
```
sygvd!(itype, jobz, uplo, A, B) -> (w, A, B)
```
Finds the generalized eigenvalues (`jobz = N`) or eigenvalues and eigenvectors (`jobz = V`) of a symmetric matrix `A` and symmetric positive-definite matrix `B`. If `uplo = U`, the upper triangles of `A` and `B` are used. If `uplo = L`, the lower triangles of `A` and `B` are used. If `itype = 1`, the problem to solve is `A * x = lambda * B * x`. If `itype = 2`, the problem to solve is `A * B * x = lambda * x`. If `itype = 3`, the problem to solve is `B * A * x = lambda * x`.
###
`LinearAlgebra.LAPACK.bdsqr!`Function
```
bdsqr!(uplo, d, e_, Vt, U, C) -> (d, Vt, U, C)
```
Computes the singular value decomposition of a bidiagonal matrix with `d` on the diagonal and `e_` on the off-diagonal. If `uplo = U`, `e_` is the superdiagonal. If `uplo = L`, `e_` is the subdiagonal. Can optionally also compute the product `Q' * C`.
Returns the singular values in `d`, and the matrix `C` overwritten with `Q' * C`.
###
`LinearAlgebra.LAPACK.bdsdc!`Function
```
bdsdc!(uplo, compq, d, e_) -> (d, e, u, vt, q, iq)
```
Computes the singular value decomposition of a bidiagonal matrix with `d` on the diagonal and `e_` on the off-diagonal using a divide and conqueq method. If `uplo = U`, `e_` is the superdiagonal. If `uplo = L`, `e_` is the subdiagonal. If `compq = N`, only the singular values are found. If `compq = I`, the singular values and vectors are found. If `compq = P`, the singular values and vectors are found in compact form. Only works for real types.
Returns the singular values in `d`, and if `compq = P`, the compact singular vectors in `iq`.
###
`LinearAlgebra.LAPACK.gecon!`Function
```
gecon!(normtype, A, anorm)
```
Finds the reciprocal condition number of matrix `A`. If `normtype = I`, the condition number is found in the infinity norm. If `normtype = O` or `1`, the condition number is found in the one norm. `A` must be the result of `getrf!` and `anorm` is the norm of `A` in the relevant norm.
###
`LinearAlgebra.LAPACK.gehrd!`Function
```
gehrd!(ilo, ihi, A) -> (A, tau)
```
Converts a matrix `A` to Hessenberg form. If `A` is balanced with `gebal!` then `ilo` and `ihi` are the outputs of `gebal!`. Otherwise they should be `ilo = 1` and `ihi = size(A,2)`. `tau` contains the elementary reflectors of the factorization.
###
`LinearAlgebra.LAPACK.orghr!`Function
```
orghr!(ilo, ihi, A, tau)
```
Explicitly finds `Q`, the orthogonal/unitary matrix from `gehrd!`. `ilo`, `ihi`, `A`, and `tau` must correspond to the input/output to `gehrd!`.
###
`LinearAlgebra.LAPACK.gees!`Function
```
gees!(jobvs, A) -> (A, vs, w)
```
Computes the eigenvalues (`jobvs = N`) or the eigenvalues and Schur vectors (`jobvs = V`) of matrix `A`. `A` is overwritten by its Schur form.
Returns `A`, `vs` containing the Schur vectors, and `w`, containing the eigenvalues.
###
`LinearAlgebra.LAPACK.gges!`Function
```
gges!(jobvsl, jobvsr, A, B) -> (A, B, alpha, beta, vsl, vsr)
```
Computes the generalized eigenvalues, generalized Schur form, left Schur vectors (`jobsvl = V`), or right Schur vectors (`jobvsr = V`) of `A` and `B`.
The generalized eigenvalues are returned in `alpha` and `beta`. The left Schur vectors are returned in `vsl` and the right Schur vectors are returned in `vsr`.
###
`LinearAlgebra.LAPACK.trexc!`Function
```
trexc!(compq, ifst, ilst, T, Q) -> (T, Q)
trexc!(ifst, ilst, T, Q) -> (T, Q)
```
Reorder the Schur factorization `T` of a matrix, such that the diagonal block of `T` with row index `ifst` is moved to row index `ilst`. If `compq = V`, the Schur vectors `Q` are reordered. If `compq = N` they are not modified. The 4-arg method calls the 5-arg method with `compq = V`.
###
`LinearAlgebra.LAPACK.trsen!`Function
```
trsen!(job, compq, select, T, Q) -> (T, Q, w, s, sep)
trsen!(select, T, Q) -> (T, Q, w, s, sep)
```
Reorder the Schur factorization of a matrix and optionally finds reciprocal condition numbers. If `job = N`, no condition numbers are found. If `job = E`, only the condition number for this cluster of eigenvalues is found. If `job = V`, only the condition number for the invariant subspace is found. If `job = B` then the condition numbers for the cluster and subspace are found. If `compq = V` the Schur vectors `Q` are updated. If `compq = N` the Schur vectors are not modified. `select` determines which eigenvalues are in the cluster. The 3-arg method calls the 5-arg method with `job = N` and `compq = V`.
Returns `T`, `Q`, reordered eigenvalues in `w`, the condition number of the cluster of eigenvalues `s`, and the condition number of the invariant subspace `sep`.
###
`LinearAlgebra.LAPACK.tgsen!`Function
```
tgsen!(select, S, T, Q, Z) -> (S, T, alpha, beta, Q, Z)
```
Reorders the vectors of a generalized Schur decomposition. `select` specifies the eigenvalues in each cluster.
###
`LinearAlgebra.LAPACK.trsyl!`Function
```
trsyl!(transa, transb, A, B, C, isgn=1) -> (C, scale)
```
Solves the Sylvester matrix equation `A * X +/- X * B = scale*C` where `A` and `B` are both quasi-upper triangular. If `transa = N`, `A` is not modified. If `transa = T`, `A` is transposed. If `transa = C`, `A` is conjugate transposed. Similarly for `transb` and `B`. If `isgn = 1`, the equation `A * X + X * B = scale * C` is solved. If `isgn = -1`, the equation `A * X - X * B = scale * C` is solved.
Returns `X` (overwriting `C`) and `scale`.
* [Bischof1987](#citeref-Bischof1987)C Bischof and C Van Loan, "The WY representation for products of Householder matrices", SIAM J Sci Stat Comput 8 (1987), s2-s13. [doi:10.1137/0908009](https://doi.org/10.1137/0908009)
* [Schreiber1989](#citeref-Schreiber1989)R Schreiber and C Van Loan, "A storage-efficient WY representation for products of Householder transformations", SIAM J Sci Stat Comput 10 (1989), 53-57. [doi:10.1137/0910005](https://doi.org/10.1137/0910005)
* [Bunch1977](#citeref-Bunch1977)J R Bunch and L Kaufman, Some stable methods for calculating inertia and solving symmetric linear systems, Mathematics of Computation 31:137 (1977), 163-179. [url](http://www.ams.org/journals/mcom/1977-31-137/S0025-5718-1977-0428694-0/).
* [issue8859](#citeref-issue8859)Issue 8859, "Fix least squares", <https://github.com/JuliaLang/julia/pull/8859>
* [B96](#citeref-B96)Åke Björck, "Numerical Methods for Least Squares Problems", SIAM Press, Philadelphia, 1996, "Other Titles in Applied Mathematics", Vol. 51. [doi:10.1137/1.9781611971484](http://epubs.siam.org/doi/book/10.1137/1.9781611971484)
* [S84](#citeref-S84)G. W. Stewart, "Rank Degeneracy", SIAM Journal on Scientific and Statistical Computing, 5(2), 1984, 403-413. [doi:10.1137/0905030](http://epubs.siam.org/doi/abs/10.1137/0905030)
* [KY88](#citeref-KY88)Konstantinos Konstantinides and Kung Yao, "Statistical analysis of effective singular values in matrix rank determination", IEEE Transactions on Acoustics, Speech and Signal Processing, 36(5), 1988, 757-763. [doi:10.1109/29.1585](https://doi.org/10.1109/29.1585)
* [H05](#citeref-H05)Nicholas J. Higham, "The squaring and scaling method for the matrix exponential revisited", SIAM Journal on Matrix Analysis and Applications, 26(4), 2005, 1179-1193. [doi:10.1137/090768539](https://doi.org/10.1137/090768539)
* [AH12](#citeref-AH12)Awad H. Al-Mohy and Nicholas J. Higham, "Improved inverse scaling and squaring algorithms for the matrix logarithm", SIAM Journal on Scientific Computing, 34(4), 2012, C153-C169. [doi:10.1137/110852553](https://doi.org/10.1137/110852553)
* [AHR13](#citeref-AHR13)Awad H. Al-Mohy, Nicholas J. Higham and Samuel D. Relton, "Computing the Fréchet derivative of the matrix logarithm and estimating the condition number", SIAM Journal on Scientific Computing, 35(4), 2013, C394-C410. [doi:10.1137/120885991](https://doi.org/10.1137/120885991)
* [BH83](#citeref-BH83)Åke Björck and Sven Hammarling, "A Schur method for the square root of a matrix", Linear Algebra and its Applications, 52-53, 1983, 127-140. [doi:10.1016/0024-3795(83)80010-X](https://doi.org/10.1016/0024-3795(83)80010-X)
* [H87](#citeref-H87)Nicholas J. Higham, "Computing real square roots of a real matrix", Linear Algebra and its Applications, 88-89, 1987, 405-430. [doi:10.1016/0024-3795(87)90118-2](https://doi.org/10.1016/0024-3795(87)90118-2)
* [AH16\_1](#citeref-AH16_1)Mary Aprahamian and Nicholas J. Higham, "Matrix Inverse Trigonometric and Inverse Hyperbolic Functions: Theory and Algorithms", MIMS EPrint: 2016.4. <https://doi.org/10.1137/16M1057577>
* [AH16\_2](#citeref-AH16_2)Mary Aprahamian and Nicholas J. Higham, "Matrix Inverse Trigonometric and Inverse Hyperbolic Functions: Theory and Algorithms", MIMS EPrint: 2016.4. <https://doi.org/10.1137/16M1057577>
* [AH16\_3](#citeref-AH16_3)Mary Aprahamian and Nicholas J. Higham, "Matrix Inverse Trigonometric and Inverse Hyperbolic Functions: Theory and Algorithms", MIMS EPrint: 2016.4. <https://doi.org/10.1137/16M1057577>
* [AH16\_4](#citeref-AH16_4)Mary Aprahamian and Nicholas J. Higham, "Matrix Inverse Trigonometric and Inverse Hyperbolic Functions: Theory and Algorithms", MIMS EPrint: 2016.4. <https://doi.org/10.1137/16M1057577>
* [AH16\_5](#citeref-AH16_5)Mary Aprahamian and Nicholas J. Higham, "Matrix Inverse Trigonometric and Inverse Hyperbolic Functions: Theory and Algorithms", MIMS EPrint: 2016.4. <https://doi.org/10.1137/16M1057577>
* [AH16\_6](#citeref-AH16_6)Mary Aprahamian and Nicholas J. Higham, "Matrix Inverse Trigonometric and Inverse Hyperbolic Functions: Theory and Algorithms", MIMS EPrint: 2016.4. <https://doi.org/10.1137/16M1057577>
| programming_docs |
julia LibGit2 LibGit2
=======
The LibGit2 module provides bindings to [libgit2](https://libgit2.org/), a portable C library that implements core functionality for the [Git](https://git-scm.com/) version control system. These bindings are currently used to power Julia's package manager. It is expected that this module will eventually be moved into a separate package.
###
[Functionality](#Functionality)
Some of this documentation assumes some prior knowledge of the libgit2 API. For more information on some of the objects and methods referenced here, consult the upstream [libgit2 API reference](https://libgit2.org/libgit2/#v0.25.1).
###
`LibGit2.Buffer`Type
```
LibGit2.Buffer
```
A data buffer for exporting data from libgit2. Matches the [`git_buf`](https://libgit2.org/libgit2/#HEAD/type/git_buf) struct.
When fetching data from LibGit2, a typical usage would look like:
```
buf_ref = Ref(Buffer())
@check ccall(..., (Ptr{Buffer},), buf_ref)
# operation on buf_ref
free(buf_ref)
```
In particular, note that `LibGit2.free` should be called afterward on the `Ref` object.
###
`LibGit2.CheckoutOptions`Type
```
LibGit2.CheckoutOptions
```
Matches the [`git_checkout_options`](https://libgit2.org/libgit2/#HEAD/type/git_checkout_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `checkout_strategy`: determine how to handle conflicts and whether to force the checkout/recreate missing files.
* `disable_filters`: if nonzero, do not apply filters like CLRF (to convert file newlines between UNIX and DOS).
* `dir_mode`: read/write/access mode for any directories involved in the checkout. Default is `0755`.
* `file_mode`: read/write/access mode for any files involved in the checkout. Default is `0755` or `0644`, depending on the blob.
* `file_open_flags`: bitflags used to open any files during the checkout.
* `notify_flags`: Flags for what sort of conflicts the user should be notified about.
* `notify_cb`: An optional callback function to notify the user if a checkout conflict occurs. If this function returns a non-zero value, the checkout will be cancelled.
* `notify_payload`: Payload for the notify callback function.
* `progress_cb`: An optional callback function to display checkout progress.
* `progress_payload`: Payload for the progress callback.
* `paths`: If not empty, describes which paths to search during the checkout. If empty, the checkout will occur over all files in the repository.
* `baseline`: Expected content of the [`workdir`](#LibGit2.workdir), captured in a (pointer to a) [`GitTree`](#LibGit2.GitTree). Defaults to the state of the tree at HEAD.
* `baseline_index`: Expected content of the [`workdir`](#LibGit2.workdir), captured in a (pointer to a) `GitIndex`. Defaults to the state of the index at HEAD.
* `target_directory`: If not empty, checkout to this directory instead of the `workdir`.
* `ancestor_label`: In case of conflicts, the name of the common ancestor side.
* `our_label`: In case of conflicts, the name of "our" side.
* `their_label`: In case of conflicts, the name of "their" side.
* `perfdata_cb`: An optional callback function to display performance data.
* `perfdata_payload`: Payload for the performance callback.
###
`LibGit2.CloneOptions`Type
```
LibGit2.CloneOptions
```
Matches the [`git_clone_options`](https://libgit2.org/libgit2/#HEAD/type/git_clone_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `checkout_opts`: The options for performing the checkout of the remote as part of the clone.
* `fetch_opts`: The options for performing the pre-checkout fetch of the remote as part of the clone.
* `bare`: If `0`, clone the full remote repository. If non-zero, perform a bare clone, in which there is no local copy of the source files in the repository and the [`gitdir`](#LibGit2.gitdir) and [`workdir`](#LibGit2.workdir) are the same.
* `localclone`: Flag whether to clone a local object database or do a fetch. The default is to let git decide. It will not use the git-aware transport for a local clone, but will use it for URLs which begin with `file://`.
* `checkout_branch`: The name of the branch to checkout. If an empty string, the default branch of the remote will be checked out.
* `repository_cb`: An optional callback which will be used to create the *new* repository into which the clone is made.
* `repository_cb_payload`: The payload for the repository callback.
* `remote_cb`: An optional callback used to create the [`GitRemote`](#LibGit2.GitRemote) before making the clone from it.
* `remote_cb_payload`: The payload for the remote callback.
###
`LibGit2.DescribeOptions`Type
```
LibGit2.DescribeOptions
```
Matches the [`git_describe_options`](https://libgit2.org/libgit2/#HEAD/type/git_describe_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `max_candidates_tags`: consider this many most recent tags in `refs/tags` to describe a commit. Defaults to 10 (so that the 10 most recent tags would be examined to see if they describe a commit).
* `describe_strategy`: whether to consider all entries in `refs/tags` (equivalent to `git-describe --tags`) or all entries in `refs/` (equivalent to `git-describe --all`). The default is to only show annotated tags. If `Consts.DESCRIBE_TAGS` is passed, all tags, annotated or not, will be considered. If `Consts.DESCRIBE_ALL` is passed, any ref in `refs/` will be considered.
* `pattern`: only consider tags which match `pattern`. Supports glob expansion.
* `only_follow_first_parent`: when finding the distance from a matching reference to the described object, only consider the distance from the first parent.
* `show_commit_oid_as_fallback`: if no matching reference can be found which describes a commit, show the commit's [`GitHash`](#LibGit2.GitHash) instead of throwing an error (the default behavior).
###
`LibGit2.DescribeFormatOptions`Type
```
LibGit2.DescribeFormatOptions
```
Matches the [`git_describe_format_options`](https://libgit2.org/libgit2/#HEAD/type/git_describe_format_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `abbreviated_size`: lower bound on the size of the abbreviated `GitHash` to use, defaulting to `7`.
* `always_use_long_format`: set to `1` to use the long format for strings even if a short format can be used.
* `dirty_suffix`: if set, this will be appended to the end of the description string if the [`workdir`](#LibGit2.workdir) is dirty.
###
`LibGit2.DiffDelta`Type
```
LibGit2.DiffDelta
```
Description of changes to one entry. Matches the [`git_diff_delta`](https://libgit2.org/libgit2/#HEAD/type/git_diff_delta) struct.
The fields represent:
* `status`: One of `Consts.DELTA_STATUS`, indicating whether the file has been added/modified/deleted.
* `flags`: Flags for the delta and the objects on each side. Determines whether to treat the file(s) as binary/text, whether they exist on each side of the diff, and whether the object ids are known to be correct.
* `similarity`: Used to indicate if a file has been renamed or copied.
* `nfiles`: The number of files in the delta (for instance, if the delta was run on a submodule commit id, it may contain more than one file).
* `old_file`: A [`DiffFile`](#LibGit2.DiffFile) containing information about the file(s) before the changes.
* `new_file`: A [`DiffFile`](#LibGit2.DiffFile) containing information about the file(s) after the changes.
###
`LibGit2.DiffFile`Type
```
LibGit2.DiffFile
```
Description of one side of a delta. Matches the [`git_diff_file`](https://libgit2.org/libgit2/#HEAD/type/git_diff_file) struct.
The fields represent:
* `id`: the [`GitHash`](#LibGit2.GitHash) of the item in the diff. If the item is empty on this side of the diff (for instance, if the diff is of the removal of a file), this will be `GitHash(0)`.
* `path`: a `NULL` terminated path to the item relative to the working directory of the repository.
* `size`: the size of the item in bytes.
* `flags`: a combination of the [`git_diff_flag_t`](https://libgit2.org/libgit2/#HEAD/type/git_diff_flag_t) flags. The `i`th bit of this integer sets the `i`th flag.
* `mode`: the [`stat`](../../base/file/index#Base.stat) mode for the item.
* `id_abbrev`: only present in LibGit2 versions newer than or equal to `0.25.0`. The length of the `id` field when converted using [`string`](../../base/strings/index#Base.string). Usually equal to `OID_HEXSZ` (40).
###
`LibGit2.DiffOptionsStruct`Type
```
LibGit2.DiffOptionsStruct
```
Matches the [`git_diff_options`](https://libgit2.org/libgit2/#HEAD/type/git_diff_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `flags`: flags controlling which files will appear in the diff. Defaults to `DIFF_NORMAL`.
* `ignore_submodules`: whether to look at files in submodules or not. Defaults to `SUBMODULE_IGNORE_UNSPECIFIED`, which means the submodule's configuration will control whether it appears in the diff or not.
* `pathspec`: path to files to include in the diff. Default is to use all files in the repository.
* `notify_cb`: optional callback which will notify the user of changes to the diff as file deltas are added to it.
* `progress_cb`: optional callback which will display diff progress. Only relevant on libgit2 versions at least as new as 0.24.0.
* `payload`: the payload to pass to `notify_cb` and `progress_cb`.
* `context_lines`: the number of *unchanged* lines used to define the edges of a hunk. This is also the number of lines which will be shown before/after a hunk to provide context. Default is 3.
* `interhunk_lines`: the maximum number of *unchanged* lines *between* two separate hunks allowed before the hunks will be combined. Default is 0.
* `id_abbrev`: sets the length of the abbreviated [`GitHash`](#LibGit2.GitHash) to print. Default is `7`.
* `max_size`: the maximum file size of a blob. Above this size, it will be treated as a binary blob. The default is 512 MB.
* `old_prefix`: the virtual file directory in which to place old files on one side of the diff. Default is `"a"`.
* `new_prefix`: the virtual file directory in which to place new files on one side of the diff. Default is `"b"`.
###
`LibGit2.FetchHead`Type
```
LibGit2.FetchHead
```
Contains the information about HEAD during a fetch, including the name and URL of the branch fetched from, the oid of the HEAD, and whether the fetched HEAD has been merged locally.
The fields represent:
* `name`: The name in the local reference database of the fetch head, for example, `"refs/heads/master"`.
* `url`: The URL of the fetch head.
* `oid`: The [`GitHash`](#LibGit2.GitHash) of the tip of the fetch head.
* `ismerge`: Boolean flag indicating whether the changes at the remote have been merged into the local copy yet or not. If `true`, the local copy is up to date with the remote fetch head.
###
`LibGit2.FetchOptions`Type
```
LibGit2.FetchOptions
```
Matches the [`git_fetch_options`](https://libgit2.org/libgit2/#HEAD/type/git_fetch_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `callbacks`: remote callbacks to use during the fetch.
* `prune`: whether to perform a prune after the fetch or not. The default is to use the setting from the `GitConfig`.
* `update_fetchhead`: whether to update the [`FetchHead`](#LibGit2.FetchHead) after the fetch. The default is to perform the update, which is the normal git behavior.
* `download_tags`: whether to download tags present at the remote or not. The default is to request the tags for objects which are being downloaded anyway from the server.
* `proxy_opts`: options for connecting to the remote through a proxy. See [`ProxyOptions`](#LibGit2.ProxyOptions). Only present on libgit2 versions newer than or equal to 0.25.0.
* `custom_headers`: any extra headers needed for the fetch. Only present on libgit2 versions newer than or equal to 0.24.0.
###
`LibGit2.GitAnnotated`Type
```
GitAnnotated(repo::GitRepo, commit_id::GitHash)
GitAnnotated(repo::GitRepo, ref::GitReference)
GitAnnotated(repo::GitRepo, fh::FetchHead)
GitAnnotated(repo::GitRepo, committish::AbstractString)
```
An annotated git commit carries with it information about how it was looked up and why, so that rebase or merge operations have more information about the context of the commit. Conflict files contain information about the source/target branches in the merge which are conflicting, for instance. An annotated commit can refer to the tip of a remote branch, for instance when a [`FetchHead`](#LibGit2.FetchHead) is passed, or to a branch head described using `GitReference`.
###
`LibGit2.GitBlame`Type
```
GitBlame(repo::GitRepo, path::AbstractString; options::BlameOptions=BlameOptions())
```
Construct a `GitBlame` object for the file at `path`, using change information gleaned from the history of `repo`. The `GitBlame` object records who changed which chunks of the file when, and how. `options` controls how to separate the contents of the file and which commits to probe - see [`BlameOptions`](#LibGit2.BlameOptions) for more information.
###
`LibGit2.GitBlob`Type
```
GitBlob(repo::GitRepo, hash::AbstractGitHash)
GitBlob(repo::GitRepo, spec::AbstractString)
```
Return a `GitBlob` object from `repo` specified by `hash`/`spec`.
* `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash.
* `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list.
###
`LibGit2.GitCommit`Type
```
GitCommit(repo::GitRepo, hash::AbstractGitHash)
GitCommit(repo::GitRepo, spec::AbstractString)
```
Return a `GitCommit` object from `repo` specified by `hash`/`spec`.
* `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash.
* `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list.
###
`LibGit2.GitHash`Type
```
GitHash
```
A git object identifier, based on the sha-1 hash. It is a 20 byte string (40 hex digits) used to identify a `GitObject` in a repository.
###
`LibGit2.GitObject`Type
```
GitObject(repo::GitRepo, hash::AbstractGitHash)
GitObject(repo::GitRepo, spec::AbstractString)
```
Return the specified object ([`GitCommit`](#LibGit2.GitCommit), [`GitBlob`](#LibGit2.GitBlob), [`GitTree`](#LibGit2.GitTree) or [`GitTag`](#LibGit2.GitTag)) from `repo` specified by `hash`/`spec`.
* `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash.
* `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list.
###
`LibGit2.GitRemote`Type
```
GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString) -> GitRemote
```
Look up a remote git repository using its name and URL. Uses the default fetch refspec.
**Examples**
```
repo = LibGit2.init(repo_path)
remote = LibGit2.GitRemote(repo, "upstream", repo_url)
```
```
GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString, fetch_spec::AbstractString) -> GitRemote
```
Look up a remote git repository using the repository's name and URL, as well as specifications for how to fetch from the remote (e.g. which remote branch to fetch from).
**Examples**
```
repo = LibGit2.init(repo_path)
refspec = "+refs/heads/mybranch:refs/remotes/origin/mybranch"
remote = LibGit2.GitRemote(repo, "upstream", repo_url, refspec)
```
###
`LibGit2.GitRemoteAnon`Function
```
GitRemoteAnon(repo::GitRepo, url::AbstractString) -> GitRemote
```
Look up a remote git repository using only its URL, not its name.
**Examples**
```
repo = LibGit2.init(repo_path)
remote = LibGit2.GitRemoteAnon(repo, repo_url)
```
###
`LibGit2.GitRepo`Type
```
LibGit2.GitRepo(path::AbstractString)
```
Open a git repository at `path`.
###
`LibGit2.GitRepoExt`Function
```
LibGit2.GitRepoExt(path::AbstractString, flags::Cuint = Cuint(Consts.REPOSITORY_OPEN_DEFAULT))
```
Open a git repository at `path` with extended controls (for instance, if the current user must be a member of a special access group to read `path`).
###
`LibGit2.GitRevWalker`Type
```
GitRevWalker(repo::GitRepo)
```
A `GitRevWalker` *walks* through the *revisions* (i.e. commits) of a git repository `repo`. It is a collection of the commits in the repository, and supports iteration and calls to [`LibGit2.map`](#LibGit2.map) and [`LibGit2.count`](#LibGit2.count) (for instance, `LibGit2.count` could be used to determine what percentage of commits in a repository were made by a certain author).
```
cnt = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker
LibGit2.count((oid,repo)->(oid == commit_oid1), walker, oid=commit_oid1, by=LibGit2.Consts.SORT_TIME)
end
```
Here, `LibGit2.count` finds the number of commits along the walk with a certain `GitHash`. Since the `GitHash` is unique to a commit, `cnt` will be `1`.
###
`LibGit2.GitShortHash`Type
```
GitShortHash(hash::GitHash, len::Integer)
```
A shortened git object identifier, which can be used to identify a git object when it is unique, consisting of the initial `len` hexadecimal digits of `hash` (the remaining digits are ignored).
###
`LibGit2.GitSignature`Type
```
LibGit2.GitSignature
```
This is a Julia wrapper around a pointer to a [`git_signature`](https://libgit2.org/libgit2/#HEAD/type/git_signature) object.
###
`LibGit2.GitStatus`Type
```
LibGit2.GitStatus(repo::GitRepo; status_opts=StatusOptions())
```
Collect information about the status of each file in the git repository `repo` (e.g. is the file modified, staged, etc.). `status_opts` can be used to set various options, for instance whether or not to look at untracked files or whether to include submodules or not. See [`StatusOptions`](#LibGit2.StatusOptions) for more information.
###
`LibGit2.GitTag`Type
```
GitTag(repo::GitRepo, hash::AbstractGitHash)
GitTag(repo::GitRepo, spec::AbstractString)
```
Return a `GitTag` object from `repo` specified by `hash`/`spec`.
* `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash.
* `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list.
###
`LibGit2.GitTree`Type
```
GitTree(repo::GitRepo, hash::AbstractGitHash)
GitTree(repo::GitRepo, spec::AbstractString)
```
Return a `GitTree` object from `repo` specified by `hash`/`spec`.
* `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash.
* `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list.
###
`LibGit2.IndexEntry`Type
```
LibGit2.IndexEntry
```
In-memory representation of a file entry in the index. Matches the [`git_index_entry`](https://libgit2.org/libgit2/#HEAD/type/git_index_entry) struct.
###
`LibGit2.IndexTime`Type
```
LibGit2.IndexTime
```
Matches the [`git_index_time`](https://libgit2.org/libgit2/#HEAD/type/git_index_time) struct.
###
`LibGit2.BlameOptions`Type
```
LibGit2.BlameOptions
```
Matches the [`git_blame_options`](https://libgit2.org/libgit2/#HEAD/type/git_blame_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `flags`: one of `Consts.BLAME_NORMAL` or `Consts.BLAME_FIRST_PARENT` (the other blame flags are not yet implemented by libgit2).
* `min_match_characters`: the minimum number of *alphanumeric* characters which much change in a commit in order for the change to be associated with that commit. The default is 20. Only takes effect if one of the `Consts.BLAME_*_COPIES` flags are used, which libgit2 does not implement yet.
* `newest_commit`: the [`GitHash`](#LibGit2.GitHash) of the newest commit from which to look at changes.
* `oldest_commit`: the [`GitHash`](#LibGit2.GitHash) of the oldest commit from which to look at changes.
* `min_line`: the first line of the file from which to starting blaming. The default is `1`.
* `max_line`: the last line of the file to which to blame. The default is `0`, meaning the last line of the file.
###
`LibGit2.MergeOptions`Type
```
LibGit2.MergeOptions
```
Matches the [`git_merge_options`](https://libgit2.org/libgit2/#HEAD/type/git_merge_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `flags`: an `enum` for flags describing merge behavior. Defined in [`git_merge_flag_t`](https://github.com/libgit2/libgit2/blob/HEAD/include/git2/merge.h#L95). The corresponding Julia enum is `GIT_MERGE` and has values:
+ `MERGE_FIND_RENAMES`: detect if a file has been renamed between the common ancestor and the "ours" or "theirs" side of the merge. Allows merges where a file has been renamed.
+ `MERGE_FAIL_ON_CONFLICT`: exit immediately if a conflict is found rather than trying to resolve it.
+ `MERGE_SKIP_REUC`: do not write the REUC extension on the index resulting from the merge.
+ `MERGE_NO_RECURSIVE`: if the commits being merged have multiple merge bases, use the first one, rather than trying to recursively merge the bases.
* `rename_threshold`: how similar two files must to consider one a rename of the other. This is an integer that sets the percentage similarity. The default is 50.
* `target_limit`: the maximum number of files to compare with to look for renames. The default is 200.
* `metric`: optional custom function to use to determine the similarity between two files for rename detection.
* `recursion_limit`: the upper limit on the number of merges of common ancestors to perform to try to build a new virtual merge base for the merge. The default is no limit. This field is only present on libgit2 versions newer than 0.24.0.
* `default_driver`: the merge driver to use if both sides have changed. This field is only present on libgit2 versions newer than 0.25.0.
* `file_favor`: how to handle conflicting file contents for the `text` driver.
+ `MERGE_FILE_FAVOR_NORMAL`: if both sides of the merge have changes to a section, make a note of the conflict in the index which `git checkout` will use to create a merge file, which the user can then reference to resolve the conflicts. This is the default.
+ `MERGE_FILE_FAVOR_OURS`: if both sides of the merge have changes to a section, use the version in the "ours" side of the merge in the index.
+ `MERGE_FILE_FAVOR_THEIRS`: if both sides of the merge have changes to a section, use the version in the "theirs" side of the merge in the index.
+ `MERGE_FILE_FAVOR_UNION`: if both sides of the merge have changes to a section, include each unique line from both sides in the file which is put into the index.
* `file_flags`: guidelines for merging files.
###
`LibGit2.ProxyOptions`Type
```
LibGit2.ProxyOptions
```
Options for connecting through a proxy.
Matches the [`git_proxy_options`](https://libgit2.org/libgit2/#HEAD/type/git_proxy_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `proxytype`: an `enum` for the type of proxy to use. Defined in [`git_proxy_t`](https://libgit2.org/libgit2/#HEAD/type/git_proxy_t). The corresponding Julia enum is `GIT_PROXY` and has values:
+ `PROXY_NONE`: do not attempt the connection through a proxy.
+ `PROXY_AUTO`: attempt to figure out the proxy configuration from the git configuration.
+ `PROXY_SPECIFIED`: connect using the URL given in the `url` field of this struct.Default is to auto-detect the proxy type.
* `url`: the URL of the proxy.
* `credential_cb`: a pointer to a callback function which will be called if the remote requires authentication to connect.
* `certificate_cb`: a pointer to a callback function which will be called if certificate verification fails. This lets the user decide whether or not to keep connecting. If the function returns `1`, connecting will be allowed. If it returns `0`, the connection will not be allowed. A negative value can be used to return errors.
* `payload`: the payload to be provided to the two callback functions.
**Examples**
```
julia> fo = LibGit2.FetchOptions(
proxy_opts = LibGit2.ProxyOptions(url = Cstring("https://my_proxy_url.com")))
julia> fetch(remote, "master", options=fo)
```
###
`LibGit2.PushOptions`Type
```
LibGit2.PushOptions
```
Matches the [`git_push_options`](https://libgit2.org/libgit2/#HEAD/type/git_push_options) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `parallelism`: if a pack file must be created, this variable sets the number of worker threads which will be spawned by the packbuilder. If `0`, the packbuilder will auto-set the number of threads to use. The default is `1`.
* `callbacks`: the callbacks (e.g. for authentication with the remote) to use for the push.
* `proxy_opts`: only relevant if the LibGit2 version is greater than or equal to `0.25.0`. Sets options for using a proxy to communicate with a remote. See [`ProxyOptions`](#LibGit2.ProxyOptions) for more information.
* `custom_headers`: only relevant if the LibGit2 version is greater than or equal to `0.24.0`. Extra headers needed for the push operation.
###
`LibGit2.RebaseOperation`Type
```
LibGit2.RebaseOperation
```
Describes a single instruction/operation to be performed during the rebase. Matches the [`git_rebase_operation`](https://libgit2.org/libgit2/#HEAD/type/git_rebase_operation_t) struct.
The fields represent:
* `optype`: the type of rebase operation currently being performed. The options are:
+ `REBASE_OPERATION_PICK`: cherry-pick the commit in question.
+ `REBASE_OPERATION_REWORD`: cherry-pick the commit in question, but rewrite its message using the prompt.
+ `REBASE_OPERATION_EDIT`: cherry-pick the commit in question, but allow the user to edit the commit's contents and its message.
+ `REBASE_OPERATION_SQUASH`: squash the commit in question into the previous commit. The commit messages of the two commits will be merged.
+ `REBASE_OPERATION_FIXUP`: squash the commit in question into the previous commit. Only the commit message of the previous commit will be used.
+ `REBASE_OPERATION_EXEC`: do not cherry-pick a commit. Run a command and continue if the command exits successfully.
* `id`: the [`GitHash`](#LibGit2.GitHash) of the commit being worked on during this rebase step.
* `exec`: in case `REBASE_OPERATION_EXEC` is used, the command to run during this step (for instance, running the test suite after each commit).
###
`LibGit2.RebaseOptions`Type
```
LibGit2.RebaseOptions
```
Matches the `git_rebase_options` struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `quiet`: inform other git clients helping with/working on the rebase that the rebase should be done "quietly". Used for interoperability. The default is `1`.
* `inmemory`: start an in-memory rebase. Callers working on the rebase can go through its steps and commit any changes, but cannot rewind HEAD or update the repository. The [`workdir`](#LibGit2.workdir) will not be modified. Only present on libgit2 versions newer than or equal to 0.24.0.
* `rewrite_notes_ref`: name of the reference to notes to use to rewrite the commit notes as the rebase is finished.
* `merge_opts`: merge options controlling how the trees will be merged at each rebase step. Only present on libgit2 versions newer than or equal to 0.24.0.
* `checkout_opts`: checkout options for writing files when initializing the rebase, stepping through it, and aborting it. See [`CheckoutOptions`](#LibGit2.CheckoutOptions) for more information.
###
`LibGit2.RemoteCallbacks`Type
```
LibGit2.RemoteCallbacks
```
Callback settings. Matches the [`git_remote_callbacks`](https://libgit2.org/libgit2/#HEAD/type/git_remote_callbacks) struct.
###
`LibGit2.SignatureStruct`Type
```
LibGit2.SignatureStruct
```
An action signature (e.g. for committers, taggers, etc). Matches the [`git_signature`](https://libgit2.org/libgit2/#HEAD/type/git_signature) struct.
The fields represent:
* `name`: The full name of the committer or author of the commit.
* `email`: The email at which the committer/author can be contacted.
* `when`: a [`TimeStruct`](#LibGit2.TimeStruct) indicating when the commit was authored/committed into the repository.
###
`LibGit2.StatusEntry`Type
```
LibGit2.StatusEntry
```
Providing the differences between the file as it exists in HEAD and the index, and providing the differences between the index and the working directory. Matches the `git_status_entry` struct.
The fields represent:
* `status`: contains the status flags for the file, indicating if it is current, or has been changed in some way in the index or work tree.
* `head_to_index`: a pointer to a [`DiffDelta`](#LibGit2.DiffDelta) which encapsulates the difference(s) between the file as it exists in HEAD and in the index.
* `index_to_workdir`: a pointer to a `DiffDelta` which encapsulates the difference(s) between the file as it exists in the index and in the [`workdir`](#LibGit2.workdir).
###
`LibGit2.StatusOptions`Type
```
LibGit2.StatusOptions
```
Options to control how `git_status_foreach_ext()` will issue callbacks. Matches the [`git_status_opt_t`](https://libgit2.org/libgit2/#HEAD/type/git_status_opt_t) struct.
The fields represent:
* `version`: version of the struct in use, in case this changes later. For now, always `1`.
* `show`: a flag for which files to examine and in which order. The default is `Consts.STATUS_SHOW_INDEX_AND_WORKDIR`.
* `flags`: flags for controlling any callbacks used in a status call.
* `pathspec`: an array of paths to use for path-matching. The behavior of the path-matching will vary depending on the values of `show` and `flags`.
* The `baseline` is the tree to be used for comparison to the working directory and index; defaults to HEAD.
###
`LibGit2.StrArrayStruct`Type
```
LibGit2.StrArrayStruct
```
A LibGit2 representation of an array of strings. Matches the [`git_strarray`](https://libgit2.org/libgit2/#HEAD/type/git_strarray) struct.
When fetching data from LibGit2, a typical usage would look like:
```
sa_ref = Ref(StrArrayStruct())
@check ccall(..., (Ptr{StrArrayStruct},), sa_ref)
res = convert(Vector{String}, sa_ref[])
free(sa_ref)
```
In particular, note that `LibGit2.free` should be called afterward on the `Ref` object.
Conversely, when passing a vector of strings to LibGit2, it is generally simplest to rely on implicit conversion:
```
strs = String[...]
@check ccall(..., (Ptr{StrArrayStruct},), strs)
```
Note that no call to `free` is required as the data is allocated by Julia.
###
`LibGit2.TimeStruct`Type
```
LibGit2.TimeStruct
```
Time in a signature. Matches the [`git_time`](https://libgit2.org/libgit2/#HEAD/type/git_time) struct.
###
`LibGit2.add!`Function
```
add!(repo::GitRepo, files::AbstractString...; flags::Cuint = Consts.INDEX_ADD_DEFAULT)
add!(idx::GitIndex, files::AbstractString...; flags::Cuint = Consts.INDEX_ADD_DEFAULT)
```
Add all the files with paths specified by `files` to the index `idx` (or the index of the `repo`). If the file already exists, the index entry will be updated. If the file does not exist already, it will be newly added into the index. `files` may contain glob patterns which will be expanded and any matching files will be added (unless `INDEX_ADD_DISABLE_PATHSPEC_MATCH` is set, see below). If a file has been ignored (in `.gitignore` or in the config), it *will not* be added, *unless* it is already being tracked in the index, in which case it *will* be updated. The keyword argument `flags` is a set of bit-flags which control the behavior with respect to ignored files:
* `Consts.INDEX_ADD_DEFAULT` - default, described above.
* `Consts.INDEX_ADD_FORCE` - disregard the existing ignore rules and force addition of the file to the index even if it is already ignored.
* `Consts.INDEX_ADD_CHECK_PATHSPEC` - cannot be used at the same time as `INDEX_ADD_FORCE`. Check that each file in `files` which exists on disk is not in the ignore list. If one of the files *is* ignored, the function will return `EINVALIDSPEC`.
* `Consts.INDEX_ADD_DISABLE_PATHSPEC_MATCH` - turn off glob matching, and only add files to the index which exactly match the paths specified in `files`.
###
`LibGit2.add_fetch!`Function
```
add_fetch!(repo::GitRepo, rmt::GitRemote, fetch_spec::String)
```
Add a *fetch* refspec for the specified `rmt`. This refspec will contain information about which branch(es) to fetch from.
**Examples**
```
julia> LibGit2.add_fetch!(repo, remote, "upstream");
julia> LibGit2.fetch_refspecs(remote)
String["+refs/heads/*:refs/remotes/upstream/*"]
```
###
`LibGit2.add_push!`Function
```
add_push!(repo::GitRepo, rmt::GitRemote, push_spec::String)
```
Add a *push* refspec for the specified `rmt`. This refspec will contain information about which branch(es) to push to.
**Examples**
```
julia> LibGit2.add_push!(repo, remote, "refs/heads/master");
julia> remote = LibGit2.get(LibGit2.GitRemote, repo, branch);
julia> LibGit2.push_refspecs(remote)
String["refs/heads/master"]
```
You may need to [`close`](../../base/io-network/index#Base.close) and reopen the `GitRemote` in question after updating its push refspecs in order for the change to take effect and for calls to [`push`](#LibGit2.push) to work.
###
`LibGit2.addblob!`Function
```
LibGit2.addblob!(repo::GitRepo, path::AbstractString)
```
Read the file at `path` and adds it to the object database of `repo` as a loose blob. Return the [`GitHash`](#LibGit2.GitHash) of the resulting blob.
**Examples**
```
hash_str = string(commit_oid)
blob_file = joinpath(repo_path, ".git", "objects", hash_str[1:2], hash_str[3:end])
id = LibGit2.addblob!(repo, blob_file)
```
###
`LibGit2.author`Function
```
author(c::GitCommit)
```
Return the `Signature` of the author of the commit `c`. The author is the person who made changes to the relevant file(s). See also [`committer`](#LibGit2.committer).
###
`LibGit2.authors`Function
```
authors(repo::GitRepo) -> Vector{Signature}
```
Return all authors of commits to the `repo` repository.
**Examples**
```
repo = LibGit2.GitRepo(repo_path)
repo_file = open(joinpath(repo_path, test_file), "a")
println(repo_file, commit_msg)
flush(repo_file)
LibGit2.add!(repo, test_file)
sig = LibGit2.Signature("TEST", "[email protected]", round(time(), 0), 0)
commit_oid1 = LibGit2.commit(repo, "commit1"; author=sig, committer=sig)
println(repo_file, randstring(10))
flush(repo_file)
LibGit2.add!(repo, test_file)
commit_oid2 = LibGit2.commit(repo, "commit2"; author=sig, committer=sig)
# will be a Vector of [sig, sig]
auths = LibGit2.authors(repo)
```
###
`LibGit2.branch`Function
```
branch(repo::GitRepo)
```
Equivalent to `git branch`. Create a new branch from the current HEAD.
###
`LibGit2.branch!`Function
```
branch!(repo::GitRepo, branch_name::AbstractString, commit::AbstractString=""; kwargs...)
```
Checkout a new git branch in the `repo` repository. `commit` is the [`GitHash`](#LibGit2.GitHash), in string form, which will be the start of the new branch. If `commit` is an empty string, the current HEAD will be used.
The keyword arguments are:
* `track::AbstractString=""`: the name of the remote branch this new branch should track, if any. If empty (the default), no remote branch will be tracked.
* `force::Bool=false`: if `true`, branch creation will be forced.
* `set_head::Bool=true`: if `true`, after the branch creation finishes the branch head will be set as the HEAD of `repo`.
Equivalent to `git checkout [-b|-B] <branch_name> [<commit>] [--track <track>]`.
**Examples**
```
repo = LibGit2.GitRepo(repo_path)
LibGit2.branch!(repo, "new_branch", set_head=false)
```
###
`LibGit2.checkout!`Function
```
checkout!(repo::GitRepo, commit::AbstractString=""; force::Bool=true)
```
Equivalent to `git checkout [-f] --detach <commit>`. Checkout the git commit `commit` (a [`GitHash`](#LibGit2.GitHash) in string form) in `repo`. If `force` is `true`, force the checkout and discard any current changes. Note that this detaches the current HEAD.
**Examples**
```
repo = LibGit2.init(repo_path)
open(joinpath(LibGit2.path(repo), "file1"), "w") do f
write(f, "111
")
end
LibGit2.add!(repo, "file1")
commit_oid = LibGit2.commit(repo, "add file1")
open(joinpath(LibGit2.path(repo), "file1"), "w") do f
write(f, "112
")
end
# would fail without the force=true
# since there are modifications to the file
LibGit2.checkout!(repo, string(commit_oid), force=true)
```
###
`LibGit2.clone`Function
```
clone(repo_url::AbstractString, repo_path::AbstractString, clone_opts::CloneOptions)
```
Clone the remote repository at `repo_url` (which can be a remote URL or a path on the local filesystem) to `repo_path` (which must be a path on the local filesystem). Options for the clone, such as whether to perform a bare clone or not, are set by [`CloneOptions`](#LibGit2.CloneOptions).
**Examples**
```
repo_url = "https://github.com/JuliaLang/Example.jl"
repo = LibGit2.clone(repo_url, "/home/me/projects/Example")
```
```
clone(repo_url::AbstractString, repo_path::AbstractString; kwargs...)
```
Clone a remote repository located at `repo_url` to the local filesystem location `repo_path`.
The keyword arguments are:
* `branch::AbstractString=""`: which branch of the remote to clone, if not the default repository branch (usually `master`).
* `isbare::Bool=false`: if `true`, clone the remote as a bare repository, which will make `repo_path` itself the git directory instead of `repo_path/.git`. This means that a working tree cannot be checked out. Plays the role of the git CLI argument `--bare`.
* `remote_cb::Ptr{Cvoid}=C_NULL`: a callback which will be used to create the remote before it is cloned. If `C_NULL` (the default), no attempt will be made to create the remote - it will be assumed to already exist.
* `credentials::Creds=nothing`: provides credentials and/or settings when authenticating against a private repository.
* `callbacks::Callbacks=Callbacks()`: user provided callbacks and payloads.
Equivalent to `git clone [-b <branch>] [--bare] <repo_url> <repo_path>`.
**Examples**
```
repo_url = "https://github.com/JuliaLang/Example.jl"
repo1 = LibGit2.clone(repo_url, "test_path")
repo2 = LibGit2.clone(repo_url, "test_path", isbare=true)
julia_url = "https://github.com/JuliaLang/julia"
julia_repo = LibGit2.clone(julia_url, "julia_path", branch="release-0.6")
```
###
`LibGit2.commit`Function
```
commit(repo::GitRepo, msg::AbstractString; kwargs...) -> GitHash
```
Wrapper around [`git_commit_create`](https://libgit2.org/libgit2/#HEAD/group/commit/git_commit_create). Create a commit in the repository `repo`. `msg` is the commit message. Return the OID of the new commit.
The keyword arguments are:
* `refname::AbstractString=Consts.HEAD_FILE`: if not NULL, the name of the reference to update to point to the new commit. For example, `"HEAD"` will update the HEAD of the current branch. If the reference does not yet exist, it will be created.
* `author::Signature = Signature(repo)` is a `Signature` containing information about the person who authored the commit.
* `committer::Signature = Signature(repo)` is a `Signature` containing information about the person who committed the commit to the repository. Not necessarily the same as `author`, for instance if `author` emailed a patch to `committer` who committed it.
* `tree_id::GitHash = GitHash()` is a git tree to use to create the commit, showing its ancestry and relationship with any other history. `tree` must belong to `repo`.
* `parent_ids::Vector{GitHash}=GitHash[]` is a list of commits by [`GitHash`](#LibGit2.GitHash) to use as parent commits for the new one, and may be empty. A commit might have multiple parents if it is a merge commit, for example.
```
LibGit2.commit(rb::GitRebase, sig::GitSignature)
```
Commit the current patch to the rebase `rb`, using `sig` as the committer. Is silent if the commit has already been applied.
###
`LibGit2.committer`Function
```
committer(c::GitCommit)
```
Return the `Signature` of the committer of the commit `c`. The committer is the person who committed the changes originally authored by the [`author`](#LibGit2.author), but need not be the same as the `author`, for example, if the `author` emailed a patch to a `committer` who committed it.
###
`LibGit2.count`Function
```
LibGit2.count(f::Function, walker::GitRevWalker; oid::GitHash=GitHash(), by::Cint=Consts.SORT_NONE, rev::Bool=false)
```
Using the [`GitRevWalker`](#LibGit2.GitRevWalker) `walker` to "walk" over every commit in the repository's history, find the number of commits which return `true` when `f` is applied to them. The keyword arguments are: \* `oid`: The [`GitHash`](#LibGit2.GitHash) of the commit to begin the walk from. The default is to use [`push_head!`](#LibGit2.push_head!) and therefore the HEAD commit and all its ancestors. \* `by`: The sorting method. The default is not to sort. Other options are to sort by topology (`LibGit2.Consts.SORT_TOPOLOGICAL`), to sort forwards in time (`LibGit2.Consts.SORT_TIME`, most ancient first) or to sort backwards in time (`LibGit2.Consts.SORT_REVERSE`, most recent first). \* `rev`: Whether to reverse the sorted order (for instance, if topological sorting is used).
**Examples**
```
cnt = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker
LibGit2.count((oid, repo)->(oid == commit_oid1), walker, oid=commit_oid1, by=LibGit2.Consts.SORT_TIME)
end
```
`LibGit2.count` finds the number of commits along the walk with a certain `GitHash` `commit_oid1`, starting the walk from that commit and moving forwards in time from it. Since the `GitHash` is unique to a commit, `cnt` will be `1`.
###
`LibGit2.counthunks`Function
```
counthunks(blame::GitBlame)
```
Return the number of distinct "hunks" with a file. A hunk may contain multiple lines. A hunk is usually a piece of a file that was added/changed/removed together, for example, a function added to a source file or an inner loop that was optimized out of that function later.
###
`LibGit2.create_branch`Function
```
LibGit2.create_branch(repo::GitRepo, bname::AbstractString, commit_obj::GitCommit; force::Bool=false)
```
Create a new branch in the repository `repo` with name `bname`, which points to commit `commit_obj` (which has to be part of `repo`). If `force` is `true`, overwrite an existing branch named `bname` if it exists. If `force` is `false` and a branch already exists named `bname`, this function will throw an error.
###
`LibGit2.credentials_callback`Function
```
credential_callback(...) -> Cint
```
A LibGit2 credential callback function which provides different credential acquisition functionality w.r.t. a connection protocol. The `payload_ptr` is required to contain a `LibGit2.CredentialPayload` object which will keep track of state and settings.
The `allowed_types` contains a bitmask of `LibGit2.Consts.GIT_CREDTYPE` values specifying which authentication methods should be attempted.
Credential authentication is done in the following order (if supported):
* SSH agent
* SSH private/public key pair
* Username/password plain text
If a user is presented with a credential prompt they can abort the prompt by typing `^D` (pressing the control key together with the `d` key).
**Note**: Due to the specifics of the `libgit2` authentication procedure, when authentication fails, this function is called again without any indication whether authentication was successful or not. To avoid an infinite loop from repeatedly using the same faulty credentials, we will keep track of state using the payload.
For addition details see the LibGit2 guide on [authenticating against a server](https://libgit2.org/docs/guides/authentication/).
###
`LibGit2.credentials_cb`Function
C function pointer for `credentials_callback`
###
`LibGit2.default_signature`Function
Return signature object. Free it after use.
###
`LibGit2.delete_branch`Function
```
LibGit2.delete_branch(branch::GitReference)
```
Delete the branch pointed to by `branch`.
###
`LibGit2.diff_files`Function
```
diff_files(repo::GitRepo, branch1::AbstractString, branch2::AbstractString; kwarg...) -> Vector{AbstractString}
```
Show which files have changed in the git repository `repo` between branches `branch1` and `branch2`.
The keyword argument is:
* `filter::Set{Consts.DELTA_STATUS}=Set([Consts.DELTA_ADDED, Consts.DELTA_MODIFIED, Consts.DELTA_DELETED]))`, and it sets options for the diff. The default is to show files added, modified, or deleted.
Return only the *names* of the files which have changed, *not* their contents.
**Examples**
```
LibGit2.branch!(repo, "branch/a")
LibGit2.branch!(repo, "branch/b")
# add a file to repo
open(joinpath(LibGit2.path(repo),"file"),"w") do f
write(f, "hello repo
")
end
LibGit2.add!(repo, "file")
LibGit2.commit(repo, "add file")
# returns ["file"]
filt = Set([LibGit2.Consts.DELTA_ADDED])
files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt)
# returns [] because existing files weren't modified
filt = Set([LibGit2.Consts.DELTA_MODIFIED])
files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt)
```
Equivalent to `git diff --name-only --diff-filter=<filter> <branch1> <branch2>`.
###
`LibGit2.entryid`Function
```
entryid(te::GitTreeEntry)
```
Return the [`GitHash`](#LibGit2.GitHash) of the object to which `te` refers.
###
`LibGit2.entrytype`Function
```
entrytype(te::GitTreeEntry)
```
Return the type of the object to which `te` refers. The result will be one of the types which [`objtype`](#LibGit2.objtype) returns, e.g. a `GitTree` or `GitBlob`.
###
`LibGit2.fetch`Function
```
fetch(rmt::GitRemote, refspecs; options::FetchOptions=FetchOptions(), msg="")
```
Fetch from the specified `rmt` remote git repository, using `refspecs` to determine which remote branch(es) to fetch. The keyword arguments are:
* `options`: determines the options for the fetch, e.g. whether to prune afterwards. See [`FetchOptions`](#LibGit2.FetchOptions) for more information.
* `msg`: a message to insert into the reflogs.
```
fetch(repo::GitRepo; kwargs...)
```
Fetches updates from an upstream of the repository `repo`.
The keyword arguments are:
* `remote::AbstractString="origin"`: which remote, specified by name, of `repo` to fetch from. If this is empty, the URL will be used to construct an anonymous remote.
* `remoteurl::AbstractString=""`: the URL of `remote`. If not specified, will be assumed based on the given name of `remote`.
* `refspecs=AbstractString[]`: determines properties of the fetch.
* `credentials=nothing`: provides credentials and/or settings when authenticating against a private `remote`.
* `callbacks=Callbacks()`: user provided callbacks and payloads.
Equivalent to `git fetch [<remoteurl>|<repo>] [<refspecs>]`.
###
`LibGit2.fetchheads`Function
```
fetchheads(repo::GitRepo) -> Vector{FetchHead}
```
Return the list of all the fetch heads for `repo`, each represented as a [`FetchHead`](#LibGit2.FetchHead), including their names, URLs, and merge statuses.
**Examples**
```
julia> fetch_heads = LibGit2.fetchheads(repo);
julia> fetch_heads[1].name
"refs/heads/master"
julia> fetch_heads[1].ismerge
true
julia> fetch_heads[2].name
"refs/heads/test_branch"
julia> fetch_heads[2].ismerge
false
```
###
`LibGit2.fetch_refspecs`Function
```
fetch_refspecs(rmt::GitRemote) -> Vector{String}
```
Get the *fetch* refspecs for the specified `rmt`. These refspecs contain information about which branch(es) to fetch from.
**Examples**
```
julia> remote = LibGit2.get(LibGit2.GitRemote, repo, "upstream");
julia> LibGit2.add_fetch!(repo, remote, "upstream");
julia> LibGit2.fetch_refspecs(remote)
String["+refs/heads/*:refs/remotes/upstream/*"]
```
###
`LibGit2.fetchhead_foreach_cb`Function
C function pointer for `fetchhead_foreach_callback`
###
`LibGit2.merge_base`Function
```
merge_base(repo::GitRepo, one::AbstractString, two::AbstractString) -> GitHash
```
Find a merge base (a common ancestor) between the commits `one` and `two`. `one` and `two` may both be in string form. Return the `GitHash` of the merge base.
###
`LibGit2.merge!`Method
```
merge!(repo::GitRepo; kwargs...) -> Bool
```
Perform a git merge on the repository `repo`, merging commits with diverging history into the current branch. Return `true` if the merge succeeded, `false` if not.
The keyword arguments are:
* `committish::AbstractString=""`: Merge the named commit(s) in `committish`.
* `branch::AbstractString=""`: Merge the branch `branch` and all its commits since it diverged from the current branch.
* `fastforward::Bool=false`: If `fastforward` is `true`, only merge if the merge is a fast-forward (the current branch head is an ancestor of the commits to be merged), otherwise refuse to merge and return `false`. This is equivalent to the git CLI option `--ff-only`.
* `merge_opts::MergeOptions=MergeOptions()`: `merge_opts` specifies options for the merge, such as merge strategy in case of conflicts.
* `checkout_opts::CheckoutOptions=CheckoutOptions()`: `checkout_opts` specifies options for the checkout step.
Equivalent to `git merge [--ff-only] [<committish> | <branch>]`.
If you specify a `branch`, this must be done in reference format, since the string will be turned into a `GitReference`. For example, if you wanted to merge branch `branch_a`, you would call `merge!(repo, branch="refs/heads/branch_a")`.
###
`LibGit2.merge!`Method
```
merge!(repo::GitRepo, anns::Vector{GitAnnotated}; kwargs...) -> Bool
```
Merge changes from the annotated commits (captured as [`GitAnnotated`](#LibGit2.GitAnnotated) objects) `anns` into the HEAD of the repository `repo`. The keyword arguments are:
* `merge_opts::MergeOptions = MergeOptions()`: options for how to perform the merge, including whether fastforwarding is allowed. See [`MergeOptions`](#LibGit2.MergeOptions) for more information.
* `checkout_opts::CheckoutOptions = CheckoutOptions()`: options for how to perform the checkout. See [`CheckoutOptions`](#LibGit2.CheckoutOptions) for more information.
`anns` may refer to remote or local branch heads. Return `true` if the merge is successful, otherwise return `false` (for instance, if no merge is possible because the branches have no common ancestor).
**Examples**
```
upst_ann = LibGit2.GitAnnotated(repo, "branch/a")
# merge the branch in
LibGit2.merge!(repo, [upst_ann])
```
###
`LibGit2.merge!`Method
```
merge!(repo::GitRepo, anns::Vector{GitAnnotated}, fastforward::Bool; kwargs...) -> Bool
```
Merge changes from the annotated commits (captured as [`GitAnnotated`](#LibGit2.GitAnnotated) objects) `anns` into the HEAD of the repository `repo`. If `fastforward` is `true`, *only* a fastforward merge is allowed. In this case, if conflicts occur, the merge will fail. Otherwise, if `fastforward` is `false`, the merge may produce a conflict file which the user will need to resolve.
The keyword arguments are:
* `merge_opts::MergeOptions = MergeOptions()`: options for how to perform the merge, including whether fastforwarding is allowed. See [`MergeOptions`](#LibGit2.MergeOptions) for more information.
* `checkout_opts::CheckoutOptions = CheckoutOptions()`: options for how to perform the checkout. See [`CheckoutOptions`](#LibGit2.CheckoutOptions) for more information.
`anns` may refer to remote or local branch heads. Return `true` if the merge is successful, otherwise return `false` (for instance, if no merge is possible because the branches have no common ancestor).
**Examples**
```
upst_ann_1 = LibGit2.GitAnnotated(repo, "branch/a")
# merge the branch in, fastforward
LibGit2.merge!(repo, [upst_ann_1], true)
# merge conflicts!
upst_ann_2 = LibGit2.GitAnnotated(repo, "branch/b")
# merge the branch in, try to fastforward
LibGit2.merge!(repo, [upst_ann_2], true) # will return false
LibGit2.merge!(repo, [upst_ann_2], false) # will return true
```
###
`LibGit2.ffmerge!`Function
```
ffmerge!(repo::GitRepo, ann::GitAnnotated)
```
Fastforward merge changes into current HEAD. This is only possible if the commit referred to by `ann` is descended from the current HEAD (e.g. if pulling changes from a remote branch which is simply ahead of the local branch tip).
###
`LibGit2.fullname`Function
```
LibGit2.fullname(ref::GitReference)
```
Return the name of the reference pointed to by the symbolic reference `ref`. If `ref` is not a symbolic reference, return an empty string.
###
`LibGit2.features`Function
```
features()
```
Return a list of git features the current version of libgit2 supports, such as threading or using HTTPS or SSH.
###
`LibGit2.filename`Function
```
filename(te::GitTreeEntry)
```
Return the filename of the object on disk to which `te` refers.
###
`LibGit2.filemode`Function
```
filemode(te::GitTreeEntry) -> Cint
```
Return the UNIX filemode of the object on disk to which `te` refers as an integer.
###
`LibGit2.gitdir`Function
```
LibGit2.gitdir(repo::GitRepo)
```
Return the location of the "git" files of `repo`:
* for normal repositories, this is the location of the `.git` folder.
* for bare repositories, this is the location of the repository itself.
See also [`workdir`](#LibGit2.workdir), [`path`](#LibGit2.path).
###
`LibGit2.git_url`Function
```
LibGit2.git_url(; kwargs...) -> String
```
Create a string based upon the URL components provided. When the `scheme` keyword is not provided the URL produced will use the alternative [scp-like syntax](https://git-scm.com/docs/git-clone#_git_urls_a_id_urls_a).
**Keywords**
* `scheme::AbstractString=""`: the URL scheme which identifies the protocol to be used. For HTTP use "http", SSH use "ssh", etc. When `scheme` is not provided the output format will be "ssh" but using the scp-like syntax.
* `username::AbstractString=""`: the username to use in the output if provided.
* `password::AbstractString=""`: the password to use in the output if provided.
* `host::AbstractString=""`: the hostname to use in the output. A hostname is required to be specified.
* `port::Union{AbstractString,Integer}=""`: the port number to use in the output if provided. Cannot be specified when using the scp-like syntax.
* `path::AbstractString=""`: the path to use in the output if provided.
Avoid using passwords in URLs. Unlike the credential objects, Julia is not able to securely zero or destroy the sensitive data after use and the password may remain in memory; possibly to be exposed by an uninitialized memory.
**Examples**
```
julia> LibGit2.git_url(username="git", host="github.com", path="JuliaLang/julia.git")
"[email protected]:JuliaLang/julia.git"
julia> LibGit2.git_url(scheme="https", host="github.com", path="/JuliaLang/julia.git")
"https://github.com/JuliaLang/julia.git"
julia> LibGit2.git_url(scheme="ssh", username="git", host="github.com", port=2222, path="JuliaLang/julia.git")
"ssh://[email protected]:2222/JuliaLang/julia.git"
```
###
`LibGit2.@githash_str`Macro
```
@githash_str -> AbstractGitHash
```
Construct a git hash object from the given string, returning a `GitShortHash` if the string is shorter than 40 hexadecimal digits, otherwise a `GitHash`.
**Examples**
```
julia> LibGit2.githash"d114feb74ce633"
GitShortHash("d114feb74ce633")
julia> LibGit2.githash"d114feb74ce63307afe878a5228ad014e0289a85"
GitHash("d114feb74ce63307afe878a5228ad014e0289a85")
```
###
`LibGit2.head`Function
```
LibGit2.head(repo::GitRepo) -> GitReference
```
Return a `GitReference` to the current HEAD of `repo`.
```
head(pkg::AbstractString) -> String
```
Return current HEAD [`GitHash`](#LibGit2.GitHash) of the `pkg` repo as a string.
###
`LibGit2.head!`Function
```
LibGit2.head!(repo::GitRepo, ref::GitReference) -> GitReference
```
Set the HEAD of `repo` to the object pointed to by `ref`.
###
`LibGit2.head_oid`Function
```
LibGit2.head_oid(repo::GitRepo) -> GitHash
```
Lookup the object id of the current HEAD of git repository `repo`.
###
`LibGit2.headname`Function
```
LibGit2.headname(repo::GitRepo)
```
Lookup the name of the current HEAD of git repository `repo`. If `repo` is currently detached, return the name of the HEAD it's detached from.
###
`LibGit2.init`Function
```
LibGit2.init(path::AbstractString, bare::Bool=false) -> GitRepo
```
Open a new git repository at `path`. If `bare` is `false`, the working tree will be created in `path/.git`. If `bare` is `true`, no working directory will be created.
###
`LibGit2.is_ancestor_of`Function
```
is_ancestor_of(a::AbstractString, b::AbstractString, repo::GitRepo) -> Bool
```
Return `true` if `a`, a [`GitHash`](#LibGit2.GitHash) in string form, is an ancestor of `b`, a [`GitHash`](#LibGit2.GitHash) in string form.
**Examples**
```
julia> repo = LibGit2.GitRepo(repo_path);
julia> LibGit2.add!(repo, test_file1);
julia> commit_oid1 = LibGit2.commit(repo, "commit1");
julia> LibGit2.add!(repo, test_file2);
julia> commit_oid2 = LibGit2.commit(repo, "commit2");
julia> LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo)
true
```
###
`LibGit2.isbinary`Function
```
isbinary(blob::GitBlob) -> Bool
```
Use a heuristic to guess if a file is binary: searching for NULL bytes and looking for a reasonable ratio of printable to non-printable characters among the first 8000 bytes.
###
`LibGit2.iscommit`Function
```
iscommit(id::AbstractString, repo::GitRepo) -> Bool
```
Check if commit `id` (which is a [`GitHash`](#LibGit2.GitHash) in string form) is in the repository.
**Examples**
```
julia> repo = LibGit2.GitRepo(repo_path);
julia> LibGit2.add!(repo, test_file);
julia> commit_oid = LibGit2.commit(repo, "add test_file");
julia> LibGit2.iscommit(string(commit_oid), repo)
true
```
###
`LibGit2.isdiff`Function
```
LibGit2.isdiff(repo::GitRepo, treeish::AbstractString, pathspecs::AbstractString=""; cached::Bool=false)
```
Checks if there are any differences between the tree specified by `treeish` and the tracked files in the working tree (if `cached=false`) or the index (if `cached=true`). `pathspecs` are the specifications for options for the diff.
**Examples**
```
repo = LibGit2.GitRepo(repo_path)
LibGit2.isdiff(repo, "HEAD") # should be false
open(joinpath(repo_path, new_file), "a") do f
println(f, "here's my cool new file")
end
LibGit2.isdiff(repo, "HEAD") # now true
```
Equivalent to `git diff-index <treeish> [-- <pathspecs>]`.
###
`LibGit2.isdirty`Function
```
LibGit2.isdirty(repo::GitRepo, pathspecs::AbstractString=""; cached::Bool=false) -> Bool
```
Check if there have been any changes to tracked files in the working tree (if `cached=false`) or the index (if `cached=true`). `pathspecs` are the specifications for options for the diff.
**Examples**
```
repo = LibGit2.GitRepo(repo_path)
LibGit2.isdirty(repo) # should be false
open(joinpath(repo_path, new_file), "a") do f
println(f, "here's my cool new file")
end
LibGit2.isdirty(repo) # now true
LibGit2.isdirty(repo, new_file) # now true
```
Equivalent to `git diff-index HEAD [-- <pathspecs>]`.
###
`LibGit2.isorphan`Function
```
LibGit2.isorphan(repo::GitRepo)
```
Check if the current branch is an "orphan" branch, i.e. has no commits. The first commit to this branch will have no parents.
###
`LibGit2.isset`Function
```
isset(val::Integer, flag::Integer)
```
Test whether the bits of `val` indexed by `flag` are set (`1`) or unset (`0`).
###
`LibGit2.iszero`Function
```
iszero(id::GitHash) -> Bool
```
Determine whether all hexadecimal digits of the given [`GitHash`](#LibGit2.GitHash) are zero.
###
`LibGit2.lookup_branch`Function
```
lookup_branch(repo::GitRepo, branch_name::AbstractString, remote::Bool=false) -> Union{GitReference, Nothing}
```
Determine if the branch specified by `branch_name` exists in the repository `repo`. If `remote` is `true`, `repo` is assumed to be a remote git repository. Otherwise, it is part of the local filesystem.
Return either a `GitReference` to the requested branch if it exists, or [`nothing`](../../base/constants/index#Core.nothing) if not.
###
`LibGit2.map`Function
```
LibGit2.map(f::Function, walker::GitRevWalker; oid::GitHash=GitHash(), range::AbstractString="", by::Cint=Consts.SORT_NONE, rev::Bool=false)
```
Using the [`GitRevWalker`](#LibGit2.GitRevWalker) `walker` to "walk" over every commit in the repository's history, apply `f` to each commit in the walk. The keyword arguments are: \* `oid`: The [`GitHash`](#LibGit2.GitHash) of the commit to begin the walk from. The default is to use [`push_head!`](#LibGit2.push_head!) and therefore the HEAD commit and all its ancestors. \* `range`: A range of `GitHash`s in the format `oid1..oid2`. `f` will be applied to all commits between the two. \* `by`: The sorting method. The default is not to sort. Other options are to sort by topology (`LibGit2.Consts.SORT_TOPOLOGICAL`), to sort forwards in time (`LibGit2.Consts.SORT_TIME`, most ancient first) or to sort backwards in time (`LibGit2.Consts.SORT_REVERSE`, most recent first). \* `rev`: Whether to reverse the sorted order (for instance, if topological sorting is used).
**Examples**
```
oids = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker
LibGit2.map((oid, repo)->string(oid), walker, by=LibGit2.Consts.SORT_TIME)
end
```
Here, `LibGit2.map` visits each commit using the `GitRevWalker` and finds its `GitHash`.
###
`LibGit2.mirror_callback`Function
Mirror callback function
Function sets `+refs/*:refs/*` refspecs and `mirror` flag for remote reference.
###
`LibGit2.mirror_cb`Function
C function pointer for `mirror_callback`
###
`LibGit2.message`Function
```
message(c::GitCommit, raw::Bool=false)
```
Return the commit message describing the changes made in commit `c`. If `raw` is `false`, return a slightly "cleaned up" message (which has any leading newlines removed). If `raw` is `true`, the message is not stripped of any such newlines.
###
`LibGit2.merge_analysis`Function
```
merge_analysis(repo::GitRepo, anns::Vector{GitAnnotated}) -> analysis, preference
```
Run analysis on the branches pointed to by the annotated branch tips `anns` and determine under what circumstances they can be merged. For instance, if `anns[1]` is simply an ancestor of `ann[2]`, then `merge_analysis` will report that a fast-forward merge is possible.
Return two outputs, `analysis` and `preference`. `analysis` has several possible values: \* `MERGE_ANALYSIS_NONE`: it is not possible to merge the elements of `anns`. \* `MERGE_ANALYSIS_NORMAL`: a regular merge, when HEAD and the commits that the user wishes to merge have all diverged from a common ancestor. In this case the changes have to be resolved and conflicts may occur. \* `MERGE_ANALYSIS_UP_TO_DATE`: all the input commits the user wishes to merge can be reached from HEAD, so no merge needs to be performed. \* `MERGE_ANALYSIS_FASTFORWARD`: the input commit is a descendant of HEAD and so no merge needs to be performed - instead, the user can simply checkout the input commit(s). \* `MERGE_ANALYSIS_UNBORN`: the HEAD of the repository refers to a commit which does not exist. It is not possible to merge, but it may be possible to checkout the input commits. `preference` also has several possible values: \* `MERGE_PREFERENCE_NONE`: the user has no preference. \* `MERGE_PREFERENCE_NO_FASTFORWARD`: do not allow any fast-forward merges. \* `MERGE_PREFERENCE_FASTFORWARD_ONLY`: allow only fast-forward merges and no other type (which may introduce conflicts). `preference` can be controlled through the repository or global git configuration.
###
`LibGit2.name`Function
```
LibGit2.name(ref::GitReference)
```
Return the full name of `ref`.
```
name(rmt::GitRemote)
```
Get the name of a remote repository, for instance `"origin"`. If the remote is anonymous (see [`GitRemoteAnon`](#LibGit2.GitRemoteAnon)) the name will be an empty string `""`.
**Examples**
```
julia> repo_url = "https://github.com/JuliaLang/Example.jl";
julia> repo = LibGit2.clone(cache_repo, "test_directory");
julia> remote = LibGit2.GitRemote(repo, "origin", repo_url);
julia> name(remote)
"origin"
```
```
LibGit2.name(tag::GitTag)
```
The name of `tag` (e.g. `"v0.5"`).
###
`LibGit2.need_update`Function
```
need_update(repo::GitRepo)
```
Equivalent to `git update-index`. Return `true` if `repo` needs updating.
###
`LibGit2.objtype`Function
```
objtype(obj_type::Consts.OBJECT)
```
Return the type corresponding to the enum value.
###
`LibGit2.path`Function
```
LibGit2.path(repo::GitRepo)
```
Return the base file path of the repository `repo`.
* for normal repositories, this will typically be the parent directory of the ".git" directory (note: this may be different than the working directory, see `workdir` for more details).
* for bare repositories, this is the location of the "git" files.
See also [`gitdir`](#LibGit2.gitdir), [`workdir`](#LibGit2.workdir).
###
`LibGit2.peel`Function
```
peel([T,] ref::GitReference)
```
Recursively peel `ref` until an object of type `T` is obtained. If no `T` is provided, then `ref` will be peeled until an object other than a [`GitTag`](#LibGit2.GitTag) is obtained.
* A `GitTag` will be peeled to the object it references.
* A [`GitCommit`](#LibGit2.GitCommit) will be peeled to a [`GitTree`](#LibGit2.GitTree).
Only annotated tags can be peeled to `GitTag` objects. Lightweight tags (the default) are references under `refs/tags/` which point directly to `GitCommit` objects.
```
peel([T,] obj::GitObject)
```
Recursively peel `obj` until an object of type `T` is obtained. If no `T` is provided, then `obj` will be peeled until the type changes.
* A `GitTag` will be peeled to the object it references.
* A `GitCommit` will be peeled to a `GitTree`.
###
`LibGit2.posixpath`Function
```
LibGit2.posixpath(path)
```
Standardise the path string `path` to use POSIX separators.
###
`LibGit2.push`Function
```
push(rmt::GitRemote, refspecs; force::Bool=false, options::PushOptions=PushOptions())
```
Push to the specified `rmt` remote git repository, using `refspecs` to determine which remote branch(es) to push to. The keyword arguments are:
* `force`: if `true`, a force-push will occur, disregarding conflicts.
* `options`: determines the options for the push, e.g. which proxy headers to use. See [`PushOptions`](#LibGit2.PushOptions) for more information.
You can add information about the push refspecs in two other ways: by setting an option in the repository's `GitConfig` (with `push.default` as the key) or by calling [`add_push!`](#LibGit2.add_push!). Otherwise you will need to explicitly specify a push refspec in the call to `push` for it to have any effect, like so: `LibGit2.push(repo, refspecs=["refs/heads/master"])`.
```
push(repo::GitRepo; kwargs...)
```
Pushes updates to an upstream of `repo`.
The keyword arguments are:
* `remote::AbstractString="origin"`: the name of the upstream remote to push to.
* `remoteurl::AbstractString=""`: the URL of `remote`.
* `refspecs=AbstractString[]`: determines properties of the push.
* `force::Bool=false`: determines if the push will be a force push, overwriting the remote branch.
* `credentials=nothing`: provides credentials and/or settings when authenticating against a private `remote`.
* `callbacks=Callbacks()`: user provided callbacks and payloads.
Equivalent to `git push [<remoteurl>|<repo>] [<refspecs>]`.
###
`LibGit2.push!`Method
```
LibGit2.push!(w::GitRevWalker, cid::GitHash)
```
Start the [`GitRevWalker`](#LibGit2.GitRevWalker) `walker` at commit `cid`. This function can be used to apply a function to all commits since a certain year, by passing the first commit of that year as `cid` and then passing the resulting `w` to [`LibGit2.map`](#LibGit2.map).
###
`LibGit2.push_head!`Function
```
LibGit2.push_head!(w::GitRevWalker)
```
Push the HEAD commit and its ancestors onto the [`GitRevWalker`](#LibGit2.GitRevWalker) `w`. This ensures that HEAD and all its ancestor commits will be encountered during the walk.
###
`LibGit2.push_refspecs`Function
```
push_refspecs(rmt::GitRemote) -> Vector{String}
```
Get the *push* refspecs for the specified `rmt`. These refspecs contain information about which branch(es) to push to.
**Examples**
```
julia> remote = LibGit2.get(LibGit2.GitRemote, repo, "upstream");
julia> LibGit2.add_push!(repo, remote, "refs/heads/master");
julia> close(remote);
julia> remote = LibGit2.get(LibGit2.GitRemote, repo, "upstream");
julia> LibGit2.push_refspecs(remote)
String["refs/heads/master"]
```
###
`LibGit2.raw`Function
```
raw(id::GitHash) -> Vector{UInt8}
```
Obtain the raw bytes of the [`GitHash`](#LibGit2.GitHash) as a vector of length 20.
###
`LibGit2.read_tree!`Function
```
LibGit2.read_tree!(idx::GitIndex, tree::GitTree)
LibGit2.read_tree!(idx::GitIndex, treehash::AbstractGitHash)
```
Read the tree `tree` (or the tree pointed to by `treehash` in the repository owned by `idx`) into the index `idx`. The current index contents will be replaced.
###
`LibGit2.rebase!`Function
```
LibGit2.rebase!(repo::GitRepo, upstream::AbstractString="", newbase::AbstractString="")
```
Attempt an automatic merge rebase of the current branch, from `upstream` if provided, or otherwise from the upstream tracking branch. `newbase` is the branch to rebase onto. By default this is `upstream`.
If any conflicts arise which cannot be automatically resolved, the rebase will abort, leaving the repository and working tree in its original state, and the function will throw a `GitError`. This is roughly equivalent to the following command line statement:
```
git rebase --merge [<upstream>]
if [ -d ".git/rebase-merge" ]; then
git rebase --abort
fi
```
###
`LibGit2.ref_list`Function
```
LibGit2.ref_list(repo::GitRepo) -> Vector{String}
```
Get a list of all reference names in the `repo` repository.
###
`LibGit2.reftype`Function
```
LibGit2.reftype(ref::GitReference) -> Cint
```
Return a `Cint` corresponding to the type of `ref`:
* `0` if the reference is invalid
* `1` if the reference is an object id
* `2` if the reference is symbolic
###
`LibGit2.remotes`Function
```
LibGit2.remotes(repo::GitRepo)
```
Return a vector of the names of the remotes of `repo`.
###
`LibGit2.remove!`Function
```
remove!(repo::GitRepo, files::AbstractString...)
remove!(idx::GitIndex, files::AbstractString...)
```
Remove all the files with paths specified by `files` in the index `idx` (or the index of the `repo`).
###
`LibGit2.reset`Function
```
reset(val::Integer, flag::Integer)
```
Unset the bits of `val` indexed by `flag`, returning them to `0`.
###
`LibGit2.reset!`Function
```
reset!(payload, [config]) -> CredentialPayload
```
Reset the `payload` state back to the initial values so that it can be used again within the credential callback. If a `config` is provided the configuration will also be updated.
Updates some entries, determined by the `pathspecs`, in the index from the target commit tree.
Sets the current head to the specified commit oid and optionally resets the index and working tree to match.
git reset [<committish>] [–] <pathspecs>...
```
reset!(repo::GitRepo, id::GitHash, mode::Cint=Consts.RESET_MIXED)
```
Reset the repository `repo` to its state at `id`, using one of three modes set by `mode`:
1. `Consts.RESET_SOFT` - move HEAD to `id`.
2. `Consts.RESET_MIXED` - default, move HEAD to `id` and reset the index to `id`.
3. `Consts.RESET_HARD` - move HEAD to `id`, reset the index to `id`, and discard all working changes.
**Examples**
```
# fetch changes
LibGit2.fetch(repo)
isfile(joinpath(repo_path, our_file)) # will be false
# fastforward merge the changes
LibGit2.merge!(repo, fastforward=true)
# because there was not any file locally, but there is
# a file remotely, we need to reset the branch
head_oid = LibGit2.head_oid(repo)
new_head = LibGit2.reset!(repo, head_oid, LibGit2.Consts.RESET_HARD)
```
In this example, the remote which is being fetched from *does* have a file called `our_file` in its index, which is why we must reset.
Equivalent to `git reset [--soft | --mixed | --hard] <id>`.
**Examples**
```
repo = LibGit2.GitRepo(repo_path)
head_oid = LibGit2.head_oid(repo)
open(joinpath(repo_path, "file1"), "w") do f
write(f, "111
")
end
LibGit2.add!(repo, "file1")
mode = LibGit2.Consts.RESET_HARD
# will discard the changes to file1
# and unstage it
new_head = LibGit2.reset!(repo, head_oid, mode)
```
###
`LibGit2.restore`Function
```
restore(s::State, repo::GitRepo)
```
Return a repository `repo` to a previous `State` `s`, for example the HEAD of a branch before a merge attempt. `s` can be generated using the [`snapshot`](#LibGit2.snapshot) function.
###
`LibGit2.revcount`Function
```
LibGit2.revcount(repo::GitRepo, commit1::AbstractString, commit2::AbstractString)
```
List the number of revisions between `commit1` and `commit2` (committish OIDs in string form). Since `commit1` and `commit2` may be on different branches, `revcount` performs a "left-right" revision list (and count), returning a tuple of `Int`s - the number of left and right commits, respectively. A left (or right) commit refers to which side of a symmetric difference in a tree the commit is reachable from.
Equivalent to `git rev-list --left-right --count <commit1> <commit2>`.
**Examples**
```
repo = LibGit2.GitRepo(repo_path)
repo_file = open(joinpath(repo_path, test_file), "a")
println(repo_file, "hello world")
flush(repo_file)
LibGit2.add!(repo, test_file)
commit_oid1 = LibGit2.commit(repo, "commit 1")
println(repo_file, "hello world again")
flush(repo_file)
LibGit2.add!(repo, test_file)
commit_oid2 = LibGit2.commit(repo, "commit 2")
LibGit2.revcount(repo, string(commit_oid1), string(commit_oid2))
```
This will return `(-1, 0)`.
###
`LibGit2.set_remote_url`Function
```
set_remote_url(repo::GitRepo, remote_name, url)
set_remote_url(repo::String, remote_name, url)
```
Set both the fetch and push `url` for `remote_name` for the [`GitRepo`](#LibGit2.GitRepo) or the git repository located at `path`. Typically git repos use `"origin"` as the remote name.
**Examples**
```
repo_path = joinpath(tempdir(), "Example")
repo = LibGit2.init(repo_path)
LibGit2.set_remote_url(repo, "upstream", "https://github.com/JuliaLang/Example.jl")
LibGit2.set_remote_url(repo_path, "upstream2", "https://github.com/JuliaLang/Example2.jl")
```
###
`LibGit2.shortname`Function
```
LibGit2.shortname(ref::GitReference)
```
Return a shortened version of the name of `ref` that's "human-readable".
```
julia> repo = LibGit2.GitRepo(path_to_repo);
julia> branch_ref = LibGit2.head(repo);
julia> LibGit2.name(branch_ref)
"refs/heads/master"
julia> LibGit2.shortname(branch_ref)
"master"
```
###
`LibGit2.snapshot`Function
```
snapshot(repo::GitRepo) -> State
```
Take a snapshot of the current state of the repository `repo`, storing the current HEAD, index, and any uncommitted work. The output `State` can be used later during a call to [`restore`](#LibGit2.restore) to return the repository to the snapshotted state.
###
`LibGit2.split_cfg_entry`Function
```
LibGit2.split_cfg_entry(ce::LibGit2.ConfigEntry) -> Tuple{String,String,String,String}
```
Break the `ConfigEntry` up to the following pieces: section, subsection, name, and value.
**Examples**
Given the git configuration file containing:
```
[credential "https://example.com"]
username = me
```
The `ConfigEntry` would look like the following:
```
julia> entry
ConfigEntry("credential.https://example.com.username", "me")
julia> LibGit2.split_cfg_entry(entry)
("credential", "https://example.com", "username", "me")
```
Refer to the [git config syntax documentation](https://git-scm.com/docs/git-config#_syntax) for more details.
###
`LibGit2.status`Function
```
LibGit2.status(repo::GitRepo, path::String) -> Union{Cuint, Cvoid}
```
Lookup the status of the file at `path` in the git repository `repo`. For instance, this can be used to check if the file at `path` has been modified and needs to be staged and committed.
###
`LibGit2.stage`Function
```
stage(ie::IndexEntry) -> Cint
```
Get the stage number of `ie`. The stage number `0` represents the current state of the working tree, but other numbers can be used in the case of a merge conflict. In such a case, the various stage numbers on an `IndexEntry` describe which side(s) of the conflict the current state of the file belongs to. Stage `0` is the state before the attempted merge, stage `1` is the changes which have been made locally, stages `2` and larger are for changes from other branches (for instance, in the case of a multi-branch "octopus" merge, stages `2`, `3`, and `4` might be used).
###
`LibGit2.tag_create`Function
```
LibGit2.tag_create(repo::GitRepo, tag::AbstractString, commit; kwargs...)
```
Create a new git tag `tag` (e.g. `"v0.5"`) in the repository `repo`, at the commit `commit`.
The keyword arguments are:
* `msg::AbstractString=""`: the message for the tag.
* `force::Bool=false`: if `true`, existing references will be overwritten.
* `sig::Signature=Signature(repo)`: the tagger's signature.
###
`LibGit2.tag_delete`Function
```
LibGit2.tag_delete(repo::GitRepo, tag::AbstractString)
```
Remove the git tag `tag` from the repository `repo`.
###
`LibGit2.tag_list`Function
```
LibGit2.tag_list(repo::GitRepo) -> Vector{String}
```
Get a list of all tags in the git repository `repo`.
###
`LibGit2.target`Function
```
LibGit2.target(tag::GitTag)
```
The `GitHash` of the target object of `tag`.
###
`LibGit2.toggle`Function
```
toggle(val::Integer, flag::Integer)
```
Flip the bits of `val` indexed by `flag`, so that if a bit is `0` it will be `1` after the toggle, and vice-versa.
###
`LibGit2.transact`Function
```
transact(f::Function, repo::GitRepo)
```
Apply function `f` to the git repository `repo`, taking a [`snapshot`](#LibGit2.snapshot) before applying `f`. If an error occurs within `f`, `repo` will be returned to its snapshot state using [`restore`](#LibGit2.restore). The error which occurred will be rethrown, but the state of `repo` will not be corrupted.
###
`LibGit2.treewalk`Function
```
treewalk(f, tree::GitTree, post::Bool=false)
```
Traverse the entries in `tree` and its subtrees in post or pre order. Preorder means beginning at the root and then traversing the leftmost subtree (and recursively on down through that subtree's leftmost subtrees) and moving right through the subtrees. Postorder means beginning at the bottom of the leftmost subtree, traversing upwards through it, then traversing the next right subtree (again beginning at the bottom) and finally visiting the tree root last of all.
The function parameter `f` should have following signature:
```
(String, GitTreeEntry) -> Cint
```
A negative value returned from `f` stops the tree walk. A positive value means that the entry will be skipped if `post` is `false`.
###
`LibGit2.upstream`Function
```
upstream(ref::GitReference) -> Union{GitReference, Nothing}
```
Determine if the branch containing `ref` has a specified upstream branch.
Return either a `GitReference` to the upstream branch if it exists, or [`nothing`](../../base/constants/index#Core.nothing) if the requested branch does not have an upstream counterpart.
###
`LibGit2.update!`Function
```
update!(repo::GitRepo, files::AbstractString...)
update!(idx::GitIndex, files::AbstractString...)
```
Update all the files with paths specified by `files` in the index `idx` (or the index of the `repo`). Match the state of each file in the index with the current state on disk, removing it if it has been removed on disk, or updating its entry in the object database.
###
`LibGit2.url`Function
```
url(rmt::GitRemote)
```
Get the fetch URL of a remote git repository.
**Examples**
```
julia> repo_url = "https://github.com/JuliaLang/Example.jl";
julia> repo = LibGit2.init(mktempdir());
julia> remote = LibGit2.GitRemote(repo, "origin", repo_url);
julia> LibGit2.url(remote)
"https://github.com/JuliaLang/Example.jl"
```
###
`LibGit2.version`Function
```
version() -> VersionNumber
```
Return the version of libgit2 in use, as a [`VersionNumber`](../../manual/strings/index#man-version-number-literals).
###
`LibGit2.with`Function
```
with(f::Function, obj)
```
Resource management helper function. Applies `f` to `obj`, making sure to call `close` on `obj` after `f` successfully returns or throws an error. Ensures that allocated git resources are finalized as soon as they are no longer needed.
###
`LibGit2.with_warn`Function
```
with_warn(f::Function, ::Type{T}, args...)
```
Resource management helper function. Apply `f` to `args`, first constructing an instance of type `T` from `args`. Makes sure to call `close` on the resulting object after `f` successfully returns or throws an error. Ensures that allocated git resources are finalized as soon as they are no longer needed. If an error is thrown by `f`, a warning is shown containing the error.
###
`LibGit2.workdir`Function
```
LibGit2.workdir(repo::GitRepo)
```
Return the location of the working directory of `repo`. This will throw an error for bare repositories.
This will typically be the parent directory of `gitdir(repo)`, but can be different in some cases: e.g. if either the `core.worktree` configuration variable or the `GIT_WORK_TREE` environment variable is set.
See also [`gitdir`](#LibGit2.gitdir), [`path`](#LibGit2.path).
###
`LibGit2.GitObject`Method
```
(::Type{T})(te::GitTreeEntry) where T<:GitObject
```
Get the git object to which `te` refers and return it as its actual type (the type [`entrytype`](#LibGit2.entrytype) would show), for instance a `GitBlob` or `GitTag`.
**Examples**
```
tree = LibGit2.GitTree(repo, "HEAD^{tree}")
tree_entry = tree[1]
blob = LibGit2.GitBlob(tree_entry)
```
###
`LibGit2.UserPasswordCredential`Type
Credential that support only `user` and `password` parameters
###
`LibGit2.SSHCredential`Type
SSH credential type
###
`LibGit2.isfilled`Function
```
isfilled(cred::AbstractCredential) -> Bool
```
Verifies that a credential is ready for use in authentication.
###
`LibGit2.CachedCredentials`Type
Caches credential information for re-use
###
`LibGit2.CredentialPayload`Type
```
LibGit2.CredentialPayload
```
Retains the state between multiple calls to the credential callback for the same URL. A `CredentialPayload` instance is expected to be `reset!` whenever it will be used with a different URL.
###
`LibGit2.approve`Function
```
approve(payload::CredentialPayload; shred::Bool=true) -> Nothing
```
Store the `payload` credential for re-use in a future authentication. Should only be called when authentication was successful.
The `shred` keyword controls whether sensitive information in the payload credential field should be destroyed. Should only be set to `false` during testing.
###
`LibGit2.reject`Function
```
reject(payload::CredentialPayload; shred::Bool=true) -> Nothing
```
Discard the `payload` credential from begin re-used in future authentication. Should only be called when authentication was unsuccessful.
The `shred` keyword controls whether sensitive information in the payload credential field should be destroyed. Should only be set to `false` during testing.
| programming_docs |
julia Random Numbers Random Numbers
==============
Random number generation in Julia uses the [Xoshiro256++](https://prng.di.unimi.it/) algorithm by default, with per-`Task` state. Other RNG types can be plugged in by inheriting the `AbstractRNG` type; they can then be used to obtain multiple streams of random numbers.
The PRNGs (pseudorandom number generators) exported by the `Random` package are:
* `TaskLocalRNG`: a token that represents use of the currently active Task-local stream, deterministically seeded from the parent task, or by `RandomDevice` (with system randomness) at program start
* `Xoshiro`: generates a high-quality stream of random numbers with a small state vector and high performance using the Xoshiro256++ algorithm
* `RandomDevice`: for OS-provided entropy. This may be used for cryptographically secure random numbers (CS(P)RNG).
* `MersenneTwister`: an alternate high-quality PRNG which was the default in older versions of Julia, and is also quite fast, but requires much more space to store the state vector and generate a random sequence.
Most functions related to random generation accept an optional `AbstractRNG` object as first argument. Some also accept dimension specifications `dims...` (which can also be given as a tuple) to generate arrays of random values. In a multi-threaded program, you should generally use different RNG objects from different threads or tasks in order to be thread-safe. However, the default RNG is thread-safe as of Julia 1.3 (using a per-thread RNG up to version 1.6, and per-task thereafter).
The provided RNGs can generate uniform random numbers of the following types: [`Float16`](../../base/numbers/index#Core.Float16), [`Float32`](../../base/numbers/index#Core.Float32), [`Float64`](../../base/numbers/index#Core.Float64), [`BigFloat`](../../base/numbers/index#Base.MPFR.BigFloat), [`Bool`](../../base/numbers/index#Core.Bool), [`Int8`](../../base/numbers/index#Core.Int8), [`UInt8`](../../base/numbers/index#Core.UInt8), [`Int16`](../../base/numbers/index#Core.Int16), [`UInt16`](../../base/numbers/index#Core.UInt16), [`Int32`](../../base/numbers/index#Core.Int32), [`UInt32`](../../base/numbers/index#Core.UInt32), [`Int64`](../../base/numbers/index#Core.Int64), [`UInt64`](../../base/numbers/index#Core.UInt64), [`Int128`](../../base/numbers/index#Core.Int128), [`UInt128`](../../base/numbers/index#Core.UInt128), [`BigInt`](../../base/numbers/index#Base.GMP.BigInt) (or complex numbers of those types). Random floating point numbers are generated uniformly in $[0, 1)$. As `BigInt` represents unbounded integers, the interval must be specified (e.g. `rand(big.(1:6))`).
Additionally, normal and exponential distributions are implemented for some `AbstractFloat` and `Complex` types, see [`randn`](#Base.randn) and [`randexp`](#Random.randexp) for details.
Because the precise way in which random numbers are generated is considered an implementation detail, bug fixes and speed improvements may change the stream of numbers that are generated after a version change. Relying on a specific seed or generated stream of numbers during unit testing is thus discouraged - consider testing properties of the methods in question instead.
[Random numbers module](#Random-numbers-module)
------------------------------------------------
###
`Random.Random`Module
```
Random
```
Support for generating random numbers. Provides [`rand`](#Base.rand), [`randn`](#Base.randn), [`AbstractRNG`](#Random.AbstractRNG), [`MersenneTwister`](#Random.MersenneTwister), and [`RandomDevice`](#Random.RandomDevice).
[Random generation functions](#Random-generation-functions)
------------------------------------------------------------
###
`Base.rand`Function
```
rand([rng=GLOBAL_RNG], [S], [dims...])
```
Pick a random element or array of random elements from the set of values specified by `S`; `S` can be
* an indexable collection (for example `1:9` or `('x', "y", :z)`),
* an `AbstractDict` or `AbstractSet` object,
* a string (considered as a collection of characters), or
* a type: the set of values to pick from is then equivalent to `typemin(S):typemax(S)` for integers (this is not applicable to [`BigInt`](../../base/numbers/index#Base.GMP.BigInt)), to $[0, 1)$ for floating point numbers and to $[0, 1)+i[0, 1)$ for complex floating point numbers;
`S` defaults to [`Float64`](../../base/numbers/index#Core.Float64). When only one argument is passed besides the optional `rng` and is a `Tuple`, it is interpreted as a collection of values (`S`) and not as `dims`.
Support for `S` as a tuple requires at least Julia 1.1.
**Examples**
```
julia> rand(Int, 2)
2-element Array{Int64,1}:
1339893410598768192
1575814717733606317
julia> using Random
julia> rand(MersenneTwister(0), Dict(1=>2, 3=>4))
1=>2
julia> rand((2, 3))
3
julia> rand(Float64, (2, 3))
2×3 Array{Float64,2}:
0.999717 0.0143835 0.540787
0.696556 0.783855 0.938235
```
The complexity of `rand(rng, s::Union{AbstractDict,AbstractSet})` is linear in the length of `s`, unless an optimized method with constant complexity is available, which is the case for `Dict`, `Set` and dense `BitSet`s. For more than a few calls, use `rand(rng, collect(s))` instead, or either `rand(rng, Dict(s))` or `rand(rng, Set(s))` as appropriate.
###
`Random.rand!`Function
```
rand!([rng=GLOBAL_RNG], A, [S=eltype(A)])
```
Populate the array `A` with random values. If `S` is specified (`S` can be a type or a collection, cf. [`rand`](#Base.rand) for details), the values are picked randomly from `S`. This is equivalent to `copyto!(A, rand(rng, S, size(A)))` but without allocating a new array.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> rand!(rng, zeros(5))
5-element Vector{Float64}:
0.5908446386657102
0.7667970365022592
0.5662374165061859
0.4600853424625171
0.7940257103317943
```
###
`Random.bitrand`Function
```
bitrand([rng=GLOBAL_RNG], [dims...])
```
Generate a `BitArray` of random boolean values.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> bitrand(rng, 10)
10-element BitVector:
0
0
0
0
1
0
0
0
1
1
```
###
`Base.randn`Function
```
randn([rng=GLOBAL_RNG], [T=Float64], [dims...])
```
Generate a normally-distributed random number of type `T` with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers. The `Base` module currently provides an implementation for the types [`Float16`](../../base/numbers/index#Core.Float16), [`Float32`](../../base/numbers/index#Core.Float32), and [`Float64`](../../base/numbers/index#Core.Float64) (the default), and their [`Complex`](../../base/numbers/index#Base.Complex) counterparts. When the type argument is complex, the values are drawn from the circularly symmetric complex normal distribution of variance 1 (corresponding to real and imaginary part having independent normal distribution with mean zero and variance `1/2`).
**Examples**
```
julia> using Random
julia> rng = MersenneTwister(1234);
julia> randn(rng, ComplexF64)
0.6133070881429037 - 0.6376291670853887im
julia> randn(rng, ComplexF32, (2, 3))
2×3 Matrix{ComplexF32}:
-0.349649-0.638457im 0.376756-0.192146im -0.396334-0.0136413im
0.611224+1.56403im 0.355204-0.365563im 0.0905552+1.31012im
```
###
`Random.randn!`Function
```
randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A
```
Fill the array `A` with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the [`rand`](#Base.rand) function.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> randn!(rng, zeros(5))
5-element Vector{Float64}:
0.8673472019512456
-0.9017438158568171
-0.4944787535042339
-0.9029142938652416
0.8644013132535154
```
###
`Random.randexp`Function
```
randexp([rng=GLOBAL_RNG], [T=Float64], [dims...])
```
Generate a random number of type `T` according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. The `Base` module currently provides an implementation for the types [`Float16`](../../base/numbers/index#Core.Float16), [`Float32`](../../base/numbers/index#Core.Float32), and [`Float64`](../../base/numbers/index#Core.Float64) (the default).
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> randexp(rng, Float32)
2.4835055f0
julia> randexp(rng, 3, 3)
3×3 Matrix{Float64}:
1.5167 1.30652 0.344435
0.604436 2.78029 0.418516
0.695867 0.693292 0.643644
```
###
`Random.randexp!`Function
```
randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A
```
Fill the array `A` with random numbers following the exponential distribution (with scale 1).
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> randexp!(rng, zeros(5))
5-element Vector{Float64}:
2.4835053723904896
1.516703605376473
0.6044364871025417
0.6958665886385867
1.3065196315496677
```
###
`Random.randstring`Function
```
randstring([rng=GLOBAL_RNG], [chars], [len=8])
```
Create a random string of length `len`, consisting of characters from `chars`, which defaults to the set of upper- and lower-case letters and the digits 0-9. The optional `rng` argument specifies a random number generator, see [Random Numbers](#Random-Numbers).
**Examples**
```
julia> Random.seed!(3); randstring()
"Lxz5hUwn"
julia> randstring(MersenneTwister(3), 'a':'z', 6)
"ocucay"
julia> randstring("ACGT")
"TGCTCCTC"
```
`chars` can be any collection of characters, of type `Char` or `UInt8` (more efficient), provided [`rand`](#Base.rand) can randomly pick characters from it.
[Subsequences, permutations and shuffling](#Subsequences,-permutations-and-shuffling)
--------------------------------------------------------------------------------------
###
`Random.randsubseq`Function
```
randsubseq([rng=GLOBAL_RNG,] A, p) -> Vector
```
Return a vector consisting of a random subsequence of the given array `A`, where each element of `A` is included (in order) with independent probability `p`. (Complexity is linear in `p*length(A)`, so this function is efficient even if `p` is small and `A` is large.) Technically, this process is known as "Bernoulli sampling" of `A`.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> randsubseq(rng, 1:8, 0.3)
2-element Vector{Int64}:
7
8
```
###
`Random.randsubseq!`Function
```
randsubseq!([rng=GLOBAL_RNG,] S, A, p)
```
Like [`randsubseq`](#Random.randsubseq), but the results are stored in `S` (which is resized as needed).
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> S = Int64[];
julia> randsubseq!(rng, S, 1:8, 0.3)
2-element Vector{Int64}:
7
8
julia> S
2-element Vector{Int64}:
7
8
```
###
`Random.randperm`Function
```
randperm([rng=GLOBAL_RNG,] n::Integer)
```
Construct a random permutation of length `n`. The optional `rng` argument specifies a random number generator (see [Random Numbers](#Random-Numbers)). The element type of the result is the same as the type of `n`.
To randomly permute an arbitrary vector, see [`shuffle`](#Random.shuffle) or [`shuffle!`](#Random.shuffle!).
In Julia 1.1 `randperm` returns a vector `v` with `eltype(v) == typeof(n)` while in Julia 1.0 `eltype(v) == Int`.
**Examples**
```
julia> randperm(MersenneTwister(1234), 4)
4-element Vector{Int64}:
2
1
4
3
```
###
`Random.randperm!`Function
```
randperm!([rng=GLOBAL_RNG,] A::Array{<:Integer})
```
Construct in `A` a random permutation of length `length(A)`. The optional `rng` argument specifies a random number generator (see [Random Numbers](#Random-Numbers)). To randomly permute an arbitrary vector, see [`shuffle`](#Random.shuffle) or [`shuffle!`](#Random.shuffle!).
**Examples**
```
julia> randperm!(MersenneTwister(1234), Vector{Int}(undef, 4))
4-element Vector{Int64}:
2
1
4
3
```
###
`Random.randcycle`Function
```
randcycle([rng=GLOBAL_RNG,] n::Integer)
```
Construct a random cyclic permutation of length `n`. The optional `rng` argument specifies a random number generator, see [Random Numbers](#Random-Numbers). The element type of the result is the same as the type of `n`.
In Julia 1.1 `randcycle` returns a vector `v` with `eltype(v) == typeof(n)` while in Julia 1.0 `eltype(v) == Int`.
**Examples**
```
julia> randcycle(MersenneTwister(1234), 6)
6-element Vector{Int64}:
3
5
4
6
1
2
```
###
`Random.randcycle!`Function
```
randcycle!([rng=GLOBAL_RNG,] A::Array{<:Integer})
```
Construct in `A` a random cyclic permutation of length `length(A)`. The optional `rng` argument specifies a random number generator, see [Random Numbers](#Random-Numbers).
**Examples**
```
julia> randcycle!(MersenneTwister(1234), Vector{Int}(undef, 6))
6-element Vector{Int64}:
3
5
4
6
1
2
```
###
`Random.shuffle`Function
```
shuffle([rng=GLOBAL_RNG,] v::AbstractArray)
```
Return a randomly permuted copy of `v`. The optional `rng` argument specifies a random number generator (see [Random Numbers](#Random-Numbers)). To permute `v` in-place, see [`shuffle!`](#Random.shuffle!). To obtain randomly permuted indices, see [`randperm`](#Random.randperm).
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> shuffle(rng, Vector(1:10))
10-element Vector{Int64}:
6
1
10
2
3
9
5
7
4
8
```
###
`Random.shuffle!`Function
```
shuffle!([rng=GLOBAL_RNG,] v::AbstractArray)
```
In-place version of [`shuffle`](#Random.shuffle): randomly permute `v` in-place, optionally supplying the random-number generator `rng`.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> shuffle!(rng, Vector(1:16))
16-element Vector{Int64}:
2
15
5
14
1
9
10
6
11
3
16
7
4
12
8
13
```
[Generators (creation and seeding)](#Generators-(creation-and-seeding))
------------------------------------------------------------------------
###
`Random.seed!`Function
```
seed!([rng=GLOBAL_RNG], seed) -> rng
seed!([rng=GLOBAL_RNG]) -> rng
```
Reseed the random number generator: `rng` will give a reproducible sequence of numbers if and only if a `seed` is provided. Some RNGs don't accept a seed, like `RandomDevice`. After the call to `seed!`, `rng` is equivalent to a newly created object initialized with the same seed.
If `rng` is not specified, it defaults to seeding the state of the shared task-local generator.
**Examples**
```
julia> Random.seed!(1234);
julia> x1 = rand(2)
2-element Array{Float64,1}:
0.590845
0.766797
julia> Random.seed!(1234);
julia> x2 = rand(2)
2-element Array{Float64,1}:
0.590845
0.766797
julia> x1 == x2
true
julia> rng = MersenneTwister(1234); rand(rng, 2) == x1
true
julia> MersenneTwister(1) == Random.seed!(rng, 1)
true
julia> rand(Random.seed!(rng), Bool) # not reproducible
true
julia> rand(Random.seed!(rng), Bool)
false
julia> rand(MersenneTwister(), Bool) # not reproducible either
true
```
###
`Random.AbstractRNG`Type
```
AbstractRNG
```
Supertype for random number generators such as [`MersenneTwister`](#Random.MersenneTwister) and [`RandomDevice`](#Random.RandomDevice).
###
`Random.TaskLocalRNG`Type
```
TaskLocalRNG
```
The `TaskLocalRNG` has state that is local to its task, not its thread. It is seeded upon task creation, from the state of its parent task. Therefore, task creation is an event that changes the parent's RNG state.
As an upside, the `TaskLocalRNG` is pretty fast, and permits reproducible multithreaded simulations (barring race conditions), independent of scheduler decisions. As long as the number of threads is not used to make decisions on task creation, simulation results are also independent of the number of available threads / CPUs. The random stream should not depend on hardware specifics, up to endianness and possibly word size.
Using or seeding the RNG of any other task than the one returned by `current_task()` is undefined behavior: it will work most of the time, and may sometimes fail silently.
###
`Random.Xoshiro`Type
```
Xoshiro(seed)
Xoshiro()
```
Xoshiro256++ is a fast pseudorandom number generator described by David Blackman and Sebastiano Vigna in "Scrambled Linear Pseudorandom Number Generators", ACM Trans. Math. Softw., 2021. Reference implementation is available at http://prng.di.unimi.it
Apart from the high speed, Xoshiro has a small memory footprint, making it suitable for applications where many different random states need to be held for long time.
Julia's Xoshiro implementation has a bulk-generation mode; this seeds new virtual PRNGs from the parent, and uses SIMD to generate in parallel (i.e. the bulk stream consists of multiple interleaved xoshiro instances). The virtual PRNGs are discarded once the bulk request has been serviced (and should cause no heap allocations).
**Examples**
```
julia> using Random
julia> rng = Xoshiro(1234);
julia> x1 = rand(rng, 2)
2-element Vector{Float64}:
0.32597672886359486
0.5490511363155669
julia> rng = Xoshiro(1234);
julia> x2 = rand(rng, 2)
2-element Vector{Float64}:
0.32597672886359486
0.5490511363155669
julia> x1 == x2
true
```
###
`Random.MersenneTwister`Type
```
MersenneTwister(seed)
MersenneTwister()
```
Create a `MersenneTwister` RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers. The `seed` may be a non-negative integer or a vector of `UInt32` integers. If no seed is provided, a randomly generated one is created (using entropy from the system). See the [`seed!`](#Random.seed!) function for reseeding an already existing `MersenneTwister` object.
**Examples**
```
julia> rng = MersenneTwister(1234);
julia> x1 = rand(rng, 2)
2-element Vector{Float64}:
0.5908446386657102
0.7667970365022592
julia> rng = MersenneTwister(1234);
julia> x2 = rand(rng, 2)
2-element Vector{Float64}:
0.5908446386657102
0.7667970365022592
julia> x1 == x2
true
```
###
`Random.RandomDevice`Type
```
RandomDevice()
```
Create a `RandomDevice` RNG object. Two such objects will always generate different streams of random numbers. The entropy is obtained from the operating system.
[Hooking into the `Random` API](#Hooking-into-the-Random-API)
--------------------------------------------------------------
There are two mostly orthogonal ways to extend `Random` functionalities:
1. generating random values of custom types
2. creating new generators
The API for 1) is quite functional, but is relatively recent so it may still have to evolve in subsequent releases of the `Random` module. For example, it's typically sufficient to implement one `rand` method in order to have all other usual methods work automatically.
The API for 2) is still rudimentary, and may require more work than strictly necessary from the implementor, in order to support usual types of generated values.
###
[Generating random values of custom types](#Generating-random-values-of-custom-types)
Generating random values for some distributions may involve various trade-offs. *Pre-computed* values, such as an [alias table](https://en.wikipedia.org/wiki/Alias_method) for discrete distributions, or [“squeezing” functions](https://en.wikipedia.org/wiki/Rejection_sampling) for univariate distributions, can speed up sampling considerably. How much information should be pre-computed can depend on the number of values we plan to draw from a distribution. Also, some random number generators can have certain properties that various algorithms may want to exploit.
The `Random` module defines a customizable framework for obtaining random values that can address these issues. Each invocation of `rand` generates a *sampler* which can be customized with the above trade-offs in mind, by adding methods to `Sampler`, which in turn can dispatch on the random number generator, the object that characterizes the distribution, and a suggestion for the number of repetitions. Currently, for the latter, `Val{1}` (for a single sample) and `Val{Inf}` (for an arbitrary number) are used, with `Random.Repetition` an alias for both.
The object returned by `Sampler` is then used to generate the random values. When implementing the random generation interface for a value `X` that can be sampled from, the implementor should define the method
```
rand(rng, sampler)
```
for the particular `sampler` returned by `Sampler(rng, X, repetition)`.
Samplers can be arbitrary values that implement `rand(rng, sampler)`, but for most applications the following predefined samplers may be sufficient:
1. `SamplerType{T}()` can be used for implementing samplers that draw from type `T` (e.g. `rand(Int)`). This is the default returned by `Sampler` for *types*.
2. `SamplerTrivial(self)` is a simple wrapper for `self`, which can be accessed with `[]`. This is the recommended sampler when no pre-computed information is needed (e.g. `rand(1:3)`), and is the default returned by `Sampler` for *values*.
3. `SamplerSimple(self, data)` also contains the additional `data` field, which can be used to store arbitrary pre-computed values, which should be computed in a *custom method* of `Sampler`.
We provide examples for each of these. We assume here that the choice of algorithm is independent of the RNG, so we use `AbstractRNG` in our signatures.
###
`Random.Sampler`Type
```
Sampler(rng, x, repetition = Val(Inf))
```
Return a sampler object that can be used to generate random values from `rng` for `x`.
When `sp = Sampler(rng, x, repetition)`, `rand(rng, sp)` will be used to draw random values, and should be defined accordingly.
`repetition` can be `Val(1)` or `Val(Inf)`, and should be used as a suggestion for deciding the amount of precomputation, if applicable.
[`Random.SamplerType`](#Random.SamplerType) and [`Random.SamplerTrivial`](#Random.SamplerTrivial) are default fallbacks for *types* and *values*, respectively. [`Random.SamplerSimple`](#Random.SamplerSimple) can be used to store pre-computed values without defining extra types for only this purpose.
###
`Random.SamplerType`Type
```
SamplerType{T}()
```
A sampler for types, containing no other information. The default fallback for `Sampler` when called with types.
###
`Random.SamplerTrivial`Type
```
SamplerTrivial(x)
```
Create a sampler that just wraps the given value `x`. This is the default fall-back for values. The `eltype` of this sampler is equal to `eltype(x)`.
The recommended use case is sampling from values without precomputed data.
###
`Random.SamplerSimple`Type
```
SamplerSimple(x, data)
```
Create a sampler that wraps the given value `x` and the `data`. The `eltype` of this sampler is equal to `eltype(x)`.
The recommended use case is sampling from values with precomputed data.
Decoupling pre-computation from actually generating the values is part of the API, and is also available to the user. As an example, assume that `rand(rng, 1:20)` has to be called repeatedly in a loop: the way to take advantage of this decoupling is as follows:
```
rng = MersenneTwister()
sp = Random.Sampler(rng, 1:20) # or Random.Sampler(MersenneTwister, 1:20)
for x in X
n = rand(rng, sp) # similar to n = rand(rng, 1:20)
# use n
end
```
This is the mechanism that is also used in the standard library, e.g. by the default implementation of random array generation (like in `rand(1:20, 10)`).
####
[Generating values from a type](#Generating-values-from-a-type)
Given a type `T`, it's currently assumed that if `rand(T)` is defined, an object of type `T` will be produced. `SamplerType` is the *default sampler for types*. In order to define random generation of values of type `T`, the `rand(rng::AbstractRNG, ::Random.SamplerType{T})` method should be defined, and should return values what `rand(rng, T)` is expected to return.
Let's take the following example: we implement a `Die` type, with a variable number `n` of sides, numbered from `1` to `n`. We want `rand(Die)` to produce a `Die` with a random number of up to 20 sides (and at least 4):
```
struct Die
nsides::Int # number of sides
end
Random.rand(rng::AbstractRNG, ::Random.SamplerType{Die}) = Die(rand(rng, 4:20))
# output
```
Scalar and array methods for `Die` now work as expected:
```
julia> rand(Die)
Die(5)
julia> rand(MersenneTwister(0), Die)
Die(11)
julia> rand(Die, 3)
3-element Vector{Die}:
Die(9)
Die(15)
Die(14)
julia> a = Vector{Die}(undef, 3); rand!(a)
3-element Vector{Die}:
Die(19)
Die(7)
Die(17)
```
####
[A simple sampler without pre-computed data](#A-simple-sampler-without-pre-computed-data)
Here we define a sampler for a collection. If no pre-computed data is required, it can be implemented with a `SamplerTrivial` sampler, which is in fact the *default fallback for values*.
In order to define random generation out of objects of type `S`, the following method should be defined: `rand(rng::AbstractRNG, sp::Random.SamplerTrivial{S})`. Here, `sp` simply wraps an object of type `S`, which can be accessed via `sp[]`. Continuing the `Die` example, we want now to define `rand(d::Die)` to produce an `Int` corresponding to one of `d`'s sides:
```
julia> Random.rand(rng::AbstractRNG, d::Random.SamplerTrivial{Die}) = rand(rng, 1:d[].nsides);
julia> rand(Die(4))
1
julia> rand(Die(4), 3)
3-element Vector{Any}:
2
3
3
```
Given a collection type `S`, it's currently assumed that if `rand(::S)` is defined, an object of type `eltype(S)` will be produced. In the last example, a `Vector{Any}` is produced; the reason is that `eltype(Die) == Any`. The remedy is to define `Base.eltype(::Type{Die}) = Int`.
####
[Generating values for an `AbstractFloat` type](#Generating-values-for-an-AbstractFloat-type)
`AbstractFloat` types are special-cased, because by default random values are not produced in the whole type domain, but rather in `[0,1)`. The following method should be implemented for `T <: AbstractFloat`: `Random.rand(::AbstractRNG, ::Random.SamplerTrivial{Random.CloseOpen01{T}})`
####
[An optimized sampler with pre-computed data](#An-optimized-sampler-with-pre-computed-data)
Consider a discrete distribution, where numbers `1:n` are drawn with given probabilities that sum to one. When many values are needed from this distribution, the fastest method is using an [alias table](https://en.wikipedia.org/wiki/Alias_method). We don't provide the algorithm for building such a table here, but suppose it is available in `make_alias_table(probabilities)` instead, and `draw_number(rng, alias_table)` can be used to draw a random number from it.
Suppose that the distribution is described by
```
struct DiscreteDistribution{V <: AbstractVector}
probabilities::V
end
```
and that we *always* want to build an alias table, regardless of the number of values needed (we learn how to customize this below). The methods
```
Random.eltype(::Type{<:DiscreteDistribution}) = Int
function Random.Sampler(::Type{<:AbstractRNG}, distribution::DiscreteDistribution, ::Repetition)
SamplerSimple(disribution, make_alias_table(distribution.probabilities))
end
```
should be defined to return a sampler with pre-computed data, then
```
function rand(rng::AbstractRNG, sp::SamplerSimple{<:DiscreteDistribution})
draw_number(rng, sp.data)
end
```
will be used to draw the values.
####
[Custom sampler types](#Custom-sampler-types)
The `SamplerSimple` type is sufficient for most use cases with precomputed data. However, in order to demonstrate how to use custom sampler types, here we implement something similar to `SamplerSimple`.
Going back to our `Die` example: `rand(::Die)` uses random generation from a range, so there is an opportunity for this optimization. We call our custom sampler `SamplerDie`.
```
import Random: Sampler, rand
struct SamplerDie <: Sampler{Int} # generates values of type Int
die::Die
sp::Sampler{Int} # this is an abstract type, so this could be improved
end
Sampler(RNG::Type{<:AbstractRNG}, die::Die, r::Random.Repetition) =
SamplerDie(die, Sampler(RNG, 1:die.nsides, r))
# the `r` parameter will be explained later on
rand(rng::AbstractRNG, sp::SamplerDie) = rand(rng, sp.sp)
```
It's now possible to get a sampler with `sp = Sampler(rng, die)`, and use `sp` instead of `die` in any `rand` call involving `rng`. In the simplistic example above, `die` doesn't need to be stored in `SamplerDie` but this is often the case in practice.
Of course, this pattern is so frequent that the helper type used above, namely `Random.SamplerSimple`, is available, saving us the definition of `SamplerDie`: we could have implemented our decoupling with:
```
Sampler(RNG::Type{<:AbstractRNG}, die::Die, r::Random.Repetition) =
SamplerSimple(die, Sampler(RNG, 1:die.nsides, r))
rand(rng::AbstractRNG, sp::SamplerSimple{Die}) = rand(rng, sp.data)
```
Here, `sp.data` refers to the second parameter in the call to the `SamplerSimple` constructor (in this case equal to `Sampler(rng, 1:die.nsides, r)`), while the `Die` object can be accessed via `sp[]`.
Like `SamplerDie`, any custom sampler must be a subtype of `Sampler{T}` where `T` is the type of the generated values. Note that `SamplerSimple(x, data) isa Sampler{eltype(x)}`, so this constrains what the first argument to `SamplerSimple` can be (it's recommended to use `SamplerSimple` like in the `Die` example, where `x` is simply forwarded while defining a `Sampler` method). Similarly, `SamplerTrivial(x) isa Sampler{eltype(x)}`.
Another helper type is currently available for other cases, `Random.SamplerTag`, but is considered as internal API, and can break at any time without proper deprecations.
####
[Using distinct algorithms for scalar or array generation](#Using-distinct-algorithms-for-scalar-or-array-generation)
In some cases, whether one wants to generate only a handful of values or a large number of values will have an impact on the choice of algorithm. This is handled with the third parameter of the `Sampler` constructor. Let's assume we defined two helper types for `Die`, say `SamplerDie1` which should be used to generate only few random values, and `SamplerDieMany` for many values. We can use those types as follows:
```
Sampler(RNG::Type{<:AbstractRNG}, die::Die, ::Val{1}) = SamplerDie1(...)
Sampler(RNG::Type{<:AbstractRNG}, die::Die, ::Val{Inf}) = SamplerDieMany(...)
```
Of course, `rand` must also be defined on those types (i.e. `rand(::AbstractRNG, ::SamplerDie1)` and `rand(::AbstractRNG, ::SamplerDieMany)`). Note that, as usual, `SamplerTrivial` and `SamplerSimple` can be used if custom types are not necessary.
Note: `Sampler(rng, x)` is simply a shorthand for `Sampler(rng, x, Val(Inf))`, and `Random.Repetition` is an alias for `Union{Val{1}, Val{Inf}}`.
###
[Creating new generators](#Creating-new-generators)
The API is not clearly defined yet, but as a rule of thumb:
1. any `rand` method producing "basic" types (`isbitstype` integer and floating types in `Base`) should be defined for this specific RNG, if they are needed;
2. other documented `rand` methods accepting an `AbstractRNG` should work out of the box, (provided the methods from 1) what are relied on are implemented), but can of course be specialized for this RNG if there is room for optimization;
3. `copy` for pseudo-RNGs should return an independent copy that generates the exact same random sequence as the original from that point when called in the same way. When this is not feasible (e.g. hardware-based RNGs), `copy` must not be implemented.
Concerning 1), a `rand` method may happen to work automatically, but it's not officially supported and may break without warnings in a subsequent release.
To define a new `rand` method for an hypothetical `MyRNG` generator, and a value specification `s` (e.g. `s == Int`, or `s == 1:10`) of type `S==typeof(s)` or `S==Type{s}` if `s` is a type, the same two methods as we saw before must be defined:
1. `Sampler(::Type{MyRNG}, ::S, ::Repetition)`, which returns an object of type say `SamplerS`
2. `rand(rng::MyRNG, sp::SamplerS)`
It can happen that `Sampler(rng::AbstractRNG, ::S, ::Repetition)` is already defined in the `Random` module. It would then be possible to skip step 1) in practice (if one wants to specialize generation for this particular RNG type), but the corresponding `SamplerS` type is considered as internal detail, and may be changed without warning.
####
[Specializing array generation](#Specializing-array-generation)
In some cases, for a given RNG type, generating an array of random values can be more efficient with a specialized method than by merely using the decoupling technique explained before. This is for example the case for `MersenneTwister`, which natively writes random values in an array.
To implement this specialization for `MyRNG` and for a specification `s`, producing elements of type `S`, the following method can be defined: `rand!(rng::MyRNG, a::AbstractArray{S}, ::SamplerS)`, where `SamplerS` is the type of the sampler returned by `Sampler(MyRNG, s, Val(Inf))`. Instead of `AbstractArray`, it's possible to implement the functionality only for a subtype, e.g. `Array{S}`. The non-mutating array method of `rand` will automatically call this specialization internally.
[Reproducibility](#Reproducibility)
====================================
By using an RNG parameter initialized with a given seed, you can reproduce the same pseudorandom number sequence when running your program multiple times. However, a minor release of Julia (e.g. 1.3 to 1.4) *may change* the sequence of pseudorandom numbers generated from a specific seed, in particular if `MersenneTwister` is used. (Even if the sequence produced by a low-level function like [`rand`](#Base.rand) does not change, the output of higher-level functions like [`randsubseq`](#Random.randsubseq) may change due to algorithm updates.) Rationale: guaranteeing that pseudorandom streams never change prohibits many algorithmic improvements.
If you need to guarantee exact reproducibility of random data, it is advisable to simply *save the data* (e.g. as a supplementary attachment in a scientific publication). (You can also, of course, specify a particular Julia version and package manifest, especially if you require bit reproducibility.)
Software tests that rely on *specific* "random" data should also generally either save the data, embed it into the test code, or use third-party packages like [StableRNGs.jl](https://github.com/JuliaRandom/StableRNGs.jl). On the other hand, tests that should pass for *most* random data (e.g. testing `A \ (A*x) ≈ x` for a random matrix `A = randn(n,n)`) can use an RNG with a fixed seed to ensure that simply running the test many times does not encounter a failure due to very improbable data (e.g. an extremely ill-conditioned matrix).
The statistical *distribution* from which random samples are drawn *is* guaranteed to be the same across any minor Julia releases.
| programming_docs |
julia Downloads Downloads
=========
###
`Downloads.download`Function
```
download(url, [ output = tempname() ];
[ method = "GET", ]
[ headers = <none>, ]
[ timeout = <none>, ]
[ progress = <none>, ]
[ verbose = false, ]
[ debug = <none>, ]
[ downloader = <default>, ]
) -> output
url :: AbstractString
output :: Union{AbstractString, AbstractCmd, IO}
method :: AbstractString
headers :: Union{AbstractVector, AbstractDict}
timeout :: Real
progress :: (total::Integer, now::Integer) --> Any
verbose :: Bool
debug :: (type, message) --> Any
downloader :: Downloader
```
Download a file from the given url, saving it to `output` or if not specified, a temporary path. The `output` can also be an `IO` handle, in which case the body of the response is streamed to that handle and the handle is returned. If `output` is a command, the command is run and output is sent to it on stdin.
If the `downloader` keyword argument is provided, it must be a `Downloader` object. Resources and connections will be shared between downloads performed by the same `Downloader` and cleaned up automatically when the object is garbage collected or there have been no downloads performed with it for a grace period. See `Downloader` for more info about configuration and usage.
If the `headers` keyword argument is provided, it must be a vector or dictionary whose elements are all pairs of strings. These pairs are passed as headers when downloading URLs with protocols that supports them, such as HTTP/S.
The `timeout` keyword argument specifies a timeout for the download in seconds, with a resolution of milliseconds. By default no timeout is set, but this can also be explicitly requested by passing a timeout value of `Inf`.
If the `progress` keyword argument is provided, it must be a callback funtion which will be called whenever there are updates about the size and status of the ongoing download. The callback must take two integer arguments: `total` and `now` which are the total size of the download in bytes, and the number of bytes which have been downloaded so far. Note that `total` starts out as zero and remains zero until the server gives an indication of the total size of the download (e.g. with a `Content-Length` header), which may never happen. So a well-behaved progress callback should handle a total size of zero gracefully.
If the `verbose` option is set to true, `libcurl`, which is used to implement the download functionality will print debugging information to `stderr`. If the `debug` option is set to a function accepting two `String` arguments, then the verbose option is ignored and instead the data that would have been printed to `stderr` is passed to the `debug` callback with `type` and `message` arguments. The `type` argument indicates what kind of event has occurred, and is one of: `TEXT`, `HEADER IN`, `HEADER OUT`, `DATA IN`, `DATA OUT`, `SSL DATA IN` or `SSL DATA OUT`. The `message` argument is the description of the debug event.
###
`Downloads.request`Function
```
request(url;
[ input = <none>, ]
[ output = <none>, ]
[ method = input ? "PUT" : output ? "GET" : "HEAD", ]
[ headers = <none>, ]
[ timeout = <none>, ]
[ progress = <none>, ]
[ verbose = false, ]
[ debug = <none>, ]
[ throw = true, ]
[ downloader = <default>, ]
) -> Union{Response, RequestError}
url :: AbstractString
input :: Union{AbstractString, AbstractCmd, IO}
output :: Union{AbstractString, AbstractCmd, IO}
method :: AbstractString
headers :: Union{AbstractVector, AbstractDict}
timeout :: Real
progress :: (dl_total, dl_now, ul_total, ul_now) --> Any
verbose :: Bool
debug :: (type, message) --> Any
throw :: Bool
downloader :: Downloader
```
Make a request to the given url, returning a `Response` object capturing the status, headers and other information about the response. The body of the reponse is written to `output` if specified and discarded otherwise. For HTTP/S requests, if an `input` stream is given, a `PUT` request is made; otherwise if an `output` stream is given, a `GET` request is made; if neither is given a `HEAD` request is made. For other protocols, appropriate default methods are used based on what combination of input and output are requested. The following options differ from the `download` function:
* `input` allows providing a request body; if provided default to `PUT` request
* `progress` is a callback taking four integers for upload and download progress
* `throw` controls whether to throw or return a `RequestError` on request error
Note that unlike `download` which throws an error if the requested URL could not be downloaded (indicated by non-2xx status code), `request` returns a `Response` object no matter what the status code of the response is. If there is an error with getting a response at all, then a `RequestError` is thrown or returned.
###
`Downloads.Response`Type
```
struct Response
proto :: String
url :: String
status :: Int
message :: String
headers :: Vector{Pair{String,String}}
end
```
`Response` is a type capturing the properties of a successful response to a request as an object. It has the following fields:
* `proto`: the protocol that was used to get the response
* `url`: the URL that was ultimately requested after following redirects
* `status`: the status code of the response, indicating success, failure, etc.
* `message`: a textual message describing the nature of the response
* `headers`: any headers that were returned with the response
The meaning and availability of some of these responses depends on the protocol used for the request. For many protocols, including HTTP/S and S/FTP, a 2xx status code indicates a successful response. For responses in protocols that do not support headers, the headers vector will be empty. HTTP/2 does not include a status message, only a status code, so the message will be empty.
###
`Downloads.RequestError`Type
```
struct RequestError <: ErrorException
url :: String
code :: Int
message :: String
response :: Response
end
```
`RequestError` is a type capturing the properties of a failed response to a request as an exception object:
* `url`: the original URL that was requested without any redirects
* `code`: the libcurl error code; `0` if a protocol-only error occurred
* `message`: the libcurl error message indicating what went wrong
* `response`: response object capturing what response info is available
The same `RequestError` type is thrown by `download` if the request was successful but there was a protocol-level error indicated by a status code that is not in the 2xx range, in which case `code` will be zero and the `message` field will be the empty string. The `request` API only throws a `RequestError` if the libcurl error `code` is non-zero, in which case the included `response` object is likely to have a `status` of zero and an empty message. There are, however, situations where a curl-level error is thrown due to a protocol error, in which case both the inner and outer code and message may be of interest.
###
`Downloads.Downloader`Type
```
Downloader(; [ grace::Real = 30 ])
```
`Downloader` objects are used to perform individual `download` operations. Connections, name lookups and other resources are shared within a `Downloader`. These connections and resources are cleaned up after a configurable grace period (default: 30 seconds) since anything was downloaded with it, or when it is garbage collected, whichever comes first. If the grace period is set to zero, all resources will be cleaned up immediately as soon as there are no more ongoing downloads in progress. If the grace period is set to `Inf` then resources are not cleaned up until `Downloader` is garbage collected.
julia Tar Tar
===
###
`Tar.create`Function
```
create([ predicate, ] dir, [ tarball ]; [ skeleton ]) -> tarball
predicate :: String --> Bool
dir :: AbstractString
tarball :: Union{AbstractString, AbstractCmd, IO}
skeleton :: Union{AbstractString, AbstractCmd, IO}
```
Create a tar archive ("tarball") of the directory `dir`. The resulting archive is written to the path `tarball` or if no path is specified, a temporary path is created and returned by the function call. If `tarball` is an IO object then the tarball content is written to that handle instead (the handle is left open).
If a `predicate` function is passed, it is called on each system path that is encountered while recursively searching `dir` and `path` is only included in the tarball if `predicate(path)` is true. If `predicate(path)` returns false for a directory, then the directory is excluded entirely: nothing under that directory will be included in the archive.
If the `skeleton` keyword is passed then the file or IO handle given is used as a "skeleton" to generate the tarball. You create a skeleton file by passing the `skeleton` keyword to the `extract` command. If `create` is called with that skeleton file and the extracted files haven't changed, an identical tarball is recreated. The `skeleton` and `predicate` arguments cannot be used together.
###
`Tar.extract`Function
```
extract(
[ predicate, ] tarball, [ dir ];
[ skeleton = <none>, ]
[ copy_symlinks = <auto>, ]
[ set_permissions = true, ]
) -> dir
predicate :: Header --> Bool
tarball :: Union{AbstractString, AbstractCmd, IO}
dir :: AbstractString
skeleton :: Union{AbstractString, AbstractCmd, IO}
copy_symlinks :: Bool
set_permissions :: Bool
```
Extract a tar archive ("tarball") located at the path `tarball` into the directory `dir`. If `tarball` is an IO object instead of a path, then the archive contents will be read from that IO stream. The archive is extracted to `dir` which must either be an existing empty directory or a non-existent path which can be created as a new directory. If `dir` is not specified, the archive is extracted into a temporary directory which is returned by `extract`.
If a `predicate` function is passed, it is called on each `Header` object that is encountered while extracting `tarball` and the entry is only extracted if the `predicate(hdr)` is true. This can be used to selectively extract only parts of an archive, to skip entries that cause `extract` to throw an error, or to record what is extracted during the extraction process.
Before it is passed to the predicate function, the `Header` object is somewhat modified from the raw header in the tarball: the `path` field is normalized to remove `.` entries and replace multiple consecutive slashes with a single slash. If the entry has type `:hardlink`, the link target path is normalized the same way so that it will match the path of the target entry; the size field is set to the size of the target path (which must be an already-seen file).
If the `skeleton` keyword is passed then a "skeleton" of the extracted tarball is written to the file or IO handle given. This skeleton file can be used to recreate an identical tarball by passing the `skeleton` keyword to the `create` function. The `skeleton` and `predicate` arguments cannot be used together.
If `copy_symlinks` is `true` then instead of extracting symbolic links as such, they will be extracted as copies of what they link to if they are internal to the tarball and if it is possible to do so. Non-internal symlinks, such as a link to `/etc/passwd` will not be copied. Symlinks which are in any way cyclic will also not be copied and will instead be skipped. By default, `extract` will detect whether symlinks can be created in `dir` or not and will automatically copy symlinks if they cannot be created.
If `set_permissions` is `false`, no permissions are set on the extracted files.
###
`Tar.list`Function
```
list(tarball; [ strict = true ]) -> Vector{Header}
list(callback, tarball; [ strict = true ])
callback :: Header, [ <data> ] --> Any
tarball :: Union{AbstractString, AbstractCmd, IO}
strict :: Bool
```
List the contents of a tar archive ("tarball") located at the path `tarball`. If `tarball` is an IO handle, read the tar contents from that stream. Returns a vector of `Header` structs. See [`Header`](#Tar.Header) for details.
If a `callback` is provided then instead of returning a vector of headers, the callback is called on each `Header`. This can be useful if the number of items in the tarball is large or if you want examine items prior to an error in the tarball. If the `callback` function can accept a second argument of either type `Vector{UInt8}` or `Vector{Pair{Symbol, String}}` then it will be called with a representation of the raw header data either as a single byte vector or as a vector of pairs mapping field names to the raw data for that field (if these fields are concatenated together, the result is the raw data of the header).
By default `list` will error if it encounters any tarball contents which the `extract` function would refuse to extract. With `strict=false` it will skip these checks and list all the the contents of the tar file whether `extract` would extract them or not. Beware that malicious tarballs can do all sorts of crafty and unexpected things to try to trick you into doing something bad.
If the `tarball` argument is a skeleton file (see `extract` and `create`) then `list` will detect that from the file header and appropriately list or iterate the headers of the skeleton file.
###
`Tar.rewrite`Function
```
rewrite([ predicate, ], old_tarball, [ new_tarball ]) -> new_tarball
predicate :: Header --> Bool
old_tarball :: Union{AbstractString, AbtractCmd, IO}
new_tarball :: Union{AbstractString, AbtractCmd, IO}
```
Rewrite `old_tarball` to the standard format that `create` generates, while also checking that it doesn't contain anything that would cause `extract` to raise an error. This is functionally equivalent to doing
```
Tar.create(Tar.extract(predicate, old_tarball), new_tarball)
```
However, it never extracts anything to disk and instead uses the `seek` function to navigate the old tarball's data. If no `new_tarball` argument is passed, the new tarball is written to a temporary file whose path is returned.
If a `predicate` function is passed, it is called on each `Header` object that is encountered while extracting `old_tarball` and the entry is skipped unless `predicate(hdr)` is true. This can be used to selectively rewrite only parts of an archive, to skip entries that would cause `extract` to throw an error, or to record what content is encountered during the rewrite process.
Before it is passed to the predicate function, the `Header` object is somewhat modified from the raw header in the tarball: the `path` field is normalized to remove `.` entries and replace multiple consecutive slashes with a single slash. If the entry has type `:hardlink`, the link target path is normalized the same way so that it will match the path of the target entry; the size field is set to the size of the target path (which must be an already-seen file).
###
`Tar.tree_hash`Function
```
tree_hash([ predicate, ] tarball;
[ algorithm = "git-sha1", ]
[ skip_empty = false ]) -> hash::String
predicate :: Header --> Bool
tarball :: Union{AbstractString, AbstractCmd, IO}
algorithm :: AbstractString
skip_empty :: Bool
```
Compute a tree hash value for the file tree that the tarball contains. By default, this uses git's tree hashing algorithm with the SHA1 secure hash function (like current versions of git). This means that for any tarball whose file tree git can represent—i.e. one with only files, symlinks and non-empty directories—the hash value computed by this function will be the same as the hash value git would compute for that file tree. Note that tarballs can represent file trees with empty directories, which git cannot store, and this function can generate hashes for those, which will, by default (see `skip_empty` below for how to change this behavior), differ from the hash of a tarball which omits those empty directories. In short, the hash function agrees with git on all trees which git can represent, but extends (in a consistent way) the domain of hashable trees to other trees which git cannot represent.
If a `predicate` function is passed, it is called on each `Header` object that is encountered while processing `tarball` and an entry is only hashed if `predicate(hdr)` is true. This can be used to selectively hash only parts of an archive, to skip entries that cause `extract` to throw an error, or to record what is extracted during the hashing process.
Before it is passed to the predicate function, the `Header` object is somewhat modified from the raw header in the tarball: the `path` field is normalized to remove `.` entries and replace multiple consecutive slashes with a single slash. If the entry has type `:hardlink`, the link target path is normalized the same way so that it will match the path of the target entry; the size field is set to the size of the target path (which must be an already-seen file).
Currently supported values for `algorithm` are `git-sha1` (the default) and `git-sha256`, which uses the same basic algorithm as `git-sha1` but replaces the SHA1 hash function with SHA2-256, the hash function that git will transition to using in the future (due to known attacks on SHA1). Support for other file tree hashing algorithms may be added in the future.
The `skip_empty` option controls whether directories in the tarball which recursively contain no files or symlinks are included in the hash or ignored. In general, if you are hashing the content of a tarball or a file tree, you care about all directories, not just non-empty ones, so including these in the computed hash is the default. So why does this function even provide the option to skip empty directories? Because git refuses to store empty directories and will ignore them if you try to add them to a repo. So if you compute a reference tree hash by by adding files to a git repo and then asking git for the tree hash, the hash value that you get will match the hash value computed by `tree_hash` with `skip_empty=true`. In other words, this option allows `tree_hash` to emulate how git would hash a tree with empty directories. If you are hashing trees that may contain empty directories (i.e. do not come from a git repo), however, it is recommended that you hash them using a tool (such as this one) that does not ignore empty directories.
###
`Tar.Header`Type
The `Header` type is a struct representing the essential metadata for a single record in a tar file with this definition:
```
struct Header
path :: String # path relative to the root
type :: Symbol # type indicator (see below)
mode :: UInt16 # mode/permissions (best viewed in octal)
size :: Int64 # size of record data in bytes
link :: String # target path of a symlink
end
```
Types are represented with the following symbols: `file`, `hardlink`, `symlink`, `chardev`, `blockdev`, `directory`, `fifo`, or for unknown types, the typeflag character as a symbol. Note that [`extract`](#Tar.extract) refuses to extract records types other than `file`, `symlink` and `directory`; [`list`](#Tar.list) will only list other kinds of records if called with `strict=false`.
The tar format includes various other metadata about records, including user and group IDs, user and group names, and timestamps. The `Tar` package, by design, completely ignores these. When creating tar files, these fields are always set to zero/empty. When reading tar files, these fields are ignored aside from verifying header checksums for each header record for all fields.
julia Future Future
======
The `Future` module implements future behavior of already existing functions, which will replace the current version in a future release of Julia.
###
`Future.copy!`Function
```
Future.copy!(dst, src) -> dst
```
Copy `src` into `dst`.
This function has moved to `Base` with Julia 1.1, consider using `copy!(dst, src)` instead. `Future.copy!` will be deprecated in the future.
###
`Future.randjump`Function
```
randjump(r::MersenneTwister, steps::Integer) -> MersenneTwister
```
Create an initialized `MersenneTwister` object, whose state is moved forward (without generating numbers) from `r` by `steps` steps. One such step corresponds to the generation of two `Float64` numbers. For each different value of `steps`, a large polynomial has to be generated internally. One is already pre-computed for `steps=big(10)^20`.
| programming_docs |
julia Sparse Linear Algebra Sparse Linear Algebra
=====================
Sparse matrix solvers call functions from [SuiteSparse](http://suitesparse.com). The following factorizations are available:
| Type | Description |
| --- | --- |
| `SuiteSparse.CHOLMOD.Factor` | Cholesky factorization |
| `SuiteSparse.UMFPACK.UmfpackLU` | LU factorization |
| `SuiteSparse.SPQR.QRSparse` | QR factorization |
Other solvers such as [Pardiso.jl](https://github.com/JuliaSparse/Pardiso.jl/) are as external packages. [Arpack.jl](https://julialinearalgebra.github.io/Arpack.jl/stable/) provides `eigs` and `svds` for iterative solution of eigensystems and singular value decompositions.
These factorizations are described in the [`Linear Algebra`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/) section of the manual:
1. [`cholesky`](../linearalgebra/index#LinearAlgebra.cholesky)
2. [`ldlt`](../linearalgebra/index#LinearAlgebra.ldlt)
3. [`lu`](../linearalgebra/index#LinearAlgebra.lu)
4. [`qr`](../linearalgebra/index#LinearAlgebra.qr)
###
`SuiteSparse.CHOLMOD.lowrankupdate`Function
```
lowrankupdate(F::CHOLMOD.Factor, C::AbstractArray) -> FF::CHOLMOD.Factor
```
Get an `LDLt` Factorization of `A + C*C'` given an `LDLt` or `LLt` factorization `F` of `A`.
The returned factor is always an `LDLt` factorization.
See also [`lowrankupdate!`](#SuiteSparse.CHOLMOD.lowrankupdate!), [`lowrankdowndate`](#SuiteSparse.CHOLMOD.lowrankdowndate), [`lowrankdowndate!`](#SuiteSparse.CHOLMOD.lowrankdowndate!).
###
`SuiteSparse.CHOLMOD.lowrankupdate!`Function
```
lowrankupdate!(F::CHOLMOD.Factor, C::AbstractArray)
```
Update an `LDLt` or `LLt` Factorization `F` of `A` to a factorization of `A + C*C'`.
`LLt` factorizations are converted to `LDLt`.
See also [`lowrankupdate`](#SuiteSparse.CHOLMOD.lowrankupdate), [`lowrankdowndate`](#SuiteSparse.CHOLMOD.lowrankdowndate), [`lowrankdowndate!`](#SuiteSparse.CHOLMOD.lowrankdowndate!).
###
`SuiteSparse.CHOLMOD.lowrankdowndate`Function
```
lowrankupdate(F::CHOLMOD.Factor, C::AbstractArray) -> FF::CHOLMOD.Factor
```
Get an `LDLt` Factorization of `A + C*C'` given an `LDLt` or `LLt` factorization `F` of `A`.
The returned factor is always an `LDLt` factorization.
See also [`lowrankdowndate!`](#SuiteSparse.CHOLMOD.lowrankdowndate!), [`lowrankupdate`](#SuiteSparse.CHOLMOD.lowrankupdate), [`lowrankupdate!`](#SuiteSparse.CHOLMOD.lowrankupdate!).
###
`SuiteSparse.CHOLMOD.lowrankdowndate!`Function
```
lowrankdowndate!(F::CHOLMOD.Factor, C::AbstractArray)
```
Update an `LDLt` or `LLt` Factorization `F` of `A` to a factorization of `A - C*C'`.
`LLt` factorizations are converted to `LDLt`.
See also [`lowrankdowndate`](#SuiteSparse.CHOLMOD.lowrankdowndate), [`lowrankupdate`](#SuiteSparse.CHOLMOD.lowrankupdate), [`lowrankupdate!`](#SuiteSparse.CHOLMOD.lowrankupdate!).
###
`SuiteSparse.CHOLMOD.lowrankupdowndate!`Function
```
lowrankupdowndate!(F::CHOLMOD.Factor, C::Sparse, update::Cint)
```
Update an `LDLt` or `LLt` Factorization `F` of `A` to a factorization of `A ± C*C'`.
If sparsity preserving factorization is used, i.e. `L*L' == P*A*P'` then the new factor will be `L*L' == P*A*P' + C'*C`
`update`: `Cint(1)` for `A + CC'`, `Cint(0)` for `A - CC'`
julia Logging Logging
=======
The [`Logging`](#Logging.Logging) module provides a way to record the history and progress of a computation as a log of events. Events are created by inserting a logging statement into the source code, for example:
```
@warn "Abandon printf debugging, all ye who enter here!"
┌ Warning: Abandon printf debugging, all ye who enter here!
└ @ Main REPL[1]:1
```
The system provides several advantages over peppering your source code with calls to `println()`. First, it allows you to control the visibility and presentation of messages without editing the source code. For example, in contrast to the `@warn` above
```
@debug "The sum of some values $(sum(rand(100)))"
```
will produce no output by default. Furthermore, it's very cheap to leave debug statements like this in the source code because the system avoids evaluating the message if it would later be ignored. In this case `sum(rand(100))` and the associated string processing will never be executed unless debug logging is enabled.
Second, the logging tools allow you to attach arbitrary data to each event as a set of key–value pairs. This allows you to capture local variables and other program state for later analysis. For example, to attach the local array variable `A` and the sum of a vector `v` as the key `s` you can use
```
A = ones(Int, 4, 4)
v = ones(100)
@info "Some variables" A s=sum(v)
# output
┌ Info: Some variables
│ A =
│ 4×4 Matrix{Int64}:
│ 1 1 1 1
│ 1 1 1 1
│ 1 1 1 1
│ 1 1 1 1
└ s = 100.0
```
All of the logging macros `@debug`, `@info`, `@warn` and `@error` share common features that are described in detail in the documentation for the more general macro [`@logmsg`](#Logging.@logmsg).
[Log event structure](#Log-event-structure)
--------------------------------------------
Each event generates several pieces of data, some provided by the user and some automatically extracted. Let's examine the user-defined data first:
* The *log level* is a broad category for the message that is used for early filtering. There are several standard levels of type [`LogLevel`](#Logging.LogLevel); user-defined levels are also possible. Each is distinct in purpose:
+ [`Logging.Debug`](#Logging.Debug) (log level -1000) is information intended for the developer of the program. These events are disabled by default.
+ [`Logging.Info`](#Logging.Info) (log level 0) is for general information to the user. Think of it as an alternative to using `println` directly.
+ [`Logging.Warn`](#Logging.Warn) (log level 1000) means something is wrong and action is likely required but that for now the program is still working.
+ [`Logging.Error`](#Logging.Error) (log level 2000) means something is wrong and it is unlikely to be recovered, at least by this part of the code. Often this log-level is unneeded as throwing an exception can convey all the required information.
* The *message* is an object describing the event. By convention `AbstractString`s passed as messages are assumed to be in markdown format. Other types will be displayed using `print(io, obj)` or `string(obj)` for text-based output and possibly `show(io,mime,obj)` for other multimedia displays used in the installed logger.
* Optional *key–value pairs* allow arbitrary data to be attached to each event. Some keys have conventional meaning that can affect the way an event is interpreted (see [`@logmsg`](#Logging.@logmsg)).
The system also generates some standard information for each event:
* The `module` in which the logging macro was expanded.
* The `file` and `line` where the logging macro occurs in the source code.
* A message `id` that is a unique, fixed identifier for the *source code statement* where the logging macro appears. This identifier is designed to be fairly stable even if the source code of the file changes, as long as the logging statement itself remains the same.
* A `group` for the event, which is set to the base name of the file by default, without extension. This can be used to group messages into categories more finely than the log level (for example, all deprecation warnings have group `:depwarn`), or into logical groupings across or within modules.
Notice that some useful information such as the event time is not included by default. This is because such information can be expensive to extract and is also *dynamically* available to the current logger. It's simple to define a [custom logger](#AbstractLogger-interface) to augment event data with the time, backtrace, values of global variables and other useful information as required.
[Processing log events](#Processing-log-events)
------------------------------------------------
As you can see in the examples, logging statements make no mention of where log events go or how they are processed. This is a key design feature that makes the system composable and natural for concurrent use. It does this by separating two different concerns:
* *Creating* log events is the concern of the module author who needs to decide where events are triggered and which information to include.
* *Processing* of log events — that is, display, filtering, aggregation and recording — is the concern of the application author who needs to bring multiple modules together into a cooperating application.
###
[Loggers](#Loggers)
Processing of events is performed by a *logger*, which is the first piece of user configurable code to see the event. All loggers must be subtypes of [`AbstractLogger`](#Logging.AbstractLogger).
When an event is triggered, the appropriate logger is found by looking for a task-local logger with the global logger as fallback. The idea here is that the application code knows how log events should be processed and exists somewhere at the top of the call stack. So we should look up through the call stack to discover the logger — that is, the logger should be *dynamically scoped*. (This is a point of contrast with logging frameworks where the logger is *lexically scoped*; provided explicitly by the module author or as a simple global variable. In such a system it's awkward to control logging while composing functionality from multiple modules.)
The global logger may be set with [`global_logger`](#Logging.global_logger), and task-local loggers controlled using [`with_logger`](#Logging.with_logger). Newly spawned tasks inherit the logger of the parent task.
There are three logger types provided by the library. [`ConsoleLogger`](#Logging.ConsoleLogger) is the default logger you see when starting the REPL. It displays events in a readable text format and tries to give simple but user friendly control over formatting and filtering. [`NullLogger`](#Logging.NullLogger) is a convenient way to drop all messages where necessary; it is the logging equivalent of the [`devnull`](../../base/base/index#Base.devnull) stream. [`SimpleLogger`](#Logging.SimpleLogger) is a very simplistic text formatting logger, mainly useful for debugging the logging system itself.
Custom loggers should come with overloads for the functions described in the [reference section](#AbstractLogger-interface).
###
[Early filtering and message handling](#Early-filtering-and-message-handling)
When an event occurs, a few steps of early filtering occur to avoid generating messages that will be discarded:
1. The message log level is checked against a global minimum level (set via [`disable_logging`](#Logging.disable_logging)). This is a crude but extremely cheap global setting.
2. The current logger state is looked up and the message level checked against the logger's cached minimum level, as found by calling [`Logging.min_enabled_level`](#Logging.min_enabled_level). This behavior can be overridden via environment variables (more on this later).
3. The [`Logging.shouldlog`](#Logging.shouldlog) function is called with the current logger, taking some minimal information (level, module, group, id) which can be computed statically. Most usefully, `shouldlog` is passed an event `id` which can be used to discard events early based on a cached predicate.
If all these checks pass, the message and key–value pairs are evaluated in full and passed to the current logger via the [`Logging.handle_message`](#Logging.handle_message) function. `handle_message()` may perform additional filtering as required and display the event to the screen, save it to a file, etc.
Exceptions that occur while generating the log event are captured and logged by default. This prevents individual broken events from crashing the application, which is helpful when enabling little-used debug events in a production system. This behavior can be customized per logger type by extending [`Logging.catch_exceptions`](#Logging.catch_exceptions).
[Testing log events](#Testing-log-events)
------------------------------------------
Log events are a side effect of running normal code, but you might find yourself wanting to test particular informational messages and warnings. The `Test` module provides a [`@test_logs`](../test/index#Test.@test_logs) macro that can be used to pattern match against the log event stream.
[Environment variables](#Environment-variables)
------------------------------------------------
Message filtering can be influenced through the `JULIA_DEBUG` environment variable, and serves as an easy way to enable debug logging for a file or module. For example, loading julia with `JULIA_DEBUG=loading` will activate `@debug` log messages in `loading.jl`:
```
$ JULIA_DEBUG=loading julia -e 'using OhMyREPL'
┌ Debug: Rejecting cache file /home/user/.julia/compiled/v0.7/OhMyREPL.ji due to it containing an invalid cache header
└ @ Base loading.jl:1328
[ Info: Recompiling stale cache file /home/user/.julia/compiled/v0.7/OhMyREPL.ji for module OhMyREPL
┌ Debug: Rejecting cache file /home/user/.julia/compiled/v0.7/Tokenize.ji due to it containing an invalid cache header
└ @ Base loading.jl:1328
...
```
Similarly, the environment variable can be used to enable debug logging of modules, such as `Pkg`, or module roots (see [`Base.moduleroot`](../../base/base/index#Base.moduleroot)). To enable all debug logging, use the special value `all`.
To turn debug logging on from the REPL, set `ENV["JULIA_DEBUG"]` to the name of the module of interest. Functions defined in the REPL belong to module `Main`; logging for them can be enabled like this:
```
julia> foo() = @debug "foo"
foo (generic function with 1 method)
julia> foo()
julia> ENV["JULIA_DEBUG"] = Main
Main
julia> foo()
┌ Debug: foo
└ @ Main REPL[1]:1
```
Use a comma separator to enable debug for multiple modules: `JULIA_DEBUG=loading,Main`.
[Examples](#Examples)
----------------------
###
[Example: Writing log events to a file](#Example:-Writing-log-events-to-a-file)
Sometimes it can be useful to write log events to a file. Here is an example of how to use a task-local and global logger to write information to a text file:
```
# Load the logging module
julia> using Logging
# Open a textfile for writing
julia> io = open("log.txt", "w+")
IOStream(<file log.txt>)
# Create a simple logger
julia> logger = SimpleLogger(io)
SimpleLogger(IOStream(<file log.txt>), Info, Dict{Any,Int64}())
# Log a task-specific message
julia> with_logger(logger) do
@info("a context specific log message")
end
# Write all buffered messages to the file
julia> flush(io)
# Set the global logger to logger
julia> global_logger(logger)
SimpleLogger(IOStream(<file log.txt>), Info, Dict{Any,Int64}())
# This message will now also be written to the file
julia> @info("a global log message")
# Close the file
julia> close(io)
```
###
[Example: Enable debug-level messages](#Example:-Enable-debug-level-messages)
Here is an example of creating a [`ConsoleLogger`](#Logging.ConsoleLogger) that lets through any messages with log level higher than, or equal, to [`Logging.Debug`](#Logging.Debug).
```
julia> using Logging
# Create a ConsoleLogger that prints any log messages with level >= Debug to stderr
julia> debuglogger = ConsoleLogger(stderr, Logging.Debug)
# Enable debuglogger for a task
julia> with_logger(debuglogger) do
@debug "a context specific log message"
end
# Set the global logger
julia> global_logger(debuglogger)
```
[Reference](#Reference)
------------------------
###
[Logging module](#Logging-module)
###
`Logging.Logging`Module
Utilities for capturing, filtering and presenting streams of log events. Normally you don't need to import `Logging` to create log events; for this the standard logging macros such as `@info` are already exported by `Base` and available by default.
###
[Creating events](#Creating-events)
###
`Logging.@logmsg`Macro
```
@debug message [key=value | value ...]
@info message [key=value | value ...]
@warn message [key=value | value ...]
@error message [key=value | value ...]
@logmsg level message [key=value | value ...]
```
Create a log record with an informational `message`. For convenience, four logging macros `@debug`, `@info`, `@warn` and `@error` are defined which log at the standard severity levels `Debug`, `Info`, `Warn` and `Error`. `@logmsg` allows `level` to be set programmatically to any `LogLevel` or custom log level types.
`message` should be an expression which evaluates to a string which is a human readable description of the log event. By convention, this string will be formatted as markdown when presented.
The optional list of `key=value` pairs supports arbitrary user defined metadata which will be passed through to the logging backend as part of the log record. If only a `value` expression is supplied, a key representing the expression will be generated using [`Symbol`](../../base/base/index#Core.Symbol). For example, `x` becomes `x=x`, and `foo(10)` becomes `Symbol("foo(10)")=foo(10)`. For splatting a list of key value pairs, use the normal splatting syntax, `@info "blah" kws...`.
There are some keys which allow automatically generated log data to be overridden:
* `_module=mod` can be used to specify a different originating module from the source location of the message.
* `_group=symbol` can be used to override the message group (this is normally derived from the base name of the source file).
* `_id=symbol` can be used to override the automatically generated unique message identifier. This is useful if you need to very closely associate messages generated on different source lines.
* `_file=string` and `_line=integer` can be used to override the apparent source location of a log message.
There's also some key value pairs which have conventional meaning:
* `maxlog=integer` should be used as a hint to the backend that the message should be displayed no more than `maxlog` times.
* `exception=ex` should be used to transport an exception with a log message, often used with `@error`. An associated backtrace `bt` may be attached using the tuple `exception=(ex,bt)`.
**Examples**
```
@debug "Verbose debugging information. Invisible by default"
@info "An informational message"
@warn "Something was odd. You should pay attention"
@error "A non fatal error occurred"
x = 10
@info "Some variables attached to the message" x a=42.0
@debug begin
sA = sum(A)
"sum(A) = $sA is an expensive operation, evaluated only when `shouldlog` returns true"
end
for i=1:10000
@info "With the default backend, you will only see (i = $i) ten times" maxlog=10
@debug "Algorithm1" i progress=i/10000
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L263-L330)###
`Logging.LogLevel`Type
```
LogLevel(level)
```
Severity/verbosity of a log record.
The log level provides a key against which potential log records may be filtered, before any other work is done to construct the log record data structure itself.
**Examples**
```
julia> Logging.LogLevel(0) == Logging.Info
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L109-L123)###
`Logging.Debug`Constant
```
Debug
```
Alias for [`LogLevel(-1000)`](#Logging.LogLevel).
###
`Logging.Info`Constant
```
Info
```
Alias for [`LogLevel(0)`](#Logging.LogLevel).
###
`Logging.Warn`Constant
```
Warn
```
Alias for [`LogLevel(1000)`](#Logging.LogLevel).
###
`Logging.Error`Constant
```
Error
```
Alias for [`LogLevel(2000)`](#Logging.LogLevel).
###
[Processing events with AbstractLogger](#AbstractLogger-interface)
Event processing is controlled by overriding functions associated with `AbstractLogger`:
| Methods to implement | | Brief description |
| --- | --- | --- |
| [`Logging.handle_message`](#Logging.handle_message) | | Handle a log event |
| [`Logging.shouldlog`](#Logging.shouldlog) | | Early filtering of events |
| [`Logging.min_enabled_level`](#Logging.min_enabled_level) | | Lower bound for log level of accepted events |
| **Optional methods** | **Default definition** | **Brief description** |
| [`Logging.catch_exceptions`](#Logging.catch_exceptions) | `true` | Catch exceptions during event evaluation |
###
`Logging.AbstractLogger`Type
A logger controls how log records are filtered and dispatched. When a log record is generated, the logger is the first piece of user configurable code which gets to inspect the record and decide what to do with it.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L24-L28)###
`Logging.handle_message`Function
```
handle_message(logger, level, message, _module, group, id, file, line; key1=val1, ...)
```
Log a message to `logger` at `level`. The logical location at which the message was generated is given by module `_module` and `group`; the source location by `file` and `line`. `id` is an arbitrary unique value (typically a [`Symbol`](../../base/base/index#Core.Symbol)) to be used as a key to identify the log statement when filtering.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L31-L39)###
`Logging.shouldlog`Function
```
shouldlog(logger, level, _module, group, id)
```
Return true when `logger` accepts a message at `level`, generated for `_module`, `group` and with unique log identifier `id`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L42-L47)###
`Logging.min_enabled_level`Function
```
min_enabled_level(logger)
```
Return the minimum enabled level for `logger` for early filtering. That is, the log level below or equal to which all messages are filtered.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L50-L55)###
`Logging.catch_exceptions`Function
```
catch_exceptions(logger)
```
Return true if the logger should catch exceptions which happen during log record construction. By default, messages are caught
By default all exceptions are caught to prevent log message generation from crashing the program. This lets users confidently toggle little-used functionality - such as debug logging - in a production system.
If you want to use logging as an audit trail you should disable this for your logger type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L58-L70)###
`Logging.disable_logging`Function
```
disable_logging(level)
```
Disable all log messages at log levels equal to or less than `level`. This is a *global* setting, intended to make debug logging extremely cheap when disabled.
**Examples**
```
Logging.disable_logging(Logging.Info) # Disable debug and info
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L520-L531)###
[Using Loggers](#Using-Loggers)
Logger installation and inspection:
###
`Logging.global_logger`Function
```
global_logger()
```
Return the global logger, used to receive messages when no specific logger exists for the current task.
```
global_logger(logger)
```
Set the global logger to `logger`, and return the previous global logger.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L586-L595)###
`Logging.with_logger`Function
```
with_logger(function, logger)
```
Execute `function`, directing all log messages to `logger`.
**Example**
```
function test(x)
@info "x = $x"
end
with_logger(logger) do
test(1)
test([1,2])
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L604-L621)###
`Logging.current_logger`Function
```
current_logger()
```
Return the logger for the current task, or the global logger if none is attached to the task.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L626-L631)Loggers that are supplied with the system:
###
`Logging.NullLogger`Type
```
NullLogger()
```
Logger which disables all messages and produces no output - the logger equivalent of /dev/null.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L93-L98)###
`Logging.ConsoleLogger`Type
```
ConsoleLogger([stream,] min_level=Info; meta_formatter=default_metafmt,
show_limited=true, right_justify=0)
```
Logger with formatting optimized for readability in a text console, for example interactive work with the Julia REPL.
Log levels less than `min_level` are filtered out.
Message formatting can be controlled by setting keyword arguments:
* `meta_formatter` is a function which takes the log event metadata `(level, _module, group, id, file, line)` and returns a color (as would be passed to printstyled), prefix and suffix for the log message. The default is to prefix with the log level and a suffix containing the module, file and line location.
* `show_limited` limits the printing of large data structures to something which can fit on the screen by setting the `:limit` `IOContext` key during formatting.
* `right_justify` is the integer column which log metadata is right justified at. The default is zero (metadata goes on its own line).
###
`Logging.SimpleLogger`Type
```
SimpleLogger([stream,] min_level=Info)
```
Simplistic logger for logging all messages with level greater than or equal to `min_level` to `stream`. If stream is closed then messages with log level greater or equal to `Warn` will be logged to `stderr` and below to `stdout`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/logging.jl#L639-L645)
| programming_docs |
julia File Events File Events
===========
###
`FileWatching.poll_fd`Function
```
poll_fd(fd, timeout_s::Real=-1; readable=false, writable=false)
```
Monitor a file descriptor `fd` for changes in the read or write availability, and with a timeout given by `timeout_s` seconds.
The keyword arguments determine which of read and/or write status should be monitored; at least one of them must be set to `true`.
The returned value is an object with boolean fields `readable`, `writable`, and `timedout`, giving the result of the polling.
###
`FileWatching.poll_file`Function
```
poll_file(path::AbstractString, interval_s::Real=5.007, timeout_s::Real=-1) -> (previous::StatStruct, current)
```
Monitor a file for changes by polling every `interval_s` seconds until a change occurs or `timeout_s` seconds have elapsed. The `interval_s` should be a long period; the default is 5.007 seconds.
Returns a pair of status objects `(previous, current)` when a change is detected. The `previous` status is always a `StatStruct`, but it may have all of the fields zeroed (indicating the file didn't previously exist, or wasn't previously accessible).
The `current` status object may be a `StatStruct`, an `EOFError` (indicating the timeout elapsed), or some other `Exception` subtype (if the `stat` operation failed - for example, if the path does not exist).
To determine when a file was modified, compare `current isa StatStruct && mtime(prev) != mtime(current)` to detect notification of changes. However, using [`watch_file`](#FileWatching.watch_file) for this operation is preferred, since it is more reliable and efficient, although in some situations it may not be available.
###
`FileWatching.watch_file`Function
```
watch_file(path::AbstractString, timeout_s::Real=-1)
```
Watch file or directory `path` for changes until a change occurs or `timeout_s` seconds have elapsed.
The returned value is an object with boolean fields `changed`, `renamed`, and `timedout`, giving the result of watching the file.
This behavior of this function varies slightly across platforms. See <https://nodejs.org/api/fs.html#fs_caveats> for more detailed information.
###
`FileWatching.watch_folder`Function
```
watch_folder(path::AbstractString, timeout_s::Real=-1)
```
Watches a file or directory `path` for changes until a change has occurred or `timeout_s` seconds have elapsed.
This will continuing tracking changes for `path` in the background until `unwatch_folder` is called on the same `path`.
The returned value is an pair where the first field is the name of the changed file (if available) and the second field is an object with boolean fields `changed`, `renamed`, and `timedout`, giving the event.
This behavior of this function varies slightly across platforms. See <https://nodejs.org/api/fs.html#fs_caveats> for more detailed information.
###
`FileWatching.unwatch_folder`Function
```
unwatch_folder(path::AbstractString)
```
Stop background tracking of changes for `path`. It is not recommended to do this while another task is waiting for `watch_folder` to return on the same path, as the result may be unpredictable.
julia Sparse Arrays Sparse Arrays
=============
Julia has support for sparse vectors and [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix) in the `SparseArrays` stdlib module. Sparse arrays are arrays that contain enough zeros that storing them in a special data structure leads to savings in space and execution time, compared to dense arrays.
[Compressed Sparse Column (CSC) Sparse Matrix Storage](#man-csc)
-----------------------------------------------------------------
In Julia, sparse matrices are stored in the [Compressed Sparse Column (CSC) format](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_.28CSC_or_CCS.29). Julia sparse matrices have the type [`SparseMatrixCSC{Tv,Ti}`](#SparseArrays.SparseMatrixCSC), where `Tv` is the type of the stored values, and `Ti` is the integer type for storing column pointers and row indices. The internal representation of `SparseMatrixCSC` is as follows:
```
struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}
m::Int # Number of rows
n::Int # Number of columns
colptr::Vector{Ti} # Column j is in colptr[j]:(colptr[j+1]-1)
rowval::Vector{Ti} # Row indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
end
```
The compressed sparse column storage makes it easy and quick to access the elements in the column of a sparse matrix, whereas accessing the sparse matrix by rows is considerably slower. Operations such as insertion of previously unstored entries one at a time in the CSC structure tend to be slow. This is because all elements of the sparse matrix that are beyond the point of insertion have to be moved one place over.
All operations on sparse matrices are carefully implemented to exploit the CSC data structure for performance, and to avoid expensive operations.
If you have data in CSC format from a different application or library, and wish to import it in Julia, make sure that you use 1-based indexing. The row indices in every column need to be sorted. If your `SparseMatrixCSC` object contains unsorted row indices, one quick way to sort them is by doing a double transpose.
In some applications, it is convenient to store explicit zero values in a `SparseMatrixCSC`. These *are* accepted by functions in `Base` (but there is no guarantee that they will be preserved in mutating operations). Such explicitly stored zeros are treated as structural nonzeros by many routines. The [`nnz`](#SparseArrays.nnz) function returns the number of elements explicitly stored in the sparse data structure, including non-structural zeros. In order to count the exact number of numerical nonzeros, use [`count(!iszero, x)`](../../base/collections/index#Base.count), which inspects every stored element of a sparse matrix. [`dropzeros`](#SparseArrays.dropzeros), and the in-place [`dropzeros!`](#SparseArrays.dropzeros!), can be used to remove stored zeros from the sparse matrix.
```
julia> A = sparse([1, 1, 2, 3], [1, 3, 2, 3], [0, 1, 2, 0])
3×3 SparseMatrixCSC{Int64, Int64} with 4 stored entries:
0 ⋅ 1
⋅ 2 ⋅
⋅ ⋅ 0
julia> dropzeros(A)
3×3 SparseMatrixCSC{Int64, Int64} with 2 stored entries:
⋅ ⋅ 1
⋅ 2 ⋅
⋅ ⋅ ⋅
```
[Sparse Vector Storage](#Sparse-Vector-Storage)
------------------------------------------------
Sparse vectors are stored in a close analog to compressed sparse column format for sparse matrices. In Julia, sparse vectors have the type [`SparseVector{Tv,Ti}`](#SparseArrays.SparseVector) where `Tv` is the type of the stored values and `Ti` the integer type for the indices. The internal representation is as follows:
```
struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
n::Int # Length of the sparse vector
nzind::Vector{Ti} # Indices of stored values
nzval::Vector{Tv} # Stored values, typically nonzeros
end
```
As for [`SparseMatrixCSC`](#SparseArrays.SparseMatrixCSC), the `SparseVector` type can also contain explicitly stored zeros. (See [Sparse Matrix Storage](#man-csc).).
[Sparse Vector and Matrix Constructors](#Sparse-Vector-and-Matrix-Constructors)
--------------------------------------------------------------------------------
The simplest way to create a sparse array is to use a function equivalent to the [`zeros`](../../base/arrays/index#Base.zeros) function that Julia provides for working with dense arrays. To produce a sparse array instead, you can use the same name with an `sp` prefix:
```
julia> spzeros(3)
3-element SparseVector{Float64, Int64} with 0 stored entries
```
The [`sparse`](#SparseArrays.sparse) function is often a handy way to construct sparse arrays. For example, to construct a sparse matrix we can input a vector `I` of row indices, a vector `J` of column indices, and a vector `V` of stored values (this is also known as the [COO (coordinate) format](https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_.28COO.29)). `sparse(I,J,V)` then constructs a sparse matrix such that `S[I[k], J[k]] = V[k]`. The equivalent sparse vector constructor is [`sparsevec`](#SparseArrays.sparsevec), which takes the (row) index vector `I` and the vector `V` with the stored values and constructs a sparse vector `R` such that `R[I[k]] = V[k]`.
```
julia> I = [1, 4, 3, 5]; J = [4, 7, 18, 9]; V = [1, 2, -5, 3];
julia> S = sparse(I,J,V)
5×18 SparseMatrixCSC{Int64, Int64} with 4 stored entries:
⠀⠈⠀⡀⠀⠀⠀⠀⠠
⠀⠀⠀⠀⠁⠀⠀⠀⠀
julia> R = sparsevec(I,V)
5-element SparseVector{Int64, Int64} with 4 stored entries:
[1] = 1
[3] = -5
[4] = 2
[5] = 3
```
The inverse of the [`sparse`](#SparseArrays.sparse) and [`sparsevec`](#SparseArrays.sparsevec) functions is [`findnz`](#SparseArrays.findnz), which retrieves the inputs used to create the sparse array. [`findall(!iszero, x)`](#) returns the cartesian indices of non-zero entries in `x` (including stored entries equal to zero).
```
julia> findnz(S)
([1, 4, 5, 3], [4, 7, 9, 18], [1, 2, 3, -5])
julia> findall(!iszero, S)
4-element Vector{CartesianIndex{2}}:
CartesianIndex(1, 4)
CartesianIndex(4, 7)
CartesianIndex(5, 9)
CartesianIndex(3, 18)
julia> findnz(R)
([1, 3, 4, 5], [1, -5, 2, 3])
julia> findall(!iszero, R)
4-element Vector{Int64}:
1
3
4
5
```
Another way to create a sparse array is to convert a dense array into a sparse array using the [`sparse`](#SparseArrays.sparse) function:
```
julia> sparse(Matrix(1.0I, 5, 5))
5×5 SparseMatrixCSC{Float64, Int64} with 5 stored entries:
1.0 ⋅ ⋅ ⋅ ⋅
⋅ 1.0 ⋅ ⋅ ⋅
⋅ ⋅ 1.0 ⋅ ⋅
⋅ ⋅ ⋅ 1.0 ⋅
⋅ ⋅ ⋅ ⋅ 1.0
julia> sparse([1.0, 0.0, 1.0])
3-element SparseVector{Float64, Int64} with 2 stored entries:
[1] = 1.0
[3] = 1.0
```
You can go in the other direction using the [`Array`](../../base/arrays/index#Core.Array) constructor. The [`issparse`](#SparseArrays.issparse) function can be used to query if a matrix is sparse.
```
julia> issparse(spzeros(5))
true
```
[Sparse matrix operations](#Sparse-matrix-operations)
------------------------------------------------------
Arithmetic operations on sparse matrices also work as they do on dense matrices. Indexing of, assignment into, and concatenation of sparse matrices work in the same way as dense matrices. Indexing operations, especially assignment, are expensive, when carried out one element at a time. In many cases it may be better to convert the sparse matrix into `(I,J,V)` format using [`findnz`](#SparseArrays.findnz), manipulate the values or the structure in the dense vectors `(I,J,V)`, and then reconstruct the sparse matrix.
[Correspondence of dense and sparse methods](#Correspondence-of-dense-and-sparse-methods)
------------------------------------------------------------------------------------------
The following table gives a correspondence between built-in methods on sparse matrices and their corresponding methods on dense matrix types. In general, methods that generate sparse matrices differ from their dense counterparts in that the resulting matrix follows the same sparsity pattern as a given sparse matrix `S`, or that the resulting sparse matrix has density `d`, i.e. each matrix element has a probability `d` of being non-zero.
Details can be found in the [Sparse Vectors and Matrices](#stdlib-sparse-arrays) section of the standard library reference.
| Sparse | Dense | Description |
| --- | --- | --- |
| [`spzeros(m,n)`](#SparseArrays.spzeros) | [`zeros(m,n)`](../../base/arrays/index#Base.zeros) | Creates a *m*-by-*n* matrix of zeros. ([`spzeros(m,n)`](#SparseArrays.spzeros) is empty.) |
| [`sparse(I,n,n)`](#SparseArrays.sparse) | [`Matrix(I,n,n)`](../../base/arrays/index#Base.Matrix) | Creates a *n*-by-*n* identity matrix. |
| [`sparse(A)`](#SparseArrays.sparse) | [`Array(S)`](../../base/arrays/index#Core.Array) | Interconverts between dense and sparse formats. |
| [`sprand(m,n,d)`](#SparseArrays.sprand) | [`rand(m,n)`](../random/index#Base.rand) | Creates a *m*-by-*n* random matrix (of density *d*) with iid non-zero elements distributed uniformly on the half-open interval $[0, 1)$. |
| [`sprandn(m,n,d)`](#SparseArrays.sprandn) | [`randn(m,n)`](../random/index#Base.randn) | Creates a *m*-by-*n* random matrix (of density *d*) with iid non-zero elements distributed according to the standard normal (Gaussian) distribution. |
| [`sprandn(rng,m,n,d)`](#SparseArrays.sprandn) | [`randn(rng,m,n)`](../random/index#Base.randn) | Creates a *m*-by-*n* random matrix (of density *d*) with iid non-zero elements generated with the `rng` random number generator |
[Sparse Arrays](#stdlib-sparse-arrays)
=======================================
###
`SparseArrays.AbstractSparseArray`Type
```
AbstractSparseArray{Tv,Ti,N}
```
Supertype for `N`-dimensional sparse arrays (or array-like types) with elements of type `Tv` and index type `Ti`. [`SparseMatrixCSC`](#SparseArrays.SparseMatrixCSC), [`SparseVector`](#SparseArrays.SparseVector) and `SuiteSparse.CHOLMOD.Sparse` are subtypes of this.
###
`SparseArrays.AbstractSparseVector`Type
```
AbstractSparseVector{Tv,Ti}
```
Supertype for one-dimensional sparse arrays (or array-like types) with elements of type `Tv` and index type `Ti`. Alias for `AbstractSparseArray{Tv,Ti,1}`.
###
`SparseArrays.AbstractSparseMatrix`Type
```
AbstractSparseMatrix{Tv,Ti}
```
Supertype for two-dimensional sparse arrays (or array-like types) with elements of type `Tv` and index type `Ti`. Alias for `AbstractSparseArray{Tv,Ti,2}`.
###
`SparseArrays.SparseVector`Type
```
SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
```
Vector type for storing sparse vectors.
###
`SparseArrays.SparseMatrixCSC`Type
```
SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrixCSC{Tv,Ti}
```
Matrix type for storing sparse matrices in the [Compressed Sparse Column](#man-csc) format. The standard way of constructing SparseMatrixCSC is through the [`sparse`](#SparseArrays.sparse) function. See also [`spzeros`](#SparseArrays.spzeros), [`spdiagm`](#SparseArrays.spdiagm) and [`sprand`](#SparseArrays.sprand).
###
`SparseArrays.sparse`Function
```
sparse(A)
```
Convert an AbstractMatrix `A` into a sparse matrix.
**Examples**
```
julia> A = Matrix(1.0I, 3, 3)
3×3 Matrix{Float64}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> sparse(A)
3×3 SparseMatrixCSC{Float64, Int64} with 3 stored entries:
1.0 ⋅ ⋅
⋅ 1.0 ⋅
⋅ ⋅ 1.0
```
```
sparse(I, J, V,[ m, n, combine])
```
Create a sparse matrix `S` of dimensions `m x n` such that `S[I[k], J[k]] = V[k]`. The `combine` function is used to combine duplicates. If `m` and `n` are not specified, they are set to `maximum(I)` and `maximum(J)` respectively. If the `combine` function is not supplied, `combine` defaults to `+` unless the elements of `V` are Booleans in which case `combine` defaults to `|`. All elements of `I` must satisfy `1 <= I[k] <= m`, and all elements of `J` must satisfy `1 <= J[k] <= n`. Numerical zeros in (`I`, `J`, `V`) are retained as structural nonzeros; to drop numerical zeros, use [`dropzeros!`](#SparseArrays.dropzeros!).
For additional documentation and an expert driver, see `SparseArrays.sparse!`.
**Examples**
```
julia> Is = [1; 2; 3];
julia> Js = [1; 2; 3];
julia> Vs = [1; 2; 3];
julia> sparse(Is, Js, Vs)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
1 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 3
```
###
`SparseArrays.sparsevec`Function
```
sparsevec(I, V, [m, combine])
```
Create a sparse vector `S` of length `m` such that `S[I[k]] = V[k]`. Duplicates are combined using the `combine` function, which defaults to `+` if no `combine` argument is provided, unless the elements of `V` are Booleans in which case `combine` defaults to `|`.
**Examples**
```
julia> II = [1, 3, 3, 5]; V = [0.1, 0.2, 0.3, 0.2];
julia> sparsevec(II, V)
5-element SparseVector{Float64, Int64} with 3 stored entries:
[1] = 0.1
[3] = 0.5
[5] = 0.2
julia> sparsevec(II, V, 8, -)
8-element SparseVector{Float64, Int64} with 3 stored entries:
[1] = 0.1
[3] = -0.1
[5] = 0.2
julia> sparsevec([1, 3, 1, 2, 2], [true, true, false, false, false])
3-element SparseVector{Bool, Int64} with 3 stored entries:
[1] = 1
[2] = 0
[3] = 1
```
```
sparsevec(d::Dict, [m])
```
Create a sparse vector of length `m` where the nonzero indices are keys from the dictionary, and the nonzero values are the values from the dictionary.
**Examples**
```
julia> sparsevec(Dict(1 => 3, 2 => 2))
2-element SparseVector{Int64, Int64} with 2 stored entries:
[1] = 3
[2] = 2
```
```
sparsevec(A)
```
Convert a vector `A` into a sparse vector of length `m`.
**Examples**
```
julia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0])
6-element SparseVector{Float64, Int64} with 3 stored entries:
[1] = 1.0
[2] = 2.0
[5] = 3.0
```
###
`SparseArrays.issparse`Function
```
issparse(S)
```
Returns `true` if `S` is sparse, and `false` otherwise.
**Examples**
```
julia> sv = sparsevec([1, 4], [2.3, 2.2], 10)
10-element SparseVector{Float64, Int64} with 2 stored entries:
[1 ] = 2.3
[4 ] = 2.2
julia> issparse(sv)
true
julia> issparse(Array(sv))
false
```
###
`SparseArrays.nnz`Function
```
nnz(A)
```
Returns the number of stored (filled) elements in a sparse array.
**Examples**
```
julia> A = sparse(2I, 3, 3)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
2 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 2
julia> nnz(A)
3
```
###
`SparseArrays.findnz`Function
```
findnz(A::SparseMatrixCSC)
```
Return a tuple `(I, J, V)` where `I` and `J` are the row and column indices of the stored ("structurally non-zero") values in sparse matrix `A`, and `V` is a vector of the values.
**Examples**
```
julia> A = sparse([1 2 0; 0 0 3; 0 4 0])
3×3 SparseMatrixCSC{Int64, Int64} with 4 stored entries:
1 2 ⋅
⋅ ⋅ 3
⋅ 4 ⋅
julia> findnz(A)
([1, 1, 3, 2], [1, 2, 2, 3], [1, 2, 4, 3])
```
###
`SparseArrays.spzeros`Function
```
spzeros([type,]m[,n])
```
Create a sparse vector of length `m` or sparse matrix of size `m x n`. This sparse array will not contain any nonzero values. No storage will be allocated for nonzero values during construction. The type defaults to [`Float64`](../../base/numbers/index#Core.Float64) if not specified.
**Examples**
```
julia> spzeros(3, 3)
3×3 SparseMatrixCSC{Float64, Int64} with 0 stored entries:
⋅ ⋅ ⋅
⋅ ⋅ ⋅
⋅ ⋅ ⋅
julia> spzeros(Float32, 4)
4-element SparseVector{Float32, Int64} with 0 stored entries
```
###
`SparseArrays.spdiagm`Function
```
spdiagm(kv::Pair{<:Integer,<:AbstractVector}...)
spdiagm(m::Integer, n::Integer, kv::Pair{<:Integer,<:AbstractVector}...)
```
Construct a sparse diagonal matrix from `Pair`s of vectors and diagonals. Each vector `kv.second` will be placed on the `kv.first` diagonal. By default, the matrix is square and its size is inferred from `kv`, but a non-square size `m`×`n` (padded with zeros as needed) can be specified by passing `m,n` as the first arguments.
**Examples**
```
julia> spdiagm(-1 => [1,2,3,4], 1 => [4,3,2,1])
5×5 SparseMatrixCSC{Int64, Int64} with 8 stored entries:
⋅ 4 ⋅ ⋅ ⋅
1 ⋅ 3 ⋅ ⋅
⋅ 2 ⋅ 2 ⋅
⋅ ⋅ 3 ⋅ 1
⋅ ⋅ ⋅ 4 ⋅
```
```
spdiagm(v::AbstractVector)
spdiagm(m::Integer, n::Integer, v::AbstractVector)
```
Construct a sparse matrix with elements of the vector as diagonal elements. By default (no given `m` and `n`), the matrix is square and its size is given by `length(v)`, but a non-square size `m`×`n` can be specified by passing `m` and `n` as the first arguments.
These functions require at least Julia 1.6.
**Examples**
```
julia> spdiagm([1,2,3])
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
1 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 3
julia> spdiagm(sparse([1,0,3]))
3×3 SparseMatrixCSC{Int64, Int64} with 2 stored entries:
1 ⋅ ⋅
⋅ ⋅ ⋅
⋅ ⋅ 3
```
###
`SparseArrays.sparse_hcat`Function
```
sparse_hcat(A...)
```
Concatenate along dimension 2. Return a SparseMatrixCSC object.
This method was added in Julia 1.8. It mimicks previous concatenation behavior, where the concatenation with specialized "sparse" matrix types from LinearAlgebra.jl automatically yielded sparse output even in the absence of any SparseArray argument.
###
`SparseArrays.sparse_vcat`Function
```
sparse_vcat(A...)
```
Concatenate along dimension 1. Return a SparseMatrixCSC object.
This method was added in Julia 1.8. It mimicks previous concatenation behavior, where the concatenation with specialized "sparse" matrix types from LinearAlgebra.jl automatically yielded sparse output even in the absence of any SparseArray argument.
###
`SparseArrays.sparse_hvcat`Function
```
sparse_hvcat(rows::Tuple{Vararg{Int}}, values...)
```
Sparse horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row.
This method was added in Julia 1.8. It mimicks previous concatenation behavior, where the concatenation with specialized "sparse" matrix types from LinearAlgebra.jl automatically yielded sparse output even in the absence of any SparseArray argument.
###
`SparseArrays.blockdiag`Function
```
blockdiag(A...)
```
Concatenate matrices block-diagonally. Currently only implemented for sparse matrices.
**Examples**
```
julia> blockdiag(sparse(2I, 3, 3), sparse(4I, 2, 2))
5×5 SparseMatrixCSC{Int64, Int64} with 5 stored entries:
2 ⋅ ⋅ ⋅ ⋅
⋅ 2 ⋅ ⋅ ⋅
⋅ ⋅ 2 ⋅ ⋅
⋅ ⋅ ⋅ 4 ⋅
⋅ ⋅ ⋅ ⋅ 4
```
###
`SparseArrays.sprand`Function
```
sprand([rng],[type],m,[n],p::AbstractFloat,[rfn])
```
Create a random length `m` sparse vector or `m` by `n` sparse matrix, in which the probability of any element being nonzero is independently given by `p` (and hence the mean density of nonzeros is also exactly `p`). Nonzero values are sampled from the distribution specified by `rfn` and have the type `type`. The uniform distribution is used in case `rfn` is not specified. The optional `rng` argument specifies a random number generator, see [Random Numbers](../random/index#Random-Numbers).
**Examples**
```
julia> sprand(Bool, 2, 2, 0.5)
2×2 SparseMatrixCSC{Bool, Int64} with 2 stored entries:
1 1
⋅ ⋅
julia> sprand(Float64, 3, 0.75)
3-element SparseVector{Float64, Int64} with 2 stored entries:
[1] = 0.795547
[2] = 0.49425
```
###
`SparseArrays.sprandn`Function
```
sprandn([rng][,Type],m[,n],p::AbstractFloat)
```
Create a random sparse vector of length `m` or sparse matrix of size `m` by `n` with the specified (independent) probability `p` of any entry being nonzero, where nonzero values are sampled from the normal distribution. The optional `rng` argument specifies a random number generator, see [Random Numbers](../random/index#Random-Numbers).
Specifying the output element type `Type` requires at least Julia 1.1.
**Examples**
```
julia> sprandn(2, 2, 0.75)
2×2 SparseMatrixCSC{Float64, Int64} with 3 stored entries:
-1.20577 ⋅
0.311817 -0.234641
```
###
`SparseArrays.nonzeros`Function
```
nonzeros(A)
```
Return a vector of the structural nonzero values in sparse array `A`. This includes zeros that are explicitly stored in the sparse array. The returned vector points directly to the internal nonzero storage of `A`, and any modifications to the returned vector will mutate `A` as well. See [`rowvals`](#SparseArrays.rowvals) and [`nzrange`](#SparseArrays.nzrange).
**Examples**
```
julia> A = sparse(2I, 3, 3)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
2 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 2
julia> nonzeros(A)
3-element Vector{Int64}:
2
2
2
```
###
`SparseArrays.rowvals`Function
```
rowvals(A::AbstractSparseMatrixCSC)
```
Return a vector of the row indices of `A`. Any modifications to the returned vector will mutate `A` as well. Providing access to how the row indices are stored internally can be useful in conjunction with iterating over structural nonzero values. See also [`nonzeros`](#SparseArrays.nonzeros) and [`nzrange`](#SparseArrays.nzrange).
**Examples**
```
julia> A = sparse(2I, 3, 3)
3×3 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
2 ⋅ ⋅
⋅ 2 ⋅
⋅ ⋅ 2
julia> rowvals(A)
3-element Vector{Int64}:
1
2
3
```
###
`SparseArrays.nzrange`Function
```
nzrange(A::AbstractSparseMatrixCSC, col::Integer)
```
Return the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with [`nonzeros`](#SparseArrays.nonzeros) and [`rowvals`](#SparseArrays.rowvals), this allows for convenient iterating over a sparse matrix :
```
A = sparse(I,J,V)
rows = rowvals(A)
vals = nonzeros(A)
m, n = size(A)
for j = 1:n
for i in nzrange(A, j)
row = rows[i]
val = vals[i]
# perform sparse wizardry...
end
end
```
```
nzrange(x::SparseVectorUnion, col)
```
Give the range of indices to the structural nonzero values of a sparse vector. The column index `col` is ignored (assumed to be `1`).
###
`SparseArrays.droptol!`Function
```
droptol!(A::AbstractSparseMatrixCSC, tol)
```
Removes stored values from `A` whose absolute value is less than or equal to `tol`.
```
droptol!(x::SparseVector, tol)
```
Removes stored values from `x` whose absolute value is less than or equal to `tol`.
###
`SparseArrays.dropzeros!`Function
```
dropzeros!(A::AbstractSparseMatrixCSC;)
```
Removes stored numerical zeros from `A`.
For an out-of-place version, see [`dropzeros`](#SparseArrays.dropzeros). For algorithmic information, see `fkeep!`.
```
dropzeros!(x::SparseVector)
```
Removes stored numerical zeros from `x`.
For an out-of-place version, see [`dropzeros`](#SparseArrays.dropzeros). For algorithmic information, see `fkeep!`.
###
`SparseArrays.dropzeros`Function
```
dropzeros(A::AbstractSparseMatrixCSC;)
```
Generates a copy of `A` and removes stored numerical zeros from that copy.
For an in-place version and algorithmic information, see [`dropzeros!`](#SparseArrays.dropzeros!).
**Examples**
```
julia> A = sparse([1, 2, 3], [1, 2, 3], [1.0, 0.0, 1.0])
3×3 SparseMatrixCSC{Float64, Int64} with 3 stored entries:
1.0 ⋅ ⋅
⋅ 0.0 ⋅
⋅ ⋅ 1.0
julia> dropzeros(A)
3×3 SparseMatrixCSC{Float64, Int64} with 2 stored entries:
1.0 ⋅ ⋅
⋅ ⋅ ⋅
⋅ ⋅ 1.0
```
```
dropzeros(x::SparseVector)
```
Generates a copy of `x` and removes numerical zeros from that copy.
For an in-place version and algorithmic information, see [`dropzeros!`](#SparseArrays.dropzeros!).
**Examples**
```
julia> A = sparsevec([1, 2, 3], [1.0, 0.0, 1.0])
3-element SparseVector{Float64, Int64} with 3 stored entries:
[1] = 1.0
[2] = 0.0
[3] = 1.0
julia> dropzeros(A)
3-element SparseVector{Float64, Int64} with 2 stored entries:
[1] = 1.0
[3] = 1.0
```
###
`SparseArrays.permute`Function
```
permute(A::AbstractSparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},
q::AbstractVector{<:Integer}) where {Tv,Ti}
```
Bilaterally permute `A`, returning `PAQ` (`A[p,q]`). Column-permutation `q`'s length must match `A`'s column count (`length(q) == size(A, 2)`). Row-permutation `p`'s length must match `A`'s row count (`length(p) == size(A, 1)`).
For expert drivers and additional information, see [`permute!`](#).
**Examples**
```
julia> A = spdiagm(0 => [1, 2, 3, 4], 1 => [5, 6, 7])
4×4 SparseMatrixCSC{Int64, Int64} with 7 stored entries:
1 5 ⋅ ⋅
⋅ 2 6 ⋅
⋅ ⋅ 3 7
⋅ ⋅ ⋅ 4
julia> permute(A, [4, 3, 2, 1], [1, 2, 3, 4])
4×4 SparseMatrixCSC{Int64, Int64} with 7 stored entries:
⋅ ⋅ ⋅ 4
⋅ ⋅ 3 7
⋅ 2 6 ⋅
1 5 ⋅ ⋅
julia> permute(A, [1, 2, 3, 4], [4, 3, 2, 1])
4×4 SparseMatrixCSC{Int64, Int64} with 7 stored entries:
⋅ ⋅ 5 1
⋅ 6 2 ⋅
7 3 ⋅ ⋅
4 ⋅ ⋅ ⋅
```
###
`Base.permute!`Method
```
permute!(X::AbstractSparseMatrixCSC{Tv,Ti}, A::AbstractSparseMatrixCSC{Tv,Ti},
p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer},
[C::AbstractSparseMatrixCSC{Tv,Ti}]) where {Tv,Ti}
```
Bilaterally permute `A`, storing result `PAQ` (`A[p,q]`) in `X`. Stores intermediate result `(AQ)^T` (`transpose(A[:,q])`) in optional argument `C` if present. Requires that none of `X`, `A`, and, if present, `C` alias each other; to store result `PAQ` back into `A`, use the following method lacking `X`:
```
permute!(A::AbstractSparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},
q::AbstractVector{<:Integer}[, C::AbstractSparseMatrixCSC{Tv,Ti},
[workcolptr::Vector{Ti}]]) where {Tv,Ti}
```
`X`'s dimensions must match those of `A` (`size(X, 1) == size(A, 1)` and `size(X, 2) == size(A, 2)`), and `X` must have enough storage to accommodate all allocated entries in `A` (`length(rowvals(X)) >= nnz(A)` and `length(nonzeros(X)) >= nnz(A)`). Column-permutation `q`'s length must match `A`'s column count (`length(q) == size(A, 2)`). Row-permutation `p`'s length must match `A`'s row count (`length(p) == size(A, 1)`).
`C`'s dimensions must match those of `transpose(A)` (`size(C, 1) == size(A, 2)` and `size(C, 2) == size(A, 1)`), and `C` must have enough storage to accommodate all allocated entries in `A` (`length(rowvals(C)) >= nnz(A)` and `length(nonzeros(C)) >= nnz(A)`).
For additional (algorithmic) information, and for versions of these methods that forgo argument checking, see (unexported) parent methods `unchecked_noalias_permute!` and `unchecked_aliasing_permute!`.
See also [`permute`](#SparseArrays.permute).
| programming_docs |
julia Pkg Pkg
===
Pkg is Julia's builtin package manager, and handles operations such as installing, updating and removing packages.
What follows is a very brief introduction to Pkg. For more information on `Project.toml` files, `Manifest.toml` files, package version compatibility (`[compat]`), environments, registries, etc., it is highly recommended to read the full manual, which is available here: <https://pkgdocs.julialang.org>.
What follows is a quick overview of Pkg, Julia's package manager. It should help new users become familiar with basic Pkg features.
Pkg comes with a REPL. Enter the Pkg REPL by pressing `]` from the Julia REPL. To get back to the Julia REPL, press backspace or ^C.
This guide relies on the Pkg REPL to execute Pkg commands. For non-interactive use, we recommend the Pkg API. The Pkg API is fully documented in the [API Reference](https://pkgdocs.julialang.org/v1/api/) section of the Pkg documentation.
Upon entering the Pkg REPL, you should see a similar prompt:
```
(v1.1) pkg>
```
To add a package, use `add`:
```
(v1.1) pkg> add Example
```
Some Pkg output has been omitted in order to keep this guide focused. This will help maintain a good pace and not get bogged down in details. If you require more details, refer to subsequent sections of the Pkg manual.
We can also specify multiple packages at once:
```
(v1.1) pkg> add JSON StaticArrays
```
To remove packages, use `rm`:
```
(v1.1) pkg> rm JSON StaticArrays
```
So far, we have referred only to registered packages. Pkg also supports working with unregistered packages. To add an unregistered package, specify a URL:
```
(v1.1) pkg> add https://github.com/JuliaLang/Example.jl
```
Use `rm` to remove this package by name:
```
(v1.1) pkg> rm Example
```
Use `update` to update an installed package:
```
(v1.1) pkg> update Example
```
To update all installed packages, use `update` without any arguments:
```
(v1.1) pkg> update
```
Up to this point, we have covered basic package management: adding, updating and removing packages. This will be familiar if you have used other package managers. Pkg offers significant advantages over traditional package managers by organizing dependencies into **environments**.
You may have noticed the `(v1.1)` in the REPL prompt. This lets us know `v1.1` is the **active environment**. The active environment is the environment that will be modified by Pkg commands such as `add`, `rm` and `update`.
Let's set up a new environment so we may experiment. To set the active environment, use `activate`:
```
(v1.1) pkg> activate tutorial
[ Info: activating new environment at `/tmp/tutorial/Project.toml`.
```
Pkg lets us know we are creating a new environment and that this environment will be stored in the `/tmp/tutorial` directory.
Pkg has also updated the REPL prompt in order to reflect the new active environment:
```
(tutorial) pkg>
```
We can ask for information about the active environment by using `status`:
```
(tutorial) pkg> status
Status `/tmp/tutorial/Project.toml`
(empty environment)
```
`/tmp/tutorial/Project.toml` is the location of the active environment's **project file**. A project file is where Pkg stores metadata for an environment. Notice this new environment is empty. Let us add a package and observe:
```
(tutorial) pkg> add Example
...
(tutorial) pkg> status
Status `/tmp/tutorial/Project.toml`
[7876af07] Example v0.5.1
```
We can see `tutorial` now contains `Example` as a dependency.
Say we are working on `Example` and feel it needs new functionality. How can we modify the source code? We can use `develop` to set up a git clone of the `Example` package.
```
(tutorial) pkg> develop --local Example
...
(tutorial) pkg> status
Status `/tmp/tutorial/Project.toml`
[7876af07] Example v0.5.1+ [`dev/Example`]
```
Notice the feedback has changed. `dev/Example` refers to the location of the newly created clone. If we look inside the `/tmp/tutorial` directory, we will notice the following files:
```
tutorial
├── dev
│ └── Example
├── Manifest.toml
└── Project.toml
```
Instead of loading a registered version of `Example`, Julia will load the source code contained in `tutorial/dev/Example`.
Let's try it out. First we modify the file at `tutorial/dev/Example/src/Example.jl` and add a simple function:
```
plusone(x::Int) = x + 1
```
Now we can go back to the Julia REPL and load the package:
```
julia> import Example
```
A package can only be loaded once per Julia session. If you have run `import Example` in the current Julia session, you will have to restart Julia and rerun `activate tutorial` in the Pkg REPL. [Revise.jl](https://github.com/timholy/Revise.jl/) can make this process significantly more pleasant, but setting it up is beyond the scope of this guide.
Julia should load our new code. Let's test it:
```
julia> Example.plusone(1)
2
```
Say we have a change of heart and decide the world is not ready for such elegant code. We can tell Pkg to stop using the local clone and use a registered version instead. We do this with `free`:
```
(tutorial) pkg> free Example
```
When you are done experimenting with `tutorial`, you can return to the **default environment** by running `activate` with no arguments:
```
(tutorial) pkg> activate
(v1.1) pkg>
```
If you are ever stuck, you can ask `Pkg` for help:
```
(v1.1) pkg> ?
```
You should see a list of available commands along with short descriptions. You can ask for more detailed help by specifying a command:
```
(v1.1) pkg> ?develop
```
This guide should help you get started with `Pkg`. `Pkg` has much more to offer in terms of powerful package management, read the full manual to learn more!
julia SIMD Support SIMD Support
============
Type `VecElement{T}` is intended for building libraries of SIMD operations. Practical use of it requires using `llvmcall`. The type is defined as:
```
struct VecElement{T}
value::T
end
```
It has a special compilation rule: a homogeneous tuple of `VecElement{T}` maps to an LLVM `vector` type when `T` is a primitive bits type.
At `-O3`, the compiler *might* automatically vectorize operations on such tuples. For example, the following program, when compiled with `julia -O3` generates two SIMD addition instructions (`addps`) on x86 systems:
```
const m128 = NTuple{4,VecElement{Float32}}
function add(a::m128, b::m128)
(VecElement(a[1].value+b[1].value),
VecElement(a[2].value+b[2].value),
VecElement(a[3].value+b[3].value),
VecElement(a[4].value+b[4].value))
end
triple(c::m128) = add(add(c,c),c)
code_native(triple,(m128,))
```
However, since the automatic vectorization cannot be relied upon, future use will mostly be via libraries that use `llvmcall`.
julia Multi-Threading Multi-Threading
===============
###
`Base.Threads.@threads`Macro
```
Threads.@threads [schedule] for ... end
```
A macro to execute a `for` loop in parallel. The iteration space is distributed to coarse-grained tasks. This policy can be specified by the `schedule` argument. The execution of the loop waits for the evaluation of all iterations.
See also: [`@spawn`](#Base.Threads.@spawn) and `pmap` in [`Distributed`](../../stdlib/distributed/index#man-distributed).
**Extended help**
**Semantics**
Unless stronger guarantees are specified by the scheduling option, the loop executed by `@threads` macro have the following semantics.
The `@threads` macro executes the loop body in an unspecified order and potentially concurrently. It does not specify the exact assignments of the tasks and the worker threads. The assignments can be different for each execution. The loop body code (including any code transitively called from it) must not make any assumptions about the distribution of iterations to tasks or the worker thread in which they are executed. The loop body for each iteration must be able to make forward progress independent of other iterations and be free from data races. As such, invalid synchronizations across iterations may deadlock while unsynchronized memory accesses may result in undefined behavior.
For example, the above conditions imply that:
* The lock taken in an iteration *must* be released within the same iteration.
* Communicating between iterations using blocking primitives like `Channel`s is incorrect.
* Write only to locations not shared across iterations (unless a lock or atomic operation is used).
* The value of [`threadid()`](#Base.Threads.threadid) may change even within a single iteration.
**Schedulers**
Without the scheduler argument, the exact scheduling is unspecified and varies across Julia releases. Currently, `:dynamic` is used when the scheduler is not specified.
The `schedule` argument is available as of Julia 1.5.
**`:dynamic` (default)**
`:dynamic` scheduler executes iterations dynamically to available worker threads. Current implementation assumes that the workload for each iteration is uniform. However, this assumption may be removed in the future.
This scheduling option is merely a hint to the underlying execution mechanism. However, a few properties can be expected. The number of `Task`s used by `:dynamic` scheduler is bounded by a small constant multiple of the number of available worker threads ([`nthreads()`](#Base.Threads.nthreads)). Each task processes contiguous regions of the iteration space. Thus, `@threads :dynamic for x in xs; f(x); end` is typically more efficient than `@sync for x in xs; @spawn f(x); end` if `length(xs)` is significantly larger than the number of the worker threads and the run-time of `f(x)` is relatively smaller than the cost of spawning and synchronizaing a task (typically less than 10 microseconds).
The `:dynamic` option for the `schedule` argument is available and the default as of Julia 1.8.
**`:static`**
`:static` scheduler creates one task per thread and divides the iterations equally among them, assigning each task specifically to each thread. In particular, the value of [`threadid()`](#Base.Threads.threadid) is guranteed to be constant within one iteration. Specifying `:static` is an error if used from inside another `@threads` loop or from a thread other than 1.
`:static` scheduling exists for supporting transition of code written before Julia 1.3. In newly written library functions, `:static` scheduling is discouraged because the functions using this option cannot be called from arbitrary worker threads.
**Example**
To illustrate of the different scheduling strategies, consider the following function `busywait` containing a non-yielding timed loop that runs for a given number of seconds.
```
julia> function busywait(seconds)
tstart = time_ns()
while (time_ns() - tstart) / 1e9 < seconds
end
end
julia> @time begin
Threads.@spawn busywait(5)
Threads.@threads :static for i in 1:Threads.nthreads()
busywait(1)
end
end
6.003001 seconds (16.33 k allocations: 899.255 KiB, 0.25% compilation time)
julia> @time begin
Threads.@spawn busywait(5)
Threads.@threads :dynamic for i in 1:Threads.nthreads()
busywait(1)
end
end
2.012056 seconds (16.05 k allocations: 883.919 KiB, 0.66% compilation time)
```
The `:dynamic` example takes 2 seconds since one of the non-occupied threads is able to run two of the 1-second iterations to complete the for loop.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threadingconstructs.jl#L99-L205)###
`Base.Threads.foreach`Function
```
Threads.foreach(f, channel::Channel;
schedule::Threads.AbstractSchedule=Threads.FairSchedule(),
ntasks=Threads.nthreads())
```
Similar to `foreach(f, channel)`, but iteration over `channel` and calls to `f` are split across `ntasks` tasks spawned by `Threads.@spawn`. This function will wait for all internally spawned tasks to complete before returning.
If `schedule isa FairSchedule`, `Threads.foreach` will attempt to spawn tasks in a manner that enables Julia's scheduler to more freely load-balance work items across threads. This approach generally has higher per-item overhead, but may perform better than `StaticSchedule` in concurrence with other multithreaded workloads.
If `schedule isa StaticSchedule`, `Threads.foreach` will spawn tasks in a manner that incurs lower per-item overhead than `FairSchedule`, but is less amenable to load-balancing. This approach thus may be more suitable for fine-grained, uniform workloads, but may perform worse than `FairSchedule` in concurrence with other multithreaded workloads.
This function requires Julia 1.6 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threads_overloads.jl#L3-L25)###
`Base.Threads.@spawn`Macro
```
Threads.@spawn expr
```
Create a [`Task`](../parallel/index#Core.Task) and [`schedule`](../parallel/index#Base.schedule) it to run on any available thread. The task is allocated to a thread after it becomes available. To wait for the task to finish, call [`wait`](../parallel/index#Base.wait) on the result of this macro, or call [`fetch`](#) to wait and then obtain its return value.
Values can be interpolated into `@spawn` via `$`, which copies the value directly into the constructed underlying closure. This allows you to insert the *value* of a variable, isolating the asynchronous code from changes to the variable's value in the current task.
See the manual chapter on threading for important caveats.
This macro is available as of Julia 1.3.
Interpolating values via `$` is available as of Julia 1.4.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threadingconstructs.jl#L234-L254)###
`Base.Threads.threadid`Function
```
Threads.threadid()
```
Get the ID number of the current thread of execution. The master thread has ID `1`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threadingconstructs.jl#L5-L9)###
`Base.Threads.nthreads`Function
```
Threads.nthreads()
```
Get the number of threads available to the Julia process. This is the inclusive upper bound on [`threadid()`](#Base.Threads.threadid).
See also: `BLAS.get_num_threads` and `BLAS.set_num_threads` in the [`LinearAlgebra`](../../stdlib/linearalgebra/index#man-linalg) standard library, and `nprocs()` in the [`Distributed`](../../stdlib/distributed/index#man-distributed) standard library.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threadingconstructs.jl#L13-L22)See also [Multi-Threading](../../manual/multi-threading/index#man-multithreading).
[Atomic operations](#Atomic-operations)
----------------------------------------
###
`Base.@atomic`Macro
```
@atomic var
@atomic order ex
```
Mark `var` or `ex` as being performed atomically, if `ex` is a supported expression.
```
@atomic a.b.x = new
@atomic a.b.x += addend
@atomic :release a.b.x = new
@atomic :acquire_release a.b.x += addend
```
Perform the store operation expressed on the right atomically and return the new value.
With `=`, this operation translates to a `setproperty!(a.b, :x, new)` call. With any operator also, this operation translates to a `modifyproperty!(a.b, :x, +, addend)[2]` call.
```
@atomic a.b.x max arg2
@atomic a.b.x + arg2
@atomic max(a.b.x, arg2)
@atomic :acquire_release max(a.b.x, arg2)
@atomic :acquire_release a.b.x + arg2
@atomic :acquire_release a.b.x max arg2
```
Perform the binary operation expressed on the right atomically. Store the result into the field in the first argument and return the values `(old, new)`.
This operation translates to a `modifyproperty!(a.b, :x, func, arg2)` call.
See [Per-field atomics](../../manual/multi-threading/index#man-atomics) section in the manual for more details.
```
julia> mutable struct Atomic{T}; @atomic x::T; end
julia> a = Atomic(1)
Atomic{Int64}(1)
julia> @atomic a.x # fetch field x of a, with sequential consistency
1
julia> @atomic :sequentially_consistent a.x = 2 # set field x of a, with sequential consistency
2
julia> @atomic a.x += 1 # increment field x of a, with sequential consistency
3
julia> @atomic a.x + 1 # increment field x of a, with sequential consistency
3 => 4
julia> @atomic a.x # fetch field x of a, with sequential consistency
4
julia> @atomic max(a.x, 10) # change field x of a to the max value, with sequential consistency
4 => 10
julia> @atomic a.x max 5 # again change field x of a to the max value, with sequential consistency
10 => 10
```
This functionality requires at least Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L859-L922)###
`Base.@atomicswap`Macro
```
@atomicswap a.b.x = new
@atomicswap :sequentially_consistent a.b.x = new
```
Stores `new` into `a.b.x` and returns the old value of `a.b.x`.
This operation translates to a `swapproperty!(a.b, :x, new)` call.
See [Per-field atomics](../../manual/multi-threading/index#man-atomics) section in the manual for more details.
```
julia> mutable struct Atomic{T}; @atomic x::T; end
julia> a = Atomic(1)
Atomic{Int64}(1)
julia> @atomicswap a.x = 2+2 # replace field x of a with 4, with sequential consistency
1
julia> @atomic a.x # fetch field x of a, with sequential consistency
4
```
This functionality requires at least Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L981-L1006)###
`Base.@atomicreplace`Macro
```
@atomicreplace a.b.x expected => desired
@atomicreplace :sequentially_consistent a.b.x expected => desired
@atomicreplace :sequentially_consistent :monotonic a.b.x expected => desired
```
Perform the conditional replacement expressed by the pair atomically, returning the values `(old, success::Bool)`. Where `success` indicates whether the replacement was completed.
This operation translates to a `replaceproperty!(a.b, :x, expected, desired)` call.
See [Per-field atomics](../../manual/multi-threading/index#man-atomics) section in the manual for more details.
```
julia> mutable struct Atomic{T}; @atomic x::T; end
julia> a = Atomic(1)
Atomic{Int64}(1)
julia> @atomicreplace a.x 1 => 2 # replace field x of a with 2 if it was 1, with sequential consistency
(old = 1, success = true)
julia> @atomic a.x # fetch field x of a, with sequential consistency
2
julia> @atomicreplace a.x 1 => 2 # replace field x of a with 2 if it was 1, with sequential consistency
(old = 2, success = false)
julia> xchg = 2 => 0; # replace field x of a with 0 if it was 1, with sequential consistency
julia> @atomicreplace a.x xchg
(old = 2, success = true)
julia> @atomic a.x # fetch field x of a, with sequential consistency
0
```
This functionality requires at least Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L1024-L1063)
The following APIs are fairly primitive, and will likely be exposed through an `unsafe_*`-like wrapper.
```
Core.Intrinsics.atomic_pointerref(pointer::Ptr{T}, order::Symbol) --> T
Core.Intrinsics.atomic_pointerset(pointer::Ptr{T}, new::T, order::Symbol) --> pointer
Core.Intrinsics.atomic_pointerswap(pointer::Ptr{T}, new::T, order::Symbol) --> old
Core.Intrinsics.atomic_pointermodify(pointer::Ptr{T}, function::(old::T,arg::S)->T, arg::S, order::Symbol) --> old
Core.Intrinsics.atomic_pointerreplace(pointer::Ptr{T}, expected::Any, new::T, success_order::Symbol, failure_order::Symbol) --> (old, cmp)
```
The following APIs are deprecated, though support for them is likely to remain for several releases.
###
`Base.Threads.Atomic`Type
```
Threads.Atomic{T}
```
Holds a reference to an object of type `T`, ensuring that it is only accessed atomically, i.e. in a thread-safe manner.
Only certain "simple" types can be used atomically, namely the primitive boolean, integer, and float-point types. These are `Bool`, `Int8`...`Int128`, `UInt8`...`UInt128`, and `Float16`...`Float64`.
New atomic objects can be created from a non-atomic values; if none is specified, the atomic object is initialized with zero.
Atomic objects can be accessed using the `[]` notation:
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> x[] = 1
1
julia> x[]
1
```
Atomic operations use an `atomic_` prefix, such as [`atomic_add!`](#Base.Threads.atomic_add!), [`atomic_xchg!`](#Base.Threads.atomic_xchg!), etc.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L45-L74)###
`Base.Threads.atomic_cas!`Function
```
Threads.atomic_cas!(x::Atomic{T}, cmp::T, newval::T) where T
```
Atomically compare-and-set `x`
Atomically compares the value in `x` with `cmp`. If equal, write `newval` to `x`. Otherwise, leaves `x` unmodified. Returns the old value in `x`. By comparing the returned value to `cmp` (via `===`) one knows whether `x` was modified and now holds the new value `newval`.
For further details, see LLVM's `cmpxchg` instruction.
This function can be used to implement transactional semantics. Before the transaction, one records the value in `x`. After the transaction, the new value is stored only if `x` has not been modified in the mean time.
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_cas!(x, 4, 2);
julia> x
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_cas!(x, 3, 2);
julia> x
Base.Threads.Atomic{Int64}(2)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L83-L115)###
`Base.Threads.atomic_xchg!`Function
```
Threads.atomic_xchg!(x::Atomic{T}, newval::T) where T
```
Atomically exchange the value in `x`
Atomically exchanges the value in `x` with `newval`. Returns the **old** value.
For further details, see LLVM's `atomicrmw xchg` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_xchg!(x, 2)
3
julia> x[]
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L118-L139)###
`Base.Threads.atomic_add!`Function
```
Threads.atomic_add!(x::Atomic{T}, val::T) where T <: ArithmeticTypes
```
Atomically add `val` to `x`
Performs `x[] += val` atomically. Returns the **old** value. Not defined for `Atomic{Bool}`.
For further details, see LLVM's `atomicrmw add` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_add!(x, 2)
3
julia> x[]
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L142-L163)###
`Base.Threads.atomic_sub!`Function
```
Threads.atomic_sub!(x::Atomic{T}, val::T) where T <: ArithmeticTypes
```
Atomically subtract `val` from `x`
Performs `x[] -= val` atomically. Returns the **old** value. Not defined for `Atomic{Bool}`.
For further details, see LLVM's `atomicrmw sub` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_sub!(x, 2)
3
julia> x[]
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L166-L187)###
`Base.Threads.atomic_and!`Function
```
Threads.atomic_and!(x::Atomic{T}, val::T) where T
```
Atomically bitwise-and `x` with `val`
Performs `x[] &= val` atomically. Returns the **old** value.
For further details, see LLVM's `atomicrmw and` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_and!(x, 2)
3
julia> x[]
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L190-L210)###
`Base.Threads.atomic_nand!`Function
```
Threads.atomic_nand!(x::Atomic{T}, val::T) where T
```
Atomically bitwise-nand (not-and) `x` with `val`
Performs `x[] = ~(x[] & val)` atomically. Returns the **old** value.
For further details, see LLVM's `atomicrmw nand` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(3)
Base.Threads.Atomic{Int64}(3)
julia> Threads.atomic_nand!(x, 2)
3
julia> x[]
-3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L213-L233)###
`Base.Threads.atomic_or!`Function
```
Threads.atomic_or!(x::Atomic{T}, val::T) where T
```
Atomically bitwise-or `x` with `val`
Performs `x[] |= val` atomically. Returns the **old** value.
For further details, see LLVM's `atomicrmw or` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(5)
Base.Threads.Atomic{Int64}(5)
julia> Threads.atomic_or!(x, 7)
5
julia> x[]
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L236-L256)###
`Base.Threads.atomic_xor!`Function
```
Threads.atomic_xor!(x::Atomic{T}, val::T) where T
```
Atomically bitwise-xor (exclusive-or) `x` with `val`
Performs `x[] $= val` atomically. Returns the **old** value.
For further details, see LLVM's `atomicrmw xor` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(5)
Base.Threads.Atomic{Int64}(5)
julia> Threads.atomic_xor!(x, 7)
5
julia> x[]
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L259-L279)###
`Base.Threads.atomic_max!`Function
```
Threads.atomic_max!(x::Atomic{T}, val::T) where T
```
Atomically store the maximum of `x` and `val` in `x`
Performs `x[] = max(x[], val)` atomically. Returns the **old** value.
For further details, see LLVM's `atomicrmw max` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(5)
Base.Threads.Atomic{Int64}(5)
julia> Threads.atomic_max!(x, 7)
5
julia> x[]
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L282-L302)###
`Base.Threads.atomic_min!`Function
```
Threads.atomic_min!(x::Atomic{T}, val::T) where T
```
Atomically store the minimum of `x` and `val` in `x`
Performs `x[] = min(x[], val)` atomically. Returns the **old** value.
For further details, see LLVM's `atomicrmw min` instruction.
**Examples**
```
julia> x = Threads.Atomic{Int}(7)
Base.Threads.Atomic{Int64}(7)
julia> Threads.atomic_min!(x, 5)
7
julia> x[]
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L305-L325)###
`Base.Threads.atomic_fence`Function
```
Threads.atomic_fence()
```
Insert a sequential-consistency memory fence
Inserts a memory fence with sequentially-consistent ordering semantics. There are algorithms where this is needed, i.e. where an acquire/release ordering is insufficient.
This is likely a very expensive operation. Given that all other atomic operations in Julia already have acquire/release semantics, explicit fences should not be necessary in most cases.
For further details, see LLVM's `fence` instruction.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/atomics.jl#L443-L457)
[ccall using a threadpool (Experimental)](#ccall-using-a-threadpool-(Experimental))
------------------------------------------------------------------------------------
###
`Base.@threadcall`Macro
```
@threadcall((cfunc, clib), rettype, (argtypes...), argvals...)
```
The `@threadcall` macro is called in the same way as [`ccall`](../c/index#ccall) but does the work in a different thread. This is useful when you want to call a blocking C function without causing the main `julia` thread to become blocked. Concurrency is limited by size of the libuv thread pool, which defaults to 4 threads but can be increased by setting the `UV_THREADPOOL_SIZE` environment variable and restarting the `julia` process.
Note that the called function should never call back into Julia.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threadcall.jl#L7-L18)
[Low-level synchronization primitives](#Low-level-synchronization-primitives)
------------------------------------------------------------------------------
These building blocks are used to create the regular synchronization objects.
###
`Base.Threads.SpinLock`Type
```
SpinLock()
```
Create a non-reentrant, test-and-test-and-set spin lock. Recursive use will result in a deadlock. This kind of lock should only be used around code that takes little time to execute and does not block (e.g. perform I/O). In general, [`ReentrantLock`](../parallel/index#Base.ReentrantLock) should be used instead.
Each [`lock`](../parallel/index#Base.lock) must be matched with an [`unlock`](../parallel/index#Base.unlock).
Test-and-test-and-set spin locks are quickest up to about 30ish contending threads. If you have more contention than that, different synchronization approaches should be considered.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/locks-mt.jl#L14-L28)
| programming_docs |
julia C Standard Library C Standard Library
==================
###
`Base.Libc.malloc`Function
```
malloc(size::Integer) -> Ptr{Cvoid}
```
Call `malloc` from the C standard library.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L350-L354)###
`Base.Libc.calloc`Function
```
calloc(num::Integer, size::Integer) -> Ptr{Cvoid}
```
Call `calloc` from the C standard library.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L367-L371)###
`Base.Libc.realloc`Function
```
realloc(addr::Ptr, size::Integer) -> Ptr{Cvoid}
```
Call `realloc` from the C standard library.
See warning in the documentation for [`free`](#Base.Libc.free) regarding only using this on memory originally obtained from [`malloc`](#Base.Libc.malloc).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L357-L364)###
`Base.Libc.free`Function
```
free(addr::Ptr)
```
Call `free` from the C standard library. Only use this on memory obtained from [`malloc`](#Base.Libc.malloc), not on pointers retrieved from other C libraries. [`Ptr`](../c/index#Core.Ptr) objects obtained from C libraries should be freed by the free functions defined in that library, to avoid assertion failures if multiple `libc` libraries exist on the system.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L340-L347)###
`Base.Libc.errno`Function
```
errno([code])
```
Get the value of the C library's `errno`. If an argument is specified, it is used to set the value of `errno`.
The value of `errno` is only valid immediately after a `ccall` to a C library routine that sets it. Specifically, you cannot call `errno` at the next prompt in a REPL, because lots of code is executed between prompts.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L280-L289)###
`Base.Libc.strerror`Function
```
strerror(n=errno())
```
Convert a system call error code to a descriptive string
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L293-L297)###
`Base.Libc.GetLastError`Function
```
GetLastError()
```
Call the Win32 `GetLastError` function [only available on Windows].
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L301-L305)###
`Base.Libc.FormatMessage`Function
```
FormatMessage(n=GetLastError())
```
Convert a Win32 system call error code to a descriptive string [only available on Windows].
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L308-L312)###
`Base.Libc.time`Method
```
time(t::TmStruct)
```
Converts a `TmStruct` struct to a number of seconds since the epoch.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L237-L241)###
`Base.Libc.strftime`Function
```
strftime([format], time)
```
Convert time, given as a number of seconds since the epoch or a `TmStruct`, to a formatted string using the given format. Supported formats are the same as those in the standard C library.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L185-L191)###
`Base.Libc.strptime`Function
```
strptime([format], timestr)
```
Parse a formatted time string into a `TmStruct` giving the seconds, minute, hour, date, etc. Supported formats are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the result of this function will be passed to `time` to convert it to seconds since the epoch, the `isdst` field should be filled in manually. Setting it to `-1` will tell the C library to use the current system settings to determine the timezone.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L203-L212)###
`Base.Libc.TmStruct`Type
```
TmStruct([seconds])
```
Convert a number of seconds since the epoch to broken-down format, with fields `sec`, `min`, `hour`, `mday`, `month`, `year`, `wday`, `yday`, and `isdst`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L150-L155)###
`Base.Libc.flush_cstdio`Function
```
flush_cstdio()
```
Flushes the C `stdout` and `stderr` streams (which may have been written to by external C code).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L107-L111)###
`Base.Libc.systemsleep`Function
```
systemsleep(s::Real)
```
Suspends execution for `s` seconds. This function does not yield to Julia's scheduler and therefore blocks the Julia thread that it is running on for the duration of the sleep time.
See also [`sleep`](../parallel/index#Base.sleep).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L127-L135)
julia Strings Strings
=======
###
`Core.AbstractChar`Type
The `AbstractChar` type is the supertype of all character implementations in Julia. A character represents a Unicode code point, and can be converted to an integer via the [`codepoint`](#Base.codepoint) function in order to obtain the numerical value of the code point, or constructed from the same integer. These numerical values determine how characters are compared with `<` and `==`, for example. New `T <: AbstractChar` types should define a `codepoint(::T)` method and a `T(::UInt32)` constructor, at minimum.
A given `AbstractChar` subtype may be capable of representing only a subset of Unicode, in which case conversion from an unsupported `UInt32` value may throw an error. Conversely, the built-in [`Char`](#Core.Char) type represents a *superset* of Unicode (in order to losslessly encode invalid byte streams), in which case conversion of a non-Unicode value *to* `UInt32` throws an error. The [`isvalid`](#Base.isvalid-Tuple%7BAny%7D) function can be used to check which codepoints are representable in a given `AbstractChar` type.
Internally, an `AbstractChar` type may use a variety of encodings. Conversion via `codepoint(char)` will not reveal this encoding because it always returns the Unicode value of the character. `print(io, c)` of any `c::AbstractChar` produces an encoding determined by `io` (UTF-8 for all built-in `IO` types), via conversion to `Char` if necessary.
`write(io, c)`, in contrast, may emit an encoding depending on `typeof(c)`, and `read(io, typeof(c))` should read the same encoding as `write`. New `AbstractChar` types must provide their own implementations of `write` and `read`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/char.jl#L3-L30)###
`Core.Char`Type
```
Char(c::Union{Number,AbstractChar})
```
`Char` is a 32-bit [`AbstractChar`](#Core.AbstractChar) type that is the default representation of characters in Julia. `Char` is the type used for character literals like `'x'` and it is also the element type of [`String`](#Core.String-Tuple%7BAbstractString%7D).
In order to losslessly represent arbitrary byte streams stored in a `String`, a `Char` value may store information that cannot be converted to a Unicode codepoint — converting such a `Char` to `UInt32` will throw an error. The [`isvalid(c::Char)`](#Base.isvalid-Tuple%7BAny%7D) function can be used to query whether `c` represents a valid Unicode character.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/char.jl#L33-L45)###
`Base.codepoint`Function
```
codepoint(c::AbstractChar) -> Integer
```
Return the Unicode codepoint (an unsigned integer) corresponding to the character `c` (or throw an exception if `c` does not represent a valid character). For `Char`, this is a `UInt32` value, but `AbstractChar` types that represent only a subset of Unicode may return a different-sized integer (e.g. `UInt8`).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/char.jl#L67-L75)###
`Base.length`Method
```
length(s::AbstractString) -> Int
length(s::AbstractString, i::Integer, j::Integer) -> Int
```
Return the number of characters in string `s` from indices `i` through `j`.
This is computed as the number of code unit indices from `i` to `j` which are valid character indices. With only a single string argument, this computes the number of characters in the entire string. With `i` and `j` arguments it computes the number of indices between `i` and `j` inclusive that are valid indices in the string `s`. In addition to in-bounds values, `i` may take the out-of-bounds value `ncodeunits(s) + 1` and `j` may take the out-of-bounds value `0`.
The time complexity of this operation is linear in general. That is, it will take the time proportional to the number of bytes or characters in the string because it counts the value on the fly. This is in contrast to the method for arrays, which is a constant-time operation.
See also [`isvalid`](#Base.isvalid-Tuple%7BAny%7D), [`ncodeunits`](#Base.ncodeunits-Tuple%7BAbstractString%7D), [`lastindex`](../collections/index#Base.lastindex), [`thisind`](#Base.thisind), [`nextind`](#Base.nextind), [`prevind`](#Base.prevind).
**Examples**
```
julia> length("jμΛIα")
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L358-L386)###
`Base.sizeof`Method
```
sizeof(str::AbstractString)
```
Size, in bytes, of the string `str`. Equal to the number of code units in `str` multiplied by the size, in bytes, of one code unit in `str`.
**Examples**
```
julia> sizeof("")
0
julia> sizeof("∀")
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L164-L178)###
`Base.:*`Method
```
*(s::Union{AbstractString, AbstractChar}, t::Union{AbstractString, AbstractChar}...) -> AbstractString
```
Concatenate strings and/or characters, producing a [`String`](#Core.String-Tuple%7BAbstractString%7D). This is equivalent to calling the [`string`](#Base.string) function on the arguments. Concatenation of built-in string types always produces a value of type `String` but other string types may choose to return a string of a different type as appropriate.
**Examples**
```
julia> "Hello " * "world"
"Hello world"
julia> 'j' * "ulia"
"julia"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L243-L259)###
`Base.:^`Method
```
^(s::Union{AbstractString,AbstractChar}, n::Integer)
```
Repeat a string or character `n` times. This can also be written as `repeat(s, n)`.
See also [`repeat`](../arrays/index#Base.repeat).
**Examples**
```
julia> "Test "^3
"Test Test Test "
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L717-L729)###
`Base.string`Function
```
string(n::Integer; base::Integer = 10, pad::Integer = 1)
```
Convert an integer `n` to a string in the given `base`, optionally specifying a number of digits to pad to.
See also [`digits`](../numbers/index#Base.digits), [`bitstring`](../numbers/index#Base.bitstring), [`count_zeros`](../numbers/index#Base.count_zeros).
**Examples**
```
julia> string(5, base = 13, pad = 4)
"0005"
julia> string(-13, base = 5, pad = 4)
"-0023"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L774-L790)
```
string(xs...)
```
Create a string from any values using the [`print`](../io-network/index#Base.print) function.
`string` should usually not be defined directly. Instead, define a method `print(io::IO, x::MyType)`. If `string(x)` for a certain type needs to be highly efficient, then it may make sense to add a method to `string` and define `print(io::IO, x::MyType) = print(io, string(x))` to ensure the functions are consistent.
See also: [`String`](#Core.String-Tuple%7BAbstractString%7D), [`repr`](#), [`sprint`](../io-network/index#Base.sprint), [`show`](../base/index#Base.@show).
**Examples**
```
julia> string("a", 1, true)
"a1true"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L166-L184)###
`Base.repeat`Method
```
repeat(s::AbstractString, r::Integer)
```
Repeat a string `r` times. This can be written as `s^r`.
See also [`^`](#Base.:%5E-Tuple%7BUnion%7BAbstractChar,%20AbstractString%7D,%20Integer%7D).
**Examples**
```
julia> repeat("ha", 3)
"hahaha"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L702-L714)###
`Base.repeat`Method
```
repeat(c::AbstractChar, r::Integer) -> String
```
Repeat a character `r` times. This can equivalently be accomplished by calling [`c^r`](#Base.:%5E-Tuple%7BUnion%7BAbstractChar,%20AbstractString%7D,%20Integer%7D).
**Examples**
```
julia> repeat('A', 3)
"AAA"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/string.jl#L325-L336)###
`Base.repr`Method
```
repr(x; context=nothing)
```
Create a string from any value using the [`show`](#) function. You should not add methods to `repr`; define a `show` method instead.
The optional keyword argument `context` can be set to a `:key=>value` pair, a tuple of `:key=>value` pairs, or an `IO` or [`IOContext`](../io-network/index#Base.IOContext) object whose attributes are used for the I/O stream passed to `show`.
Note that `repr(x)` is usually similar to how the value of `x` would be entered in Julia. See also [`repr(MIME("text/plain"), x)`](#) to instead return a "pretty-printed" version of `x` designed more for human consumption, equivalent to the REPL display of `x`.
Passing a tuple to keyword `context` requires Julia 1.7 or later.
**Examples**
```
julia> repr(1)
"1"
julia> repr(zeros(3))
"[0.0, 0.0, 0.0]"
julia> repr(big(1/3))
"0.333333333333333314829616256247390992939472198486328125"
julia> repr(big(1/3), context=:compact => true)
"0.333333"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L248-L281)###
`Core.String`Method
```
String(s::AbstractString)
```
Convert a string to a contiguous byte array representation encoded as UTF-8 bytes. This representation is often appropriate for passing strings to C.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/string.jl#L80-L85)###
`Base.SubString`Type
```
SubString(s::AbstractString, i::Integer, j::Integer=lastindex(s))
SubString(s::AbstractString, r::UnitRange{<:Integer})
```
Like [`getindex`](../collections/index#Base.getindex), but returns a view into the parent string `s` within range `i:j` or `r` respectively instead of making a copy.
**Examples**
```
julia> SubString("abc", 1, 2)
"ab"
julia> SubString("abc", 1:2)
"ab"
julia> SubString("abc", 2)
"bc"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/substring.jl#L3-L21)###
`Base.transcode`Function
```
transcode(T, src)
```
Convert string data between Unicode encodings. `src` is either a `String` or a `Vector{UIntXX}` of UTF-XX code units, where `XX` is 8, 16, or 32. `T` indicates the encoding of the return value: `String` to return a (UTF-8 encoded) `String` or `UIntXX` to return a `Vector{UIntXX}` of UTF-`XX` data. (The alias [`Cwchar_t`](../c/index#Base.Cwchar_t) can also be used as the integer type, for converting `wchar_t*` strings used by external C libraries.)
The `transcode` function succeeds as long as the input data can be reasonably represented in the target encoding; it always succeeds for conversions between UTF-XX encodings, even for invalid Unicode data.
Only conversion to/from UTF-8 is currently supported.
**Examples**
```
julia> str = "αβγ"
"αβγ"
julia> transcode(UInt16, str)
3-element Vector{UInt16}:
0x03b1
0x03b2
0x03b3
julia> transcode(String, transcode(UInt16, str))
"αβγ"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L257-L288)###
`Base.unsafe_string`Function
```
unsafe_string(p::Ptr{UInt8}, [length::Integer])
```
Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8. (The pointer can be safely freed afterwards.) If `length` is specified (the length of the data in bytes), the string does not have to be NUL-terminated.
This function is labeled "unsafe" because it will crash if `p` is not a valid memory address to data of the requested length.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/string.jl#L57-L66)###
`Base.ncodeunits`Method
```
ncodeunits(s::AbstractString) -> Int
```
Return the number of code units in a string. Indices that are in bounds to access this string must satisfy `1 ≤ i ≤ ncodeunits(s)`. Not all such indices are valid – they may not be the start of a character, but they will return a code unit value when calling `codeunit(s,i)`.
**Examples**
```
julia> ncodeunits("The Julia Language")
18
julia> ncodeunits("∫eˣ")
6
julia> ncodeunits('∫'), ncodeunits('e'), ncodeunits('ˣ')
(3, 1, 2)
```
See also [`codeunit`](#Base.codeunit), [`checkbounds`](../arrays/index#Base.checkbounds), [`sizeof`](#), [`length`](../collections/index#Base.length), [`lastindex`](../collections/index#Base.lastindex).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L45-L67)###
`Base.codeunit`Function
```
codeunit(s::AbstractString) -> Type{<:Union{UInt8, UInt16, UInt32}}
```
Return the code unit type of the given string object. For ASCII, Latin-1, or UTF-8 encoded strings, this would be `UInt8`; for UCS-2 and UTF-16 it would be `UInt16`; for UTF-32 it would be `UInt32`. The code unit type need not be limited to these three types, but it's hard to think of widely used string encodings that don't use one of these units. `codeunit(s)` is the same as `typeof(codeunit(s,1))` when `s` is a non-empty string.
See also [`ncodeunits`](#Base.ncodeunits-Tuple%7BAbstractString%7D).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L70-L81)
```
codeunit(s::AbstractString, i::Integer) -> Union{UInt8, UInt16, UInt32}
```
Return the code unit value in the string `s` at index `i`. Note that
```
codeunit(s, i) :: codeunit(s)
```
I.e. the value returned by `codeunit(s, i)` is of the type returned by `codeunit(s)`.
**Examples**
```
julia> a = codeunit("Hello", 2)
0x65
julia> typeof(a)
UInt8
```
See also [`ncodeunits`](#Base.ncodeunits-Tuple%7BAbstractString%7D), [`checkbounds`](../arrays/index#Base.checkbounds).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L86-L106)###
`Base.codeunits`Function
```
codeunits(s::AbstractString)
```
Obtain a vector-like object containing the code units of a string. Returns a `CodeUnits` wrapper by default, but `codeunits` may optionally be defined for new string types if necessary.
**Examples**
```
julia> codeunits("Juλia")
6-element Base.CodeUnits{UInt8, String}:
0x4a
0x75
0xce
0xbb
0x69
0x61
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L763-L781)###
`Base.ascii`Function
```
ascii(s::AbstractString)
```
Convert a string to `String` type and check that it contains only ASCII data, otherwise throwing an `ArgumentError` indicating the position of the first non-ASCII byte.
See also the [`isascii`](#Base.isascii) predicate to filter or replace non-ASCII characters.
**Examples**
```
julia> ascii("abcdeγfgh")
ERROR: ArgumentError: invalid ASCII at index 6 in "abcdeγfgh"
Stacktrace:
[...]
julia> ascii("abcdefgh")
"abcdefgh"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L926-L944)###
`Base.Regex`Type
```
Regex(pattern[, flags])
```
A type representing a regular expression. `Regex` objects can be used to match strings with [`match`](#Base.match).
`Regex` objects can be created using the [`@r_str`](#Base.@r_str) string macro. The `Regex(pattern[, flags])` constructor is usually used if the `pattern` string needs to be interpolated. See the documentation of the string macro for details on flags.
To escape interpolated variables use `\Q` and `\E` (e.g. `Regex("\\Q$x\\E")`)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L17-L29)###
`Base.@r_str`Macro
```
@r_str -> Regex
```
Construct a regex, such as `r"^[a-z]*$"`, without interpolation and unescaping (except for quotation mark `"` which still has to be escaped). The regex also accepts one or more flags, listed after the ending quote, to change its behaviour:
* `i` enables case-insensitive matching
* `m` treats the `^` and `$` tokens as matching the start and end of individual lines, as opposed to the whole string.
* `s` allows the `.` modifier to match newlines.
* `x` enables "comment mode": whitespace is enabled except when escaped with `\`, and `#` is treated as starting a comment.
* `a` disables `UCP` mode (enables ASCII mode). By default `\B`, `\b`, `\D`, `\d`, `\S`, `\s`, `\W`, `\w`, etc. match based on Unicode character properties. With this option, these sequences only match ASCII characters.
See [`Regex`](#Base.Regex) if interpolation is needed.
**Examples**
```
julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
RegexMatch("angry,\nBad world")
```
This regex has the first three flags enabled.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L93-L118)###
`Base.SubstitutionString`Type
```
SubstitutionString(substr)
```
Stores the given string `substr` as a `SubstitutionString`, for use in regular expression substitutions. Most commonly constructed using the [`@s_str`](#Base.@s_str) macro.
**Examples**
```
julia> SubstitutionString("Hello \\g<name>, it's \\1")
s"Hello \g<name>, it's \1"
julia> subst = s"Hello \g<name>, it's \1"
s"Hello \g<name>, it's \1"
julia> typeof(subst)
SubstitutionString{String}
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L539-L558)###
`Base.@s_str`Macro
```
@s_str -> SubstitutionString
```
Construct a substitution string, used for regular expression substitutions. Within the string, sequences of the form `\N` refer to the Nth capture group in the regex, and `\g<groupname>` refers to a named capture group with name `groupname`.
**Examples**
```
julia> msg = "#Hello# from Julia";
julia> replace(msg, r"#(.+)# from (?<from>\w+)" => s"FROM: \g<from>; MESSAGE: \1")
"FROM: Julia; MESSAGE: Hello"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L575-L589)###
`Base.@raw_str`Macro
```
@raw_str -> String
```
Create a raw string without interpolation and unescaping. The exception is that quotation marks still must be escaped. Backslashes escape both quotation marks and other backslashes, but only when a sequence of backslashes precedes a quote character. Thus, 2n backslashes followed by a quote encodes n backslashes and the end of the literal while 2n+1 backslashes followed by a quote encodes n backslashes followed by a quote character.
**Examples**
```
julia> println(raw"\ $x")
\ $x
julia> println(raw"\"")
"
julia> println(raw"\\\"")
\"
julia> println(raw"\\x \\\"")
\\x \"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L561-L585)###
`Base.@b_str`Macro
```
@b_str
```
Create an immutable byte (`UInt8`) vector using string syntax.
**Examples**
```
julia> v = b"12\x01\x02"
4-element Base.CodeUnits{UInt8, String}:
0x31
0x32
0x01
0x02
julia> v[2]
0x32
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L538-L555)###
`Base.Docs.@html_str`Macro
```
@html_str -> Docs.HTML
```
Create an `HTML` object from a literal string.
**Examples**
```
julia> html"Julia"
HTML{String}("Julia")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/utils.jl#L44-L54)###
`Base.Docs.@text_str`Macro
```
@text_str -> Docs.Text
```
Create a `Text` object from a literal string.
**Examples**
```
julia> text"Julia"
Julia
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/utils.jl#L98-L108)###
`Base.isvalid`Method
```
isvalid(value) -> Bool
```
Returns `true` if the given value is valid for its type, which currently can be either `AbstractChar` or `String` or `SubString{String}`.
**Examples**
```
julia> isvalid(Char(0xd800))
false
julia> isvalid(SubString(String(UInt8[0xfe,0x80,0x80,0x80,0x80,0x80]),1,2))
false
julia> isvalid(Char(0xd799))
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L11-L28)###
`Base.isvalid`Method
```
isvalid(T, value) -> Bool
```
Returns `true` if the given value is valid for that type. Types currently can be either `AbstractChar` or `String`. Values for `AbstractChar` can be of type `AbstractChar` or [`UInt32`](../numbers/index#Core.UInt32). Values for `String` can be of that type, `SubString{String}`, `Vector{UInt8}`, or a contiguous subarray thereof.
**Examples**
```
julia> isvalid(Char, 0xd800)
false
julia> isvalid(String, SubString("thisisvalid",1,5))
true
julia> isvalid(Char, 0xd799)
true
```
Support for subarray values was added in Julia 1.6.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L31-L53)###
`Base.isvalid`Method
```
isvalid(s::AbstractString, i::Integer) -> Bool
```
Predicate indicating whether the given index is the start of the encoding of a character in `s` or not. If `isvalid(s, i)` is true then `s[i]` will return the character whose encoding starts at that index, if it's false, then `s[i]` will raise an invalid index error or a bounds error depending on if `i` is in bounds. In order for `isvalid(s, i)` to be an O(1) function, the encoding of `s` must be [self-synchronizing](https://en.wikipedia.org/wiki/Self-synchronizing_code). This is a basic assumption of Julia's generic string support.
See also [`getindex`](../collections/index#Base.getindex), [`iterate`](../collections/index#Base.iterate), [`thisind`](#Base.thisind), [`nextind`](#Base.nextind), [`prevind`](#Base.prevind), [`length`](../collections/index#Base.length).
**Examples**
```
julia> str = "αβγdef";
julia> isvalid(str, 1)
true
julia> str[1]
'α': Unicode U+03B1 (category Ll: Letter, lowercase)
julia> isvalid(str, 2)
false
julia> str[2]
ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'α', [3]=>'β'
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L110-L142)###
`Base.match`Function
```
match(r::Regex, s::AbstractString[, idx::Integer[, addopts]])
```
Search for the first match of the regular expression `r` in `s` and return a [`RegexMatch`](#Base.RegexMatch) object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing `m.match` and the captured sequences can be retrieved by accessing `m.captures` The optional `idx` argument specifies an index at which to start the search.
**Examples**
```
julia> rx = r"a(.)a"
r"a(.)a"
julia> m = match(rx, "cabac")
RegexMatch("aba", 1="b")
julia> m.captures
1-element Vector{Union{Nothing, SubString{String}}}:
"b"
julia> m.match
"aba"
julia> match(rx, "cabac", 3) === nothing
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L352-L378)###
`Base.eachmatch`Function
```
eachmatch(r::Regex, s::AbstractString; overlap::Bool=false)
```
Search for all matches of the regular expression `r` in `s` and return an iterator over the matches. If `overlap` is `true`, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.
**Examples**
```
julia> rx = r"a.a"
r"a.a"
julia> m = eachmatch(rx, "a1a2a3a")
Base.RegexMatchIterator(r"a.a", "a1a2a3a", false)
julia> collect(m)
2-element Vector{RegexMatch}:
RegexMatch("a1a")
RegexMatch("a3a")
julia> collect(eachmatch(rx, "a1a2a3a", overlap = true))
3-element Vector{RegexMatch}:
RegexMatch("a1a")
RegexMatch("a2a")
RegexMatch("a3a")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L730-L756)###
`Base.RegexMatch`Type
```
RegexMatch
```
A type representing a single match to a `Regex` found in a string. Typically created from the [`match`](#Base.match) function.
The `match` field stores the substring of the entire matched string. The `captures` field stores the substrings for each capture group, indexed by number. To index by capture group name, the entire match object should be indexed instead, as shown in the examples. The location of the start of the match is stored in the `offset` field. The `offsets` field stores the locations of the start of each capture group, with 0 denoting a group that was not captured.
This type can be used as an iterator over the capture groups of the `Regex`, yielding the substrings captured in each group. Because of this, the captures of a match can be destructured. If a group was not captured, `nothing` will be yielded instead of a substring.
Methods that accept a `RegexMatch` object are defined for [`iterate`](../collections/index#Base.iterate), [`length`](../collections/index#Base.length), [`eltype`](../collections/index#Base.eltype), [`keys`](#Base.keys-Tuple%7BRegexMatch%7D), [`haskey`](../collections/index#Base.haskey), and [`getindex`](../collections/index#Base.getindex), where keys are the the names or numbers of a capture group. See [`keys`](#Base.keys-Tuple%7BRegexMatch%7D) for more information.
**Examples**
```
julia> m = match(r"(?<hour>\d+):(?<minute>\d+)(am|pm)?", "11:30 in the morning")
RegexMatch("11:30", hour="11", minute="30", 3=nothing)
julia> hr, min, ampm = m;
julia> hr
"11"
julia> m["minute"]
"30"
julia> m.match
"11:30"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L148-L188)###
`Base.keys`Method
```
keys(m::RegexMatch) -> Vector
```
Return a vector of keys for all capture groups of the underlying regex. A key is included even if the capture group fails to match. That is, `idx` will be in the return value even if `m[idx] == nothing`.
Unnamed capture groups will have integer keys corresponding to their index. Named capture groups will have string keys.
This method was added in Julia 1.6
**Examples**
```
julia> keys(match(r"(?<hour>\d+):(?<minute>\d+)(am|pm)?", "11:30"))
3-element Vector{Any}:
"hour"
"minute"
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L197-L218)###
`Base.isless`Method
```
isless(a::AbstractString, b::AbstractString) -> Bool
```
Test whether string `a` comes before string `b` in alphabetical order (technically, in lexicographical order by Unicode code points).
**Examples**
```
julia> isless("a", "b")
true
julia> isless("β", "α")
false
julia> isless("a", "a")
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L326-L343)###
`Base.:==`Method
```
==(a::AbstractString, b::AbstractString) -> Bool
```
Test whether two strings are equal character by character (technically, Unicode code point by code point).
**Examples**
```
julia> "abc" == "abc"
true
julia> "abc" == "αβγ"
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L309-L323)###
`Base.cmp`Method
```
cmp(a::AbstractString, b::AbstractString) -> Int
```
Compare two strings. Return `0` if both strings have the same length and the character at each index is the same in both strings. Return `-1` if `a` is a prefix of `b`, or if `a` comes before `b` in alphabetical order. Return `1` if `b` is a prefix of `a`, or if `b` comes before `a` in alphabetical order (technically, lexicographical order by Unicode code points).
**Examples**
```
julia> cmp("abc", "abc")
0
julia> cmp("ab", "abc")
-1
julia> cmp("abc", "ab")
1
julia> cmp("ab", "ac")
-1
julia> cmp("ac", "ab")
1
julia> cmp("α", "a")
1
julia> cmp("b", "β")
-1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L266-L298)###
`Base.lpad`Function
```
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String
```
Stringify `s` and pad the resulting string on the left with `p` to make it `n` characters (in [`textwidth`](#Base.Unicode.textwidth)) long. If `s` is already `n` characters long, an equal string is returned. Pad with spaces by default.
**Examples**
```
julia> lpad("March", 10)
" March"
```
In Julia 1.7, this function was changed to use `textwidth` rather than a raw character (codepoint) count.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L421-L435)###
`Base.rpad`Function
```
rpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String
```
Stringify `s` and pad the resulting string on the right with `p` to make it `n` characters (in [`textwidth`](#Base.Unicode.textwidth)) long. If `s` is already `n` characters long, an equal string is returned. Pad with spaces by default.
**Examples**
```
julia> rpad("March", 20)
"March "
```
In Julia 1.7, this function was changed to use `textwidth` rather than a raw character (codepoint) count.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L451-L465)###
`Base.findfirst`Method
```
findfirst(pattern::AbstractString, string::AbstractString)
findfirst(pattern::AbstractPattern, string::String)
```
Find the first occurrence of `pattern` in `string`. Equivalent to [`findnext(pattern, string, firstindex(s))`](#).
**Examples**
```
julia> findfirst("z", "Hello to the world") # returns nothing, but not printed in the REPL
julia> findfirst("Julia", "JuliaLang")
1:5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L95-L109)###
`Base.findnext`Method
```
findnext(pattern::AbstractString, string::AbstractString, start::Integer)
findnext(pattern::AbstractPattern, string::String, start::Integer)
```
Find the next occurrence of `pattern` in `string` starting at position `start`. `pattern` can be either a string, or a regular expression, in which case `string` must be of type `String`.
The return value is a range of indices where the matching sequence is found, such that `s[findnext(x, s, i)] == x`:
`findnext("substring", string, i)` == `start:stop` such that `string[start:stop] == "substring"` and `i <= start`, or `nothing` if unmatched.
**Examples**
```
julia> findnext("z", "Hello to the world", 1) === nothing
true
julia> findnext("o", "Hello to the world", 6)
8:8
julia> findnext("Lang", "JuliaLang", 2)
6:9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L283-L308)###
`Base.findnext`Method
```
findnext(ch::AbstractChar, string::AbstractString, start::Integer)
```
Find the next occurrence of character `ch` in `string` starting at position `start`.
This method requires at least Julia 1.3.
**Examples**
```
julia> findnext('z', "Hello to the world", 1) === nothing
true
julia> findnext('o', "Hello to the world", 6)
8
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L311-L327)###
`Base.findlast`Method
```
findlast(pattern::AbstractString, string::AbstractString)
```
Find the last occurrence of `pattern` in `string`. Equivalent to [`findprev(pattern, string, lastindex(string))`](#).
**Examples**
```
julia> findlast("o", "Hello to the world")
15:15
julia> findfirst("Julia", "JuliaLang")
1:5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L355-L369)###
`Base.findlast`Method
```
findlast(ch::AbstractChar, string::AbstractString)
```
Find the last occurrence of character `ch` in `string`.
This method requires at least Julia 1.3.
**Examples**
```
julia> findlast('p', "happy")
4
julia> findlast('z', "happy") === nothing
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L390-L406)###
`Base.findprev`Method
```
findprev(pattern::AbstractString, string::AbstractString, start::Integer)
```
Find the previous occurrence of `pattern` in `string` starting at position `start`.
The return value is a range of indices where the matching sequence is found, such that `s[findprev(x, s, i)] == x`:
`findprev("substring", string, i)` == `start:stop` such that `string[start:stop] == "substring"` and `stop <= i`, or `nothing` if unmatched.
**Examples**
```
julia> findprev("z", "Hello to the world", 18) === nothing
true
julia> findprev("o", "Hello to the world", 18)
15:15
julia> findprev("Julia", "JuliaLang", 6)
1:5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L540-L562)###
`Base.occursin`Function
```
occursin(needle::Union{AbstractString,AbstractPattern,AbstractChar}, haystack::AbstractString)
```
Determine whether the first argument is a substring of the second. If `needle` is a regular expression, checks whether `haystack` contains a match.
**Examples**
```
julia> occursin("Julia", "JuliaLang is pretty cool!")
true
julia> occursin('a', "JuliaLang is pretty cool!")
true
julia> occursin(r"a.a", "aba")
true
julia> occursin(r"a.a", "abba")
false
```
See also [`contains`](#Base.contains).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L605-L627)
```
occursin(haystack)
```
Create a function that checks whether its argument occurs in `haystack`, i.e. a function equivalent to `needle -> occursin(needle, haystack)`.
The returned function is of type `Base.Fix2{typeof(occursin)}`.
This method requires Julia 1.6 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/search.jl#L631-L641)###
`Base.reverse`Method
```
reverse(s::AbstractString) -> AbstractString
```
Reverses a string. Technically, this function reverses the codepoints in a string and its main utility is for reversed-order string processing, especially for reversed regular-expression searches. See also [`reverseind`](../arrays/index#Base.reverseind) to convert indices in `s` to indices in `reverse(s)` and vice-versa, and `graphemes` from module `Unicode` to operate on user-visible "characters" (graphemes) rather than codepoints. See also [`Iterators.reverse`](../iterators/index#Base.Iterators.reverse) for reverse-order iteration without making a copy. Custom string types must implement the `reverse` function themselves and should typically return a string with the same type and encoding. If they return a string with a different encoding, they must also override `reverseind` for that string type to satisfy `s[reverseind(s,i)] == reverse(s)[i]`.
**Examples**
```
julia> reverse("JuliaLang")
"gnaLailuJ"
```
The examples below may be rendered differently on different systems. The comments indicate how they're supposed to be rendered
Combining characters can lead to surprising results:
```
julia> reverse("ax̂e") # hat is above x in the input, above e in the output
"êxa"
julia> using Unicode
julia> join(reverse(collect(graphemes("ax̂e")))) # reverses graphemes; hat is above x in both in- and output
"ex̂a"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/substring.jl#L135-L170)###
`Base.replace`Method
```
replace(s::AbstractString, pat=>r, [pat2=>r2, ...]; [count::Integer])
```
Search for the given pattern `pat` in `s`, and replace each occurrence with `r`. If `count` is provided, replace at most `count` occurrences. `pat` may be a single character, a vector or a set of characters, a string, or a regular expression. If `r` is a function, each occurrence is replaced with `r(s)` where `s` is the matched substring (when `pat` is a `AbstractPattern` or `AbstractString`) or character (when `pat` is an `AbstractChar` or a collection of `AbstractChar`). If `pat` is a regular expression and `r` is a [`SubstitutionString`](#Base.SubstitutionString), then capture group references in `r` are replaced with the corresponding matched text. To remove instances of `pat` from `string`, set `r` to the empty `String` (`""`).
Multiple patterns can be specified, and they will be applied left-to-right simultaneously, so only one pattern will be applied to any character, and the patterns will only be applied to the input text, not the replacements.
Support for multiple patterns requires version 1.7.
**Examples**
```
julia> replace("Python is a programming language.", "Python" => "Julia")
"Julia is a programming language."
julia> replace("The quick foxes run quickly.", "quick" => "slow", count=1)
"The slow foxes run quickly."
julia> replace("The quick foxes run quickly.", "quick" => "", count=1)
"The foxes run quickly."
julia> replace("The quick foxes run quickly.", r"fox(es)?" => s"bus\1")
"The quick buses run quickly."
julia> replace("abcabc", "a" => "b", "b" => "c", r".+" => "a")
"bca"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L736-L774)###
`Base.eachsplit`Function
```
eachsplit(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
eachsplit(str::AbstractString; limit::Integer=0, keepempty::Bool=false)
```
Split `str` on occurrences of the delimiter(s) `dlm` and return an iterator over the substrings. `dlm` can be any of the formats allowed by [`findnext`](#)'s first argument (i.e. as a string, regular expression or a function), or as a single character or collection of characters.
If `dlm` is omitted, it defaults to [`isspace`](#Base.Unicode.isspace).
The optional keyword arguments are:
* `limit`: the maximum size of the result. `limit=0` implies no maximum (default)
* `keepempty`: whether empty fields should be kept in the result. Default is `false` without a `dlm` argument, `true` with a `dlm` argument.
See also [`split`](#Base.split).
The `eachsplit` function requires at least Julia 1.8.
**Examples**
```
julia> a = "Ma.rch"
"Ma.rch"
julia> collect(eachsplit(a, "."))
2-element Vector{SubString}:
"Ma"
"rch"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L481-L512)###
`Base.split`Function
```
split(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
split(str::AbstractString; limit::Integer=0, keepempty::Bool=false)
```
Split `str` into an array of substrings on occurrences of the delimiter(s) `dlm`. `dlm` can be any of the formats allowed by [`findnext`](#)'s first argument (i.e. as a string, regular expression or a function), or as a single character or collection of characters.
If `dlm` is omitted, it defaults to [`isspace`](#Base.Unicode.isspace).
The optional keyword arguments are:
* `limit`: the maximum size of the result. `limit=0` implies no maximum (default)
* `keepempty`: whether empty fields should be kept in the result. Default is `false` without a `dlm` argument, `true` with a `dlm` argument.
See also [`rsplit`](#Base.rsplit), [`eachsplit`](#Base.eachsplit).
**Examples**
```
julia> a = "Ma.rch"
"Ma.rch"
julia> split(a, ".")
2-element Vector{SubString{String}}:
"Ma"
"rch"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L563-L591)###
`Base.rsplit`Function
```
rsplit(s::AbstractString; limit::Integer=0, keepempty::Bool=false)
rsplit(s::AbstractString, chars; limit::Integer=0, keepempty::Bool=true)
```
Similar to [`split`](#Base.split), but starting from the end of the string.
**Examples**
```
julia> a = "M.a.r.c.h"
"M.a.r.c.h"
julia> rsplit(a, ".")
5-element Vector{SubString{String}}:
"M"
"a"
"r"
"c"
"h"
julia> rsplit(a, "."; limit=1)
1-element Vector{SubString{String}}:
"M.a.r.c.h"
julia> rsplit(a, "."; limit=2)
2-element Vector{SubString{String}}:
"M.a.r.c"
"h"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L603-L631)###
`Base.strip`Function
```
strip([pred=isspace,] str::AbstractString) -> SubString
strip(str::AbstractString, chars) -> SubString
```
Remove leading and trailing characters from `str`, either those specified by `chars` or those for which the function `pred` returns `true`.
The default behaviour is to remove leading and trailing whitespace and delimiters: see [`isspace`](#Base.Unicode.isspace) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single character, vector or set of characters.
See also [`lstrip`](#Base.lstrip) and [`rstrip`](#Base.rstrip).
The method which accepts a predicate function requires Julia 1.2 or later.
**Examples**
```
julia> strip("{3, 5}\n", ['{', '}', '\n'])
"3, 5"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L391-L414)###
`Base.lstrip`Function
```
lstrip([pred=isspace,] str::AbstractString) -> SubString
lstrip(str::AbstractString, chars) -> SubString
```
Remove leading characters from `str`, either those specified by `chars` or those for which the function `pred` returns `true`.
The default behaviour is to remove leading whitespace and delimiters: see [`isspace`](#Base.Unicode.isspace) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single character, or a vector or set of characters.
See also [`strip`](#Base.strip) and [`rstrip`](#Base.rstrip).
**Examples**
```
julia> a = lpad("March", 20)
" March"
julia> lstrip(a)
"March"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L324-L347)###
`Base.rstrip`Function
```
rstrip([pred=isspace,] str::AbstractString) -> SubString
rstrip(str::AbstractString, chars) -> SubString
```
Remove trailing characters from `str`, either those specified by `chars` or those for which the function `pred` returns `true`.
The default behaviour is to remove trailing whitespace and delimiters: see [`isspace`](#Base.Unicode.isspace) for precise details.
The optional `chars` argument specifies which characters to remove: it can be a single character, or a vector or set of characters.
See also [`strip`](#Base.strip) and [`lstrip`](#Base.lstrip).
**Examples**
```
julia> a = rpad("March", 20)
"March "
julia> rstrip(a)
"March"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L358-L381)###
`Base.startswith`Function
```
startswith(s::AbstractString, prefix::AbstractString)
```
Return `true` if `s` starts with `prefix`. If `prefix` is a vector or set of characters, test whether the first character of `s` belongs to that set.
See also [`endswith`](#Base.endswith), [`contains`](#Base.contains).
**Examples**
```
julia> startswith("JuliaLang", "Julia")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L7-L20)
```
startswith(prefix)
```
Create a function that checks whether its argument starts with `prefix`, i.e. a function equivalent to `y -> startswith(y, prefix)`.
The returned function is of type `Base.Fix2{typeof(startswith)}`, which can be used to implement specialized methods.
The single argument `startswith(prefix)` requires at least Julia 1.5.
**Examples**
```
julia> startswith_julia = startswith("Julia");
julia> startswith_julia("Julia")
true
julia> startswith_julia("NotJulia")
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L137-L159)
```
startswith(s::AbstractString, prefix::Regex)
```
Return `true` if `s` starts with the regex pattern, `prefix`.
`startswith` does not compile the anchoring into the regular expression, but instead passes the anchoring as `match_option` to PCRE. If compile time is amortized, `occursin(r"^...", s)` is faster than `startswith(s, r"...")`.
See also [`occursin`](#Base.occursin) and [`endswith`](#Base.endswith).
This method requires at least Julia 1.2.
**Examples**
```
julia> startswith("JuliaLang", r"Julia|Romeo")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L274-L295)###
`Base.endswith`Function
```
endswith(s::AbstractString, suffix::AbstractString)
```
Return `true` if `s` ends with `suffix`. If `suffix` is a vector or set of characters, test whether the last character of `s` belongs to that set.
See also [`startswith`](#Base.startswith), [`contains`](#Base.contains).
**Examples**
```
julia> endswith("Sunday", "day")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L32-L45)
```
endswith(suffix)
```
Create a function that checks whether its argument ends with `suffix`, i.e. a function equivalent to `y -> endswith(y, suffix)`.
The returned function is of type `Base.Fix2{typeof(endswith)}`, which can be used to implement specialized methods.
The single argument `endswith(suffix)` requires at least Julia 1.5.
**Examples**
```
julia> endswith_julia = endswith("Julia");
julia> endswith_julia("Julia")
true
julia> endswith_julia("JuliaLang")
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L112-L134)
```
endswith(s::AbstractString, suffix::Regex)
```
Return `true` if `s` ends with the regex pattern, `suffix`.
`endswith` does not compile the anchoring into the regular expression, but instead passes the anchoring as `match_option` to PCRE. If compile time is amortized, `occursin(r"...$", s)` is faster than `endswith(s, r"...")`.
See also [`occursin`](#Base.occursin) and [`startswith`](#Base.startswith).
This method requires at least Julia 1.2.
**Examples**
```
julia> endswith("JuliaLang", r"Lang|Roberts")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L306-L327)###
`Base.contains`Function
```
contains(haystack::AbstractString, needle)
```
Return `true` if `haystack` contains `needle`. This is the same as `occursin(needle, haystack)`, but is provided for consistency with `startswith(haystack, needle)` and `endswith(haystack, needle)`.
See also [`occursin`](#Base.occursin), [`in`](../collections/index#Base.in), [`issubset`](../collections/index#Base.issubset).
**Examples**
```
julia> contains("JuliaLang is pretty cool!", "Julia")
true
julia> contains("JuliaLang is pretty cool!", 'a')
true
julia> contains("aba", r"a.a")
true
julia> contains("abba", r"a.a")
false
```
The `contains` function requires at least Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L83-L109)
```
contains(needle)
```
Create a function that checks whether its argument contains `needle`, i.e. a function equivalent to `haystack -> contains(haystack, needle)`.
The returned function is of type `Base.Fix2{typeof(contains)}`, which can be used to implement specialized methods.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L162-L170)###
`Base.first`Method
```
first(s::AbstractString, n::Integer)
```
Get a string consisting of the first `n` characters of `s`.
**Examples**
```
julia> first("∀ϵ≠0: ϵ²>0", 0)
""
julia> first("∀ϵ≠0: ϵ²>0", 1)
"∀"
julia> first("∀ϵ≠0: ϵ²>0", 3)
"∀ϵ≠"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L641-L657)###
`Base.last`Method
```
last(s::AbstractString, n::Integer)
```
Get a string consisting of the last `n` characters of `s`.
**Examples**
```
julia> last("∀ϵ≠0: ϵ²>0", 0)
""
julia> last("∀ϵ≠0: ϵ²>0", 1)
"0"
julia> last("∀ϵ≠0: ϵ²>0", 3)
"²>0"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L660-L676)###
`Base.Unicode.uppercase`Function
```
uppercase(s::AbstractString)
```
Return `s` with all characters converted to uppercase.
See also [`lowercase`](#Base.Unicode.lowercase), [`titlecase`](#Base.Unicode.titlecase), [`uppercasefirst`](#Base.Unicode.uppercasefirst).
**Examples**
```
julia> uppercase("Julia")
"JULIA"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L536-L548)###
`Base.Unicode.lowercase`Function
```
lowercase(s::AbstractString)
```
Return `s` with all characters converted to lowercase.
See also [`uppercase`](#Base.Unicode.uppercase), [`titlecase`](#Base.Unicode.titlecase), [`lowercasefirst`](#Base.Unicode.lowercasefirst).
**Examples**
```
julia> lowercase("STRINGS AND THINGS")
"strings and things"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L551-L563)###
`Base.Unicode.titlecase`Function
```
titlecase(s::AbstractString; [wordsep::Function], strict::Bool=true) -> String
```
Capitalize the first character of each word in `s`; if `strict` is true, every other character is converted to lowercase, otherwise they are left unchanged. By default, all non-letters beginning a new grapheme are considered as word separators; a predicate can be passed as the `wordsep` keyword to determine which characters should be considered as word separators. See also [`uppercasefirst`](#Base.Unicode.uppercasefirst) to capitalize only the first character in `s`.
See also [`uppercase`](#Base.Unicode.uppercase), [`lowercase`](#Base.Unicode.lowercase), [`uppercasefirst`](#Base.Unicode.uppercasefirst).
**Examples**
```
julia> titlecase("the JULIA programming language")
"The Julia Programming Language"
julia> titlecase("ISS - international space station", strict=false)
"ISS - International Space Station"
julia> titlecase("a-a b-b", wordsep = c->c==' ')
"A-a B-b"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L566-L591)###
`Base.Unicode.uppercasefirst`Function
```
uppercasefirst(s::AbstractString) -> String
```
Return `s` with the first character converted to uppercase (technically "title case" for Unicode). See also [`titlecase`](#Base.Unicode.titlecase) to capitalize the first character of every word in `s`.
See also [`lowercasefirst`](#Base.Unicode.lowercasefirst), [`uppercase`](#Base.Unicode.uppercase), [`lowercase`](#Base.Unicode.lowercase), [`titlecase`](#Base.Unicode.titlecase).
**Examples**
```
julia> uppercasefirst("python")
"Python"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L613-L628)###
`Base.Unicode.lowercasefirst`Function
```
lowercasefirst(s::AbstractString)
```
Return `s` with the first character converted to lowercase.
See also [`uppercasefirst`](#Base.Unicode.uppercasefirst), [`uppercase`](#Base.Unicode.uppercase), [`lowercase`](#Base.Unicode.lowercase), [`titlecase`](#Base.Unicode.titlecase).
**Examples**
```
julia> lowercasefirst("Julia")
"julia"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L637-L650)###
`Base.join`Function
```
join([io::IO,] iterator [, delim [, last]])
```
Join any `iterator` into a single string, inserting the given delimiter (if any) between adjacent items. If `last` is given, it will be used instead of `delim` between the last two items. Each item of `iterator` is converted to a string via `print(io::IOBuffer, x)`. If `io` is given, the result is written to `io` rather than returned as a `String`.
**Examples**
```
julia> join(["apples", "bananas", "pineapples"], ", ", " and ")
"apples, bananas and pineapples"
julia> join([1,2,3,4,5])
"12345"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L309-L325)###
`Base.chop`Function
```
chop(s::AbstractString; head::Integer = 0, tail::Integer = 1)
```
Remove the first `head` and the last `tail` characters from `s`. The call `chop(s)` removes the last character from `s`. If it is requested to remove more characters than `length(s)` then an empty string is returned.
See also [`chomp`](#Base.chomp), [`startswith`](#Base.startswith), [`first`](../collections/index#Base.first).
**Examples**
```
julia> a = "March"
"March"
julia> chop(a)
"Marc"
julia> chop(a, head = 1, tail = 2)
"ar"
julia> chop(a, head = 5, tail = 5)
""
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L173-L197)###
`Base.chopprefix`Function
```
chopprefix(s::AbstractString, prefix::Union{AbstractString,Regex}) -> SubString
```
Remove the prefix `prefix` from `s`. If `s` does not start with `prefix`, a string equal to `s` is returned.
See also [`chopsuffix`](#Base.chopsuffix).
This function is available as of Julia 1.8.
**Examples**
```
julia> chopprefix("Hamburger", "Ham")
"burger"
julia> chopprefix("Hamburger", "hotdog")
"Hamburger"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L208-L226)###
`Base.chopsuffix`Function
```
chopsuffix(s::AbstractString, suffix::Union{AbstractString,Regex}) -> SubString
```
Remove the suffix `suffix` from `s`. If `s` does not end with `suffix`, a string equal to `s` is returned.
See also [`chopprefix`](#Base.chopprefix).
This function is available as of Julia 1.8.
**Examples**
```
julia> chopsuffix("Hamburger", "er")
"Hamburg"
julia> chopsuffix("Hamburger", "hotdog")
"Hamburger"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L249-L267)###
`Base.chomp`Function
```
chomp(s::AbstractString) -> SubString
```
Remove a single trailing newline from a string.
See also [`chop`](#Base.chop).
**Examples**
```
julia> chomp("Hello\n")
"Hello"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L293-L305)###
`Base.thisind`Function
```
thisind(s::AbstractString, i::Integer) -> Int
```
If `i` is in bounds in `s` return the index of the start of the character whose encoding code unit `i` is part of. In other words, if `i` is the start of a character, return `i`; if `i` is not the start of a character, rewind until the start of a character and return that index. If `i` is equal to 0 or `ncodeunits(s)+1` return `i`. In all other cases throw `BoundsError`.
**Examples**
```
julia> thisind("α", 0)
0
julia> thisind("α", 1)
1
julia> thisind("α", 2)
1
julia> thisind("α", 3)
3
julia> thisind("α", 4)
ERROR: BoundsError: attempt to access 2-codeunit String at index [4]
[...]
julia> thisind("α", -1)
ERROR: BoundsError: attempt to access 2-codeunit String at index [-1]
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L404-L435)###
`Base.nextind`Function
```
nextind(str::AbstractString, i::Integer, n::Integer=1) -> Int
```
* Case `n == 1`
If `i` is in bounds in `s` return the index of the start of the character whose encoding starts after index `i`. In other words, if `i` is the start of a character, return the start of the next character; if `i` is not the start of a character, move forward until the start of a character and return that index. If `i` is equal to `0` return `1`. If `i` is in bounds but greater or equal to `lastindex(str)` return `ncodeunits(str)+1`. Otherwise throw `BoundsError`.
* Case `n > 1`
Behaves like applying `n` times `nextind` for `n==1`. The only difference is that if `n` is so large that applying `nextind` would reach `ncodeunits(str)+1` then each remaining iteration increases the returned value by `1`. This means that in this case `nextind` can return a value greater than `ncodeunits(str)+1`.
* Case `n == 0`
Return `i` only if `i` is a valid index in `s` or is equal to `0`. Otherwise `StringIndexError` or `BoundsError` is thrown.
**Examples**
```
julia> nextind("α", 0)
1
julia> nextind("α", 1)
3
julia> nextind("α", 3)
ERROR: BoundsError: attempt to access 2-codeunit String at index [3]
[...]
julia> nextind("α", 0, 2)
3
julia> nextind("α", 1, 2)
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L507-L550)###
`Base.prevind`Function
```
prevind(str::AbstractString, i::Integer, n::Integer=1) -> Int
```
* Case `n == 1`
If `i` is in bounds in `s` return the index of the start of the character whose encoding starts before index `i`. In other words, if `i` is the start of a character, return the start of the previous character; if `i` is not the start of a character, rewind until the start of a character and return that index. If `i` is equal to `1` return `0`. If `i` is equal to `ncodeunits(str)+1` return `lastindex(str)`. Otherwise throw `BoundsError`.
* Case `n > 1`
Behaves like applying `n` times `prevind` for `n==1`. The only difference is that if `n` is so large that applying `prevind` would reach `0` then each remaining iteration decreases the returned value by `1`. This means that in this case `prevind` can return a negative value.
* Case `n == 0`
Return `i` only if `i` is a valid index in `str` or is equal to `ncodeunits(str)+1`. Otherwise `StringIndexError` or `BoundsError` is thrown.
**Examples**
```
julia> prevind("α", 3)
1
julia> prevind("α", 1)
0
julia> prevind("α", 0)
ERROR: BoundsError: attempt to access 2-codeunit String at index [0]
[...]
julia> prevind("α", 2, 2)
0
julia> prevind("α", 2, 3)
-1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L448-L491)###
`Base.Unicode.textwidth`Function
```
textwidth(c)
```
Give the number of columns needed to print a character.
**Examples**
```
julia> textwidth('α')
1
julia> textwidth('⛵')
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L241-L254)
```
textwidth(s::AbstractString)
```
Give the number of columns needed to print a string.
**Examples**
```
julia> textwidth("March")
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L260-L270)###
`Base.isascii`Function
```
isascii(c::Union{AbstractChar,AbstractString}) -> Bool
```
Test whether a character belongs to the ASCII character set, or whether this is true for all elements of a string.
**Examples**
```
julia> isascii('a')
true
julia> isascii('α')
false
julia> isascii("abc")
true
julia> isascii("αβγ")
false
```
For example, `isascii` can be used as a predicate function for [`filter`](../collections/index#Base.filter) or [`replace`](#) to remove or replace non-ASCII characters, respectively:
```
julia> filter(isascii, "abcdeγfgh") # discard non-ASCII chars
"abcdefgh"
julia> replace("abcdeγfgh", !isascii=>' ') # replace non-ASCII chars with spaces
"abcde fgh"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L579-L608)###
`Base.Unicode.iscntrl`Function
```
iscntrl(c::AbstractChar) -> Bool
```
Tests whether a character is a control character. Control characters are the non-printing characters of the Latin-1 subset of Unicode.
**Examples**
```
julia> iscntrl('\x01')
true
julia> iscntrl('a')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L434-L448)###
`Base.Unicode.isdigit`Function
```
isdigit(c::AbstractChar) -> Bool
```
Tests whether a character is a decimal digit (0-9).
**Examples**
```
julia> isdigit('❤')
false
julia> isdigit('9')
true
julia> isdigit('α')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L365-L381)###
`Base.Unicode.isletter`Function
```
isletter(c::AbstractChar) -> Bool
```
Test whether a character is a letter. A character is classified as a letter if it belongs to the Unicode general category Letter, i.e. a character whose category code begins with 'L'.
**Examples**
```
julia> isletter('❤')
false
julia> isletter('α')
true
julia> isletter('9')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L384-L402)###
`Base.Unicode.islowercase`Function
```
islowercase(c::AbstractChar) -> Bool
```
Tests whether a character is a lowercase letter (according to the Unicode standard's `Lowercase` derived property).
See also [`isuppercase`](#Base.Unicode.isuppercase).
**Examples**
```
julia> islowercase('α')
true
julia> islowercase('Γ')
false
julia> islowercase('❤')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L304-L323)###
`Base.Unicode.isnumeric`Function
```
isnumeric(c::AbstractChar) -> Bool
```
Tests whether a character is numeric. A character is classified as numeric if it belongs to the Unicode general category Number, i.e. a character whose category code begins with 'N'.
Note that this broad category includes characters such as ¾ and ௰. Use [`isdigit`](#Base.Unicode.isdigit) to check whether a character a decimal digit between 0 and 9.
**Examples**
```
julia> isnumeric('௰')
true
julia> isnumeric('9')
true
julia> isnumeric('α')
false
julia> isnumeric('❤')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L405-L429)###
`Base.Unicode.isprint`Function
```
isprint(c::AbstractChar) -> Bool
```
Tests whether a character is printable, including spaces, but not a control character.
**Examples**
```
julia> isprint('\x01')
false
julia> isprint('A')
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L499-L512)###
`Base.Unicode.ispunct`Function
```
ispunct(c::AbstractChar) -> Bool
```
Tests whether a character belongs to the Unicode general category Punctuation, i.e. a character whose category code begins with 'P'.
**Examples**
```
julia> ispunct('α')
false
julia> ispunct('/')
true
julia> ispunct(';')
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L451-L468)###
`Base.Unicode.isspace`Function
```
isspace(c::AbstractChar) -> Bool
```
Tests whether a character is any whitespace character. Includes ASCII characters '\t', '\n', '\v', '\f', '\r', and ' ', Latin-1 character U+0085, and characters in Unicode category Zs.
**Examples**
```
julia> isspace('\n')
true
julia> isspace('\r')
true
julia> isspace(' ')
true
julia> isspace('\x20')
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L473-L494)###
`Base.Unicode.isuppercase`Function
```
isuppercase(c::AbstractChar) -> Bool
```
Tests whether a character is an uppercase letter (according to the Unicode standard's `Uppercase` derived property).
See also [`islowercase`](#Base.Unicode.islowercase).
**Examples**
```
julia> isuppercase('γ')
false
julia> isuppercase('Γ')
true
julia> isuppercase('❤')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L328-L347)###
`Base.Unicode.isxdigit`Function
```
isxdigit(c::AbstractChar) -> Bool
```
Test whether a character is a valid hexadecimal digit. Note that this does not include `x` (as in the standard `0x` prefix).
**Examples**
```
julia> isxdigit('a')
true
julia> isxdigit('x')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/unicode.jl#L517-L531)###
`Base.escape_string`Function
```
escape_string(str::AbstractString[, esc]; keep = ())::AbstractString
escape_string(io, str::AbstractString[, esc]; keep = ())::Nothing
```
General escaping of traditional C and Unicode escape sequences. The first form returns the escaped string, the second prints the result to `io`.
Backslashes (`\`) are escaped with a double-backslash (`"\\"`). Non-printable characters are escaped either with their standard C escape codes, `"\0"` for NUL (if unambiguous), unicode code point (`"\u"` prefix) or hex (`"\x"` prefix).
The optional `esc` argument specifies any additional characters that should also be escaped by a prepending backslash (`"` is also escaped by default in the first form).
The argument `keep` specifies a collection of characters which are to be kept as they are. Notice that `esc` has precedence here.
See also [`unescape_string`](#Base.unescape_string) for the reverse operation.
The `keep` argument is available as of Julia 1.7.
**Examples**
```
julia> escape_string("aaa\nbbb")
"aaa\\nbbb"
julia> escape_string("aaa\nbbb"; keep = '\n')
"aaa\nbbb"
julia> escape_string("\xfe\xff") # invalid utf-8
"\\xfe\\xff"
julia> escape_string(string('\u2135','\0')) # unambiguous
"ℵ\\0"
julia> escape_string(string('\u2135','\0','0')) # \0 would be ambiguous
"ℵ\\x000"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L362-L401)###
`Base.unescape_string`Function
```
unescape_string(str::AbstractString, keep = ())::AbstractString
unescape_string(io, s::AbstractString, keep = ())::Nothing
```
General unescaping of traditional C and Unicode escape sequences. The first form returns the escaped string, the second prints the result to `io`. The argument `keep` specifies a collection of characters which (along with backlashes) are to be kept as they are.
The following escape sequences are recognised:
* Escaped backslash (`\\`)
* Escaped double-quote (`\"`)
* Standard C escape sequences (`\a`, `\b`, `\t`, `\n`, `\v`, `\f`, `\r`, `\e`)
* Unicode BMP code points (`\u` with 1-4 trailing hex digits)
* All Unicode code points (`\U` with 1-8 trailing hex digits; max value = 0010ffff)
* Hex bytes (`\x` with 1-2 trailing hex digits)
* Octal bytes (`\` with 1-3 trailing octal digits)
See also [`escape_string`](#Base.escape_string).
**Examples**
```
julia> unescape_string("aaa\\nbbb") # C escape sequence
"aaa\nbbb"
julia> unescape_string("\\u03c0") # unicode
"π"
julia> unescape_string("\\101") # octal
"A"
julia> unescape_string("aaa \\g \\n", ['g']) # using `keep` argument
"aaa \\g \n"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L443-L477)
| programming_docs |
julia Tasks Tasks
=====
###
`Core.Task`Type
```
Task(func)
```
Create a `Task` (i.e. coroutine) to execute the given function `func` (which must be callable with no arguments). The task exits when this function returns. The task will run in the "world age" from the parent at construction when [`schedule`](#Base.schedule)d.
**Examples**
```
julia> a() = sum(i for i in 1:1000);
julia> b = Task(a);
```
In this example, `b` is a runnable `Task` that hasn't started yet.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1533-L1548)###
`Base.@task`Macro
```
@task
```
Wrap an expression in a [`Task`](#Core.Task) without executing it, and return the [`Task`](#Core.Task). This only creates a task, and does not run it.
**Examples**
```
julia> a1() = sum(i for i in 1:1000);
julia> b = @task a1();
julia> istaskstarted(b)
false
julia> schedule(b);
julia> yield();
julia> istaskdone(b)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L110-L132)###
`Base.@async`Macro
```
@async
```
Wrap an expression in a [`Task`](#Core.Task) and add it to the local machine's scheduler queue.
Values can be interpolated into `@async` via `$`, which copies the value directly into the constructed underlying closure. This allows you to insert the *value* of a variable, isolating the asynchronous code from changes to the variable's value in the current task.
Interpolating values via `$` is available as of Julia 1.4.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L463-L474)###
`Base.asyncmap`Function
```
asyncmap(f, c...; ntasks=0, batch_size=nothing)
```
Uses multiple concurrent tasks to map `f` over a collection (or multiple equal length collections). For multiple collection arguments, `f` is applied elementwise.
`ntasks` specifies the number of tasks to run concurrently. Depending on the length of the collections, if `ntasks` is unspecified, up to 100 tasks will be used for concurrent mapping.
`ntasks` can also be specified as a zero-arg function. In this case, the number of tasks to run in parallel is checked before processing every element and a new task started if the value of `ntasks_func` is greater than the current number of tasks.
If `batch_size` is specified, the collection is processed in batch mode. `f` must then be a function that must accept a `Vector` of argument tuples and must return a vector of results. The input vector will have a length of `batch_size` or less.
The following examples highlight execution in different tasks by returning the `objectid` of the tasks in which the mapping function is executed.
First, with `ntasks` undefined, each element is processed in a different task.
```
julia> tskoid() = objectid(current_task());
julia> asyncmap(x->tskoid(), 1:5)
5-element Array{UInt64,1}:
0x6e15e66c75c75853
0x440f8819a1baa682
0x9fb3eeadd0c83985
0xebd3e35fe90d4050
0x29efc93edce2b961
julia> length(unique(asyncmap(x->tskoid(), 1:5)))
5
```
With `ntasks=2` all elements are processed in 2 tasks.
```
julia> asyncmap(x->tskoid(), 1:5; ntasks=2)
5-element Array{UInt64,1}:
0x027ab1680df7ae94
0xa23d2f80cd7cf157
0x027ab1680df7ae94
0xa23d2f80cd7cf157
0x027ab1680df7ae94
julia> length(unique(asyncmap(x->tskoid(), 1:5; ntasks=2)))
2
```
With `batch_size` defined, the mapping function needs to be changed to accept an array of argument tuples and return an array of results. `map` is used in the modified mapping function to achieve this.
```
julia> batch_func(input) = map(x->string("args_tuple: ", x, ", element_val: ", x[1], ", task: ", tskoid()), input)
batch_func (generic function with 1 method)
julia> asyncmap(batch_func, 1:5; ntasks=2, batch_size=2)
5-element Array{String,1}:
"args_tuple: (1,), element_val: 1, task: 9118321258196414413"
"args_tuple: (2,), element_val: 2, task: 4904288162898683522"
"args_tuple: (3,), element_val: 3, task: 9118321258196414413"
"args_tuple: (4,), element_val: 4, task: 4904288162898683522"
"args_tuple: (5,), element_val: 5, task: 9118321258196414413"
```
Currently, all tasks in Julia are executed in a single OS thread co-operatively. Consequently, `asyncmap` is beneficial only when the mapping function involves any I/O - disk, network, remote worker invocation, etc.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncmap.jl#L5-L79)###
`Base.asyncmap!`Function
```
asyncmap!(f, results, c...; ntasks=0, batch_size=nothing)
```
Like [`asyncmap`](#Base.asyncmap), but stores output in `results` rather than returning a collection.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncmap.jl#L398-L403)###
`Base.current_task`Function
```
current_task()
```
Get the currently running [`Task`](#Core.Task).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L137-L141)###
`Base.istaskdone`Function
```
istaskdone(t::Task) -> Bool
```
Determine whether a task has exited.
**Examples**
```
julia> a2() = sum(i for i in 1:1000);
julia> b = Task(a2);
julia> istaskdone(b)
false
julia> schedule(b);
julia> yield();
julia> istaskdone(b)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L185-L206)###
`Base.istaskstarted`Function
```
istaskstarted(t::Task) -> Bool
```
Determine whether a task has started executing.
**Examples**
```
julia> a3() = sum(i for i in 1:1000);
julia> b = Task(a3);
julia> istaskstarted(b)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L209-L223)###
`Base.istaskfailed`Function
```
istaskfailed(t::Task) -> Bool
```
Determine whether a task has exited because an exception was thrown.
**Examples**
```
julia> a4() = error("task failed");
julia> b = Task(a4);
julia> istaskfailed(b)
false
julia> schedule(b);
julia> yield();
julia> istaskfailed(b)
true
```
This function requires at least Julia 1.3.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L226-L250)###
`Base.task_local_storage`Method
```
task_local_storage(key)
```
Look up the value of a key in the current task's task-local storage.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L265-L269)###
`Base.task_local_storage`Method
```
task_local_storage(key, value)
```
Assign a value to a key in the current task's task-local storage.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L272-L276)###
`Base.task_local_storage`Method
```
task_local_storage(body, key, value)
```
Call the function `body` with a modified task-local storage, in which `value` is assigned to `key`; the previous value of `key`, or lack thereof, is restored afterwards. Useful for emulating dynamic scoping.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L279-L285)
[Scheduling](#Scheduling)
--------------------------
###
`Base.yield`Function
```
yield()
```
Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L804-L810)
```
yield(t::Task, arg = nothing)
```
A fast, unfair-scheduling version of `schedule(t, arg); yield()` which immediately yields to `t` before calling the scheduler.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L824-L829)###
`Base.yieldto`Function
```
yieldto(t::Task, arg = nothing)
```
Switch to the given task. The first time a task is switched to, the task's function is called with no arguments. On subsequent switches, `arg` is returned from the task's last call to `yieldto`. This is a low-level call that only switches tasks, not considering states or scheduling in any way. Its use is discouraged.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L838-L845)###
`Base.sleep`Function
```
sleep(seconds)
```
Block the current task for a specified number of seconds. The minimum sleep time is 1 millisecond or input of `0.001`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncevent.jl#L232-L237)###
`Base.schedule`Function
```
schedule(t::Task, [val]; error=false)
```
Add a [`Task`](#Core.Task) to the scheduler's queue. This causes the task to run constantly when the system is otherwise idle, unless the task performs a blocking operation such as [`wait`](#Base.wait).
If a second argument `val` is provided, it will be passed to the task (via the return value of [`yieldto`](#Base.yieldto)) when it runs again. If `error` is `true`, the value is raised as an exception in the woken task.
It is incorrect to use `schedule` on an arbitrary `Task` that has already been started. See [the API reference](#low-level-schedule-wait) for more information.
**Examples**
```
julia> a5() = sum(i for i in 1:1000);
julia> b = Task(a5);
julia> istaskstarted(b)
false
julia> schedule(b);
julia> yield();
julia> istaskstarted(b)
true
julia> istaskdone(b)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L755-L788)
[Synchronization](#lib-task-sync)
----------------------------------
[Synchronization](#Synchronization)
------------------------------------
###
`Base.errormonitor`Function
```
errormonitor(t::Task)
```
Print an error log to `stderr` if task `t` fails.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L527-L531)###
`Base.@sync`Macro
```
@sync
```
Wait until all lexically-enclosed uses of `@async`, `@spawn`, `@spawnat` and `@distributed` are complete. All exceptions thrown by enclosed async operations are collected and thrown as a `CompositeException`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L443-L449)###
`Base.wait`Function
Special note for [`Threads.Condition`](#Base.Threads.Condition):
The caller must be holding the [`lock`](#Base.lock) that owns a `Threads.Condition` before calling this method. The calling task will be blocked until some other task wakes it, usually by calling [`notify`](#Base.notify) on the same `Threads.Condition` object. The lock will be atomically released when blocking (even if it was locked recursively), and will be reacquired before returning.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L274-L282)
```
wait(r::Future)
```
Wait for a value to become available for the specified [`Future`](../../stdlib/distributed/index#Distributed.Future).
```
wait(r::RemoteChannel, args...)
```
Wait for a value to become available on the specified [`RemoteChannel`](../../stdlib/distributed/index#Distributed.RemoteChannel).
```
wait([x])
```
Block the current task until some event occurs, depending on the type of the argument:
* [`Channel`](#Base.Channel): Wait for a value to be appended to the channel.
* [`Condition`](#Base.Condition): Wait for [`notify`](#Base.notify) on a condition and return the `val` parameter passed to `notify`.
* `Process`: Wait for a process or process chain to exit. The `exitcode` field of a process can be used to determine success or failure.
* [`Task`](#Core.Task): Wait for a `Task` to finish. If the task fails with an exception, a `TaskFailedException` (which wraps the failed task) is thrown.
* [`RawFD`](../file/index#Base.Libc.RawFD): Wait for changes on a file descriptor (see the `FileWatching` package).
If no argument is passed, the task blocks for an undefined period. A task can only be restarted by an explicit call to [`schedule`](#Base.schedule) or [`yieldto`](#Base.yieldto).
Often `wait` is called within a `while` loop to ensure a waited-for condition is met before proceeding.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/condition.jl#L99-L118)###
`Base.fetch`Method
```
fetch(t::Task)
```
Wait for a Task to finish, then return its result value. If the task fails with an exception, a `TaskFailedException` (which wraps the failed task) is thrown.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L352-L358)###
`Base.timedwait`Function
```
timedwait(callback::Function, timeout::Real; pollint::Real=0.1)
```
Waits until `callback` returns `true` or `timeout` seconds have passed, whichever is earlier. `callback` is polled every `pollint` seconds. The minimum value for `timeout` and `pollint` is `0.001`, that is, 1 millisecond.
Returns :ok or :timed\_out
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncevent.jl#L302-L310)###
`Base.Condition`Type
```
Condition()
```
Create an edge-triggered event source that tasks can wait for. Tasks that call [`wait`](#Base.wait) on a `Condition` are suspended and queued. Tasks are woken up when [`notify`](#Base.notify) is later called on the `Condition`. Edge triggering means that only tasks waiting at the time [`notify`](#Base.notify) is called can be woken up. For level-triggered notifications, you must keep extra state to keep track of whether a notification has happened. The [`Channel`](#Base.Channel) and [`Threads.Event`](#Base.Event) types do this, and can be used for level-triggered events.
This object is NOT thread-safe. See [`Threads.Condition`](#Base.Threads.Condition) for a thread-safe version.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/condition.jl#L169-L180)###
`Base.Threads.Condition`Type
```
Threads.Condition([lock])
```
A thread-safe version of [`Base.Condition`](#Base.Condition).
To call [`wait`](#Base.wait) or [`notify`](#Base.notify) on a `Threads.Condition`, you must first call [`lock`](#Base.lock) on it. When `wait` is called, the lock is atomically released during blocking, and will be reacquired before `wait` returns. Therefore idiomatic use of a `Threads.Condition` `c` looks like the following:
```
lock(c)
try
while !thing_we_are_waiting_for
wait(c)
end
finally
unlock(c)
end
```
This functionality requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L248-L271)###
`Base.Event`Type
```
Event([autoreset=false])
```
Create a level-triggered event source. Tasks that call [`wait`](#Base.wait) on an `Event` are suspended and queued until [`notify`](#Base.notify) is called on the `Event`. After `notify` is called, the `Event` remains in a signaled state and tasks will no longer block when waiting for it, until `reset` is called.
If `autoreset` is true, at most one task will be released from `wait` for each call to `notify`.
This provides an acquire & release memory ordering on notify/wait.
This functionality requires at least Julia 1.1.
The `autoreset` functionality and memory ordering guarantee requires at least Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L374-L392)###
`Base.notify`Function
```
notify(condition, val=nothing; all=true, error=false)
```
Wake up tasks waiting for a condition, passing them `val`. If `all` is `true` (the default), all waiting tasks are woken, otherwise only one is. If `error` is `true`, the passed value is raised as an exception in the woken tasks.
Return the count of tasks woken up. Return 0 if no tasks are waiting on `condition`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/condition.jl#L133-L141)###
`Base.reset`Method
```
reset(::Event)
```
Reset an Event back into an un-set state. Then any future calls to `wait` will block until `notify` is called again.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L437-L442)###
`Base.Semaphore`Type
```
Semaphore(sem_size)
```
Create a counting semaphore that allows at most `sem_size` acquires to be in use at any time. Each acquire must be matched with a release.
This provides a acquire & release memory ordering on acquire/release calls.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L286-L294)###
`Base.acquire`Function
```
acquire(s::Semaphore)
```
Wait for one of the `sem_size` permits to be available, blocking until one can be acquired.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L302-L307)
```
acquire(f, s::Semaphore)
```
Execute `f` after acquiring from Semaphore `s`, and `release` on completion or error.
For example, a do-block form that ensures only 2 calls of `foo` will be active at the same time:
```
s = Base.Semaphore(2)
@sync for _ in 1:100
Threads.@spawn begin
Base.acquire(s) do
foo()
end
end
end
```
This method requires at least Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L321-L344)###
`Base.release`Function
```
release(s::Semaphore)
```
Return one permit to the pool, possibly allowing another task to acquire it and resume execution.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L354-L360)###
`Base.AbstractLock`Type
```
AbstractLock
```
Abstract supertype describing types that implement the synchronization primitives: [`lock`](#Base.lock), [`trylock`](#Base.trylock), [`unlock`](#Base.unlock), and [`islocked`](#Base.islocked).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/condition.jl#L11-L17)###
`Base.lock`Function
```
lock(lock)
```
Acquire the `lock` when it becomes available. If the lock is already locked by a different task/thread, wait for it to become available.
Each `lock` must be matched by an [`unlock`](#Base.unlock).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L93-L101)
```
lock(f::Function, lock)
```
Acquire the `lock`, execute `f` with the `lock` held, and release the `lock` when `f` returns. If the lock is already locked by a different task/thread, wait for it to become available.
When this function returns, the `lock` has been released, so the caller should not attempt to `unlock` it.
Using a [`Channel`](#Base.Channel) as the second argument requires Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L169-L181)###
`Base.unlock`Function
```
unlock(lock)
```
Releases ownership of the `lock`.
If this is a recursive lock which has been acquired before, decrement an internal counter and return immediately.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L122-L129)###
`Base.trylock`Function
```
trylock(lock) -> Success (Boolean)
```
Acquire the lock if it is available, and return `true` if successful. If the lock is already locked by a different task/thread, return `false`.
Each successful `trylock` must be matched by an [`unlock`](#Base.unlock).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L61-L70)###
`Base.islocked`Function
```
islocked(lock) -> Status (Boolean)
```
Check whether the `lock` is held by any task/thread. This should not be used for synchronization (see instead [`trylock`](#Base.trylock)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L51-L56)###
`Base.ReentrantLock`Type
```
ReentrantLock()
```
Creates a re-entrant lock for synchronizing [`Task`](#Core.Task)s. The same task can acquire the lock as many times as required. Each [`lock`](#Base.lock) must be matched with an [`unlock`](#Base.unlock).
Calling 'lock' will also inhibit running of finalizers on that thread until the corresponding 'unlock'. Use of the standard lock pattern illustrated below should naturally be supported, but beware of inverting the try/lock order or missing the try block entirely (e.g. attempting to return with the lock still held):
This provides a acquire/release memory ordering on lock/unlock calls.
```
lock(l)
try
<atomic work>
finally
unlock(l)
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/lock.jl#L6-L29)
[Channels](#Channels)
----------------------
###
`Base.Channel`Type
```
Channel{T=Any}(size::Int=0)
```
Constructs a `Channel` with an internal buffer that can hold a maximum of `size` objects of type `T`. [`put!`](#Base.put!-Tuple%7BChannel,%20Any%7D) calls on a full channel block until an object is removed with [`take!`](#).
`Channel(0)` constructs an unbuffered channel. `put!` blocks until a matching `take!` is called. And vice-versa.
Other constructors:
* `Channel()`: default constructor, equivalent to `Channel{Any}(0)`
* `Channel(Inf)`: equivalent to `Channel{Any}(typemax(Int))`
* `Channel(sz)`: equivalent to `Channel{Any}(sz)`
The default constructor `Channel()` and default `size=0` were added in Julia 1.3.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L13-L31)###
`Base.Channel`Method
```
Channel{T=Any}(func::Function, size=0; taskref=nothing, spawn=false)
```
Create a new task from `func`, bind it to a new channel of type `T` and size `size`, and schedule the task, all in a single call. The channel is automatically closed when the task terminates.
`func` must accept the bound channel as its only argument.
If you need a reference to the created task, pass a `Ref{Task}` object via the keyword argument `taskref`.
If `spawn = true`, the Task created for `func` may be scheduled on another thread in parallel, equivalent to creating a task via [`Threads.@spawn`](../multi-threading/index#Base.Threads.@spawn).
Return a `Channel`.
**Examples**
```
julia> chnl = Channel() do ch
foreach(i -> put!(ch, i), 1:4)
end;
julia> typeof(chnl)
Channel{Any}
julia> for i in chnl
@show i
end;
i = 1
i = 2
i = 3
i = 4
```
Referencing the created task:
```
julia> taskref = Ref{Task}();
julia> chnl = Channel(taskref=taskref) do ch
println(take!(ch))
end;
julia> istaskdone(taskref[])
false
julia> put!(chnl, "Hello");
Hello
julia> istaskdone(taskref[])
true
```
The `spawn=` parameter was added in Julia 1.3. This constructor was added in Julia 1.3. In earlier versions of Julia, Channel used keyword arguments to set `size` and `T`, but those constructors are deprecated.
```
julia> chnl = Channel{Char}(1, spawn=true) do ch
for c in "hello world"
put!(ch, c)
end
end
Channel{Char}(1) (2 items available)
julia> String(collect(chnl))
"hello world"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L61-L131)###
`Base.put!`Method
```
put!(c::Channel, v)
```
Append an item `v` to the channel `c`. Blocks if the channel is full.
For unbuffered channels, blocks until a [`take!`](#) is performed by a different task.
`v` now gets converted to the channel's type with [`convert`](../base/index#Base.convert) as `put!` is called.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L307-L317)###
`Base.take!`Method
```
take!(c::Channel)
```
Remove and return a value from a [`Channel`](#Base.Channel). Blocks until data is available.
For unbuffered channels, blocks until a [`put!`](#Base.put!-Tuple%7BChannel,%20Any%7D) is performed by a different task.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L402-L409)###
`Base.isready`Method
```
isready(c::Channel)
```
Determine whether a [`Channel`](#Base.Channel) has a value stored to it. Returns immediately, does not block.
For unbuffered channels returns `true` if there are tasks waiting on a [`put!`](#Base.put!-Tuple%7BChannel,%20Any%7D).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L439-L447)###
`Base.fetch`Method
```
fetch(c::Channel)
```
Wait for and get the first available item from the channel. Does not remove the item. `fetch` is unsupported on an unbuffered (0-size) channel.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L380-L385)###
`Base.close`Method
```
close(c::Channel[, excp::Exception])
```
Close a channel. An exception (optionally given by `excp`), is thrown by:
* [`put!`](#Base.put!-Tuple%7BChannel,%20Any%7D) on a closed channel.
* [`take!`](#) and [`fetch`](#Base.fetch-Tuple%7BTask%7D) on an empty, closed channel.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L178-L185)###
`Base.bind`Method
```
bind(chnl::Channel, task::Task)
```
Associate the lifetime of `chnl` with a task. `Channel` `chnl` is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on `chnl`.
The `chnl` object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed `Channel` objects.
When a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.
**Examples**
```
julia> c = Channel(0);
julia> task = @async foreach(i->put!(c, i), 1:4);
julia> bind(c,task);
julia> for i in c
@show i
end;
i = 1
i = 2
i = 3
i = 4
julia> isopen(c)
false
```
```
julia> c = Channel(0);
julia> task = @async (put!(c, 1); error("foo"));
julia> bind(c, task);
julia> take!(c)
1
julia> put!(c, 1);
ERROR: TaskFailedException
Stacktrace:
[...]
nested task error: foo
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/channels.jl#L201-L252)
[Low-level synchronization using `schedule` and `wait`](#low-level-schedule-wait)
----------------------------------------------------------------------------------
The easiest correct use of [`schedule`](#Base.schedule) is on a `Task` that is not started (scheduled) yet. However, it is possible to use [`schedule`](#Base.schedule) and [`wait`](#Base.wait) as a very low-level building block for constructing synchronization interfaces. A crucial pre-condition of calling `schedule(task)` is that the caller must "own" the `task`; i.e., it must know that the call to `wait` in the given `task` is happening at the locations known to the code calling `schedule(task)`. One strategy for ensuring such pre-condition is to use atomics, as demonstrated in the following example:
```
@enum OWEState begin
OWE_EMPTY
OWE_WAITING
OWE_NOTIFYING
end
mutable struct OneWayEvent
@atomic state::OWEState
task::Task
OneWayEvent() = new(OWE_EMPTY)
end
function Base.notify(ev::OneWayEvent)
state = @atomic ev.state
while state !== OWE_NOTIFYING
# Spin until we successfully update the state to OWE_NOTIFYING:
state, ok = @atomicreplace(ev.state, state => OWE_NOTIFYING)
if ok
if state == OWE_WAITING
# OWE_WAITING -> OWE_NOTIFYING transition means that the waiter task is
# already waiting or about to call `wait`. The notifier task must wake up
# the waiter task.
schedule(ev.task)
else
@assert state == OWE_EMPTY
# Since we are assuming that there is only one notifier task (for
# simplicity), we know that the other possible case here is OWE_EMPTY.
# We do not need to do anything because we know that the waiter task has
# not called `wait(ev::OneWayEvent)` yet.
end
break
end
end
return
end
function Base.wait(ev::OneWayEvent)
ev.task = current_task()
state, ok = @atomicreplace(ev.state, OWE_EMPTY => OWE_WAITING)
if ok
# OWE_EMPTY -> OWE_WAITING transition means that the notifier task is guaranteed to
# invoke OWE_WAITING -> OWE_NOTIFYING transition. The waiter task must call
# `wait()` immediately. In particular, it MUST NOT invoke any function that may
# yield to the scheduler at this point in code.
wait()
else
@assert state == OWE_NOTIFYING
# Otherwise, the `state` must have already been moved to OWE_NOTIFYING by the
# notifier task.
end
return
end
ev = OneWayEvent()
@sync begin
@async begin
wait(ev)
println("done")
end
println("notifying...")
notify(ev)
end
# output
notifying...
done
```
`OneWayEvent` lets one task to `wait` for another task's `notify`. It is a limited communication interface since `wait` can only be used once from a single task (note the non-atomic assignment of `ev.task`)
In this example, `notify(ev::OneWayEvent)` is allowed to call `schedule(ev.task)` if and only if *it* modifies the state from `OWE_WAITING` to `OWE_NOTIFYING`. This lets us know that the task executing `wait(ev::OneWayEvent)` is now in the `ok` branch and that there cannot be other tasks that tries to `schedule(ev.task)` since their `@atomicreplace(ev.state, state => OWE_NOTIFYING)` will fail.
| programming_docs |
julia Numbers Numbers
=======
[Standard Numeric Types](#Standard-Numeric-Types)
--------------------------------------------------
###
[Abstract number types](#Abstract-number-types)
###
`Core.Number`Type
```
Number
```
Abstract supertype for all number types.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1775-L1779)###
`Core.Real`Type
```
Real <: Number
```
Abstract supertype for all real numbers.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1782-L1786)###
`Core.AbstractFloat`Type
```
AbstractFloat <: Real
```
Abstract supertype for all floating point numbers.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1789-L1793)###
`Core.Integer`Type
```
Integer <: Real
```
Abstract supertype for all integers.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1796-L1800)###
`Core.Signed`Type
```
Signed <: Integer
```
Abstract supertype for all signed integers.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1803-L1807)###
`Core.Unsigned`Type
```
Unsigned <: Integer
```
Abstract supertype for all unsigned integers.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1810-L1814)###
`Base.AbstractIrrational`Type
```
AbstractIrrational <: Real
```
Number type representing an exact irrational value, which is automatically rounded to the correct precision in arithmetic operations with other numeric quantities.
Subtypes `MyIrrational <: AbstractIrrational` should implement at least `==(::MyIrrational, ::MyIrrational)`, `hash(x::MyIrrational, h::UInt)`, and `convert(::Type{F}, x::MyIrrational) where {F <: Union{BigFloat,Float32,Float64}}`.
If a subtype is used to represent values that may occasionally be rational (e.g. a square-root type that represents `√n` for integers `n` will give a rational result when `n` is a perfect square), then it should also implement `isinteger`, `iszero`, `isone`, and `==` with `Real` values (since all of these default to `false` for `AbstractIrrational` types), as well as defining [`hash`](../base/index#Base.hash) to equal that of the corresponding `Rational`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/irrationals.jl#L5-L18)###
[Concrete number types](#Concrete-number-types)
###
`Core.Float16`Type
```
Float16 <: AbstractFloat
```
16-bit floating point number type (IEEE 754 standard).
Binary format: 1 sign, 5 exponent, 10 fraction bits.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1846-L1852)###
`Core.Float32`Type
```
Float32 <: AbstractFloat
```
32-bit floating point number type (IEEE 754 standard).
Binary format: 1 sign, 8 exponent, 23 fraction bits.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1846-L1852)###
`Core.Float64`Type
```
Float64 <: AbstractFloat
```
64-bit floating point number type (IEEE 754 standard).
Binary format: 1 sign, 11 exponent, 52 fraction bits.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1846-L1852)###
`Base.MPFR.BigFloat`Type
```
BigFloat <: AbstractFloat
```
Arbitrary precision floating point number type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mpfr.jl#L85-L89)###
`Core.Bool`Type
```
Bool <: Integer
```
Boolean type, containing the values `true` and `false`.
`Bool` is a kind of number: `false` is numerically equal to `0` and `true` is numerically equal to `1`. Moreover, `false` acts as a multiplicative "strong zero":
```
julia> false == 0
true
julia> true == 1
true
julia> 0 * NaN
NaN
julia> false * NaN
0.0
```
See also: [`digits`](#Base.digits), [`iszero`](#Base.iszero), [`NaN`](#Base.NaN).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1817-L1841)###
`Core.Int8`Type
```
Int8 <: Signed
```
8-bit signed integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1859-L1863)###
`Core.UInt8`Type
```
UInt8 <: Unsigned
```
8-bit unsigned integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1866-L1870)###
`Core.Int16`Type
```
Int16 <: Signed
```
16-bit signed integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1859-L1863)###
`Core.UInt16`Type
```
UInt16 <: Unsigned
```
16-bit unsigned integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1866-L1870)###
`Core.Int32`Type
```
Int32 <: Signed
```
32-bit signed integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1859-L1863)###
`Core.UInt32`Type
```
UInt32 <: Unsigned
```
32-bit unsigned integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1866-L1870)###
`Core.Int64`Type
```
Int64 <: Signed
```
64-bit signed integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1859-L1863)###
`Core.UInt64`Type
```
UInt64 <: Unsigned
```
64-bit unsigned integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1866-L1870)###
`Core.Int128`Type
```
Int128 <: Signed
```
128-bit signed integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1859-L1863)###
`Core.UInt128`Type
```
UInt128 <: Unsigned
```
128-bit unsigned integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1866-L1870)###
`Base.GMP.BigInt`Type
```
BigInt <: Signed
```
Arbitrary precision integer type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gmp.jl#L45-L49)###
`Base.Complex`Type
```
Complex{T<:Real} <: Number
```
Complex number type with real and imaginary part of type `T`.
`ComplexF16`, `ComplexF32` and `ComplexF64` are aliases for `Complex{Float16}`, `Complex{Float32}` and `Complex{Float64}` respectively.
See also: [`Real`](#Core.Real), [`complex`](#Base.complex-Tuple%7BComplex%7D), [`real`](../math/index#Base.real).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L3-L12)###
`Base.Rational`Type
```
Rational{T<:Integer} <: Real
```
Rational number type, with numerator and denominator of type `T`. Rationals are checked for overflow.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rational.jl#L3-L8)###
`Base.Irrational`Type
```
Irrational{sym} <: AbstractIrrational
```
Number type representing an exact irrational value denoted by the symbol `sym`, such as [`π`](#Base.MathConstants.pi), [`ℯ`](#Base.MathConstants.%E2%84%AF) and [`γ`](#Base.MathConstants.eulergamma).
See also [`@irrational`], [`AbstractIrrational`](#Base.AbstractIrrational).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/irrationals.jl#L21-L28)
[Data Formats](#Data-Formats)
------------------------------
###
`Base.digits`Function
```
digits([T<:Integer], n::Integer; base::T = 10, pad::Integer = 1)
```
Return an array with element type `T` (default `Int`) of the digits of `n` in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indices, such that `n == sum(digits[k]*base^(k-1) for k=1:length(digits))`.
See also [`ndigits`](../math/index#Base.ndigits), [`digits!`](#Base.digits!), and for base 2 also [`bitstring`](#Base.bitstring), [`count_ones`](#Base.count_ones).
**Examples**
```
julia> digits(10)
2-element Vector{Int64}:
0
1
julia> digits(10, base = 2)
4-element Vector{Int64}:
0
1
0
1
julia> digits(-256, base = 10, pad = 5)
5-element Vector{Int64}:
-6
-5
-2
0
0
julia> n = rand(-999:999);
julia> n == evalpoly(13, digits(n, base = 13))
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L846-L883)###
`Base.digits!`Function
```
digits!(array, n::Integer; base::Integer = 10)
```
Fills an array of the digits of `n` in the given base. More significant digits are at higher indices. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled with zeros.
**Examples**
```
julia> digits!([2, 2, 2, 2], 10, base = 2)
4-element Vector{Int64}:
0
1
0
1
julia> digits!([2, 2, 2, 2, 2, 2], 10, base = 2)
6-element Vector{Int64}:
0
1
0
1
0
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L900-L925)###
`Base.bitstring`Function
```
bitstring(n)
```
A string giving the literal bit representation of a primitive type.
See also [`count_ones`](#Base.count_ones), [`count_zeros`](#Base.count_zeros), [`digits`](#Base.digits).
**Examples**
```
julia> bitstring(Int32(4))
"00000000000000000000000000000100"
julia> bitstring(2.2)
"0100000000000001100110011001100110011001100110011001100110011010"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L812-L827)###
`Base.parse`Function
```
parse(::Type{Platform}, triplet::AbstractString)
```
Parses a string platform triplet back into a `Platform` object.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/binaryplatforms.jl#L665-L669)
```
parse(type, str; base)
```
Parse a string as a number. For `Integer` types, a base can be specified (the default is 10). For floating-point types, the string is parsed as a decimal floating-point number. `Complex` types are parsed from decimal strings of the form `"R±Iim"` as a `Complex(R,I)` of the requested type; `"i"` or `"j"` can also be used instead of `"im"`, and `"R"` or `"Iim"` are also permitted. If the string does not contain a valid number, an error is raised.
`parse(Bool, str)` requires at least Julia 1.1.
**Examples**
```
julia> parse(Int, "1234")
1234
julia> parse(Int, "1234", base = 5)
194
julia> parse(Int, "afc", base = 16)
2812
julia> parse(Float64, "1.2e-3")
0.0012
julia> parse(Complex{Float64}, "3.2e-1 + 4.5im")
0.32 + 4.5im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/parse.jl#L7-L37)###
`Base.tryparse`Function
```
tryparse(type, str; base)
```
Like [`parse`](#Base.parse), but returns either a value of the requested type, or [`nothing`](../constants/index#Core.nothing) if the string does not contain a valid number.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/parse.jl#L229-L234)###
`Base.big`Function
```
big(x)
```
Convert a number to a maximum precision representation (typically [`BigInt`](#Base.GMP.BigInt) or `BigFloat`). See [`BigFloat`](#Base.MPFR.BigFloat-Tuple%7BAny,%20RoundingMode%7D) for information about some pitfalls with floating-point numbers.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gmp.jl#L462-L468)###
`Base.signed`Function
```
signed(T::Integer)
```
Convert an integer bitstype to the signed type of the same size.
**Examples**
```
julia> signed(UInt16)
Int16
julia> signed(UInt64)
Int64
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L61-L72)
```
signed(x)
```
Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as signed without checking for overflow.
See also: [`unsigned`](#Base.unsigned), [`sign`](../math/index#Base.sign), [`signbit`](../math/index#Base.signbit).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L211-L218)###
`Base.unsigned`Function
```
unsigned(T::Integer)
```
Convert an integer bitstype to the unsigned type of the same size.
**Examples**
```
julia> unsigned(Int16)
UInt16
julia> unsigned(UInt64)
UInt64
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L48-L59)###
`Base.float`Method
```
float(x)
```
Convert a number or array to a floating point data type.
See also: [`complex`](#Base.complex-Tuple%7BComplex%7D), [`oftype`](../base/index#Base.oftype), [`convert`](../base/index#Base.convert).
**Examples**
```
julia> float(1:1000)
1.0:1.0:1000.0
julia> float(typemax(Int32))
2.147483647e9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L253-L268)###
`Base.Math.significand`Function
```
significand(x)
```
Extract the significand (a.k.a. mantissa) of a floating-point number. If `x` is a non-zero finite number, then the result will be a number of the same type and sign as `x`, and whose absolute value is on the interval $[1,2)$. Otherwise `x` is returned.
**Examples**
```
julia> significand(15.2)
1.9
julia> significand(-15.2)
-1.9
julia> significand(-15.2) * 2^3
-15.2
julia> significand(-Inf), significand(Inf), significand(NaN)
(-Inf, Inf, NaN)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L872-L894)###
`Base.Math.exponent`Function
```
exponent(x::AbstractFloat) -> Int
```
Get the exponent of a normalized floating-point number. Returns the largest integer `y` such that `2^y ≤ abs(x)`.
**Examples**
```
julia> exponent(6.5)
2
julia> exponent(16.0)
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L828-L842)###
`Base.complex`Method
```
complex(r, [i])
```
Convert real numbers or arrays to complex. `i` defaults to zero.
**Examples**
```
julia> complex(7)
7 + 0im
julia> complex([1, 2, 3])
3-element Vector{Complex{Int64}}:
1 + 0im
2 + 0im
3 + 0im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L152-L168)###
`Base.bswap`Function
```
bswap(n)
```
Reverse the byte order of `n`.
(See also [`ntoh`](../io-network/index#Base.ntoh) and [`hton`](../io-network/index#Base.hton) to convert between the current native byte order and big-endian order.)
**Examples**
```
julia> a = bswap(0x10203040)
0x40302010
julia> bswap(a)
0x10203040
julia> string(1, base = 2)
"1"
julia> string(bswap(1), base = 2)
"100000000000000000000000000000000000000000000000000000000"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L368-L389)###
`Base.hex2bytes`Function
```
hex2bytes(itr)
```
Given an iterable `itr` of ASCII codes for a sequence of hexadecimal digits, returns a `Vector{UInt8}` of bytes corresponding to the binary representation: each successive pair of hexadecimal digits in `itr` gives the value of one byte in the return vector.
The length of `itr` must be even, and the returned array has half of the length of `itr`. See also [`hex2bytes!`](#Base.hex2bytes!) for an in-place version, and [`bytes2hex`](#Base.bytes2hex) for the inverse.
Calling `hex2bytes` with iterators producing `UInt8` values requires Julia 1.7 or later. In earlier versions, you can `collect` the iterator before calling `hex2bytes`.
**Examples**
```
julia> s = string(12345, base = 16)
"3039"
julia> hex2bytes(s)
2-element Vector{UInt8}:
0x30
0x39
julia> a = b"01abEF"
6-element Base.CodeUnits{UInt8, String}:
0x30
0x31
0x61
0x62
0x45
0x46
julia> hex2bytes(a)
3-element Vector{UInt8}:
0x01
0xab
0xef
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L782-L822)###
`Base.hex2bytes!`Function
```
hex2bytes!(dest::AbstractVector{UInt8}, itr)
```
Convert an iterable `itr` of bytes representing a hexadecimal string to its binary representation, similar to [`hex2bytes`](#Base.hex2bytes) except that the output is written in-place to `dest`. The length of `dest` must be half the length of `itr`.
Calling hex2bytes! with iterators producing UInt8 requires version 1.7. In earlier versions, you can collect the iterable before calling instead.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L834-L845)###
`Base.bytes2hex`Function
```
bytes2hex(itr) -> String
bytes2hex(io::IO, itr)
```
Convert an iterator `itr` of bytes to its hexadecimal string representation, either returning a `String` via `bytes2hex(itr)` or writing the string to an `io` stream via `bytes2hex(io, itr)`. The hexadecimal characters are all lowercase.
Calling `bytes2hex` with arbitrary iterators producing `UInt8` values requires Julia 1.7 or later. In earlier versions, you can `collect` the iterator before calling `bytes2hex`.
**Examples**
```
julia> a = string(12345, base = 16)
"3039"
julia> b = hex2bytes(a)
2-element Vector{UInt8}:
0x30
0x39
julia> bytes2hex(b)
"3039"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/util.jl#L871-L897)
[General Number Functions and Constants](#General-Number-Functions-and-Constants)
----------------------------------------------------------------------------------
###
`Base.one`Function
```
one(x)
one(T::type)
```
Return a multiplicative identity for `x`: a value such that `one(x)*x == x*one(x) == x`. Alternatively `one(T)` can take a type `T`, in which case `one` returns a multiplicative identity for any `x` of type `T`.
If possible, `one(x)` returns a value of the same type as `x`, and `one(T)` returns a value of type `T`. However, this may not be the case for types representing dimensionful quantities (e.g. time in days), since the multiplicative identity must be dimensionless. In that case, `one(x)` should return an identity value of the same precision (and shape, for matrices) as `x`.
If you want a quantity that is of the same type as `x`, or of type `T`, even if `x` is dimensionful, use [`oneunit`](#Base.oneunit) instead.
See also the [`identity`](../base/index#Base.identity) function, and `I` in [`LinearAlgebra`](../../stdlib/linearalgebra/index#man-linalg) for the identity matrix.
**Examples**
```
julia> one(3.7)
1.0
julia> one(Int)
1
julia> import Dates; one(Dates.Day(1))
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L299-L333)###
`Base.oneunit`Function
```
oneunit(x::T)
oneunit(T::Type)
```
Returns `T(one(x))`, where `T` is either the type of the argument or (if a type is passed) the argument. This differs from [`one`](#Base.one) for dimensionful quantities: `one` is dimensionless (a multiplicative identity) while `oneunit` is dimensionful (of the same type as `x`, or of type `T`).
**Examples**
```
julia> oneunit(3.7)
1.0
julia> import Dates; oneunit(Dates.Day)
1 day
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L339-L356)###
`Base.zero`Function
```
zero(x)
zero(::Type)
```
Get the additive identity element for the type of `x` (`x` can also specify the type itself).
See also [`iszero`](#Base.iszero), [`one`](#Base.one), [`oneunit`](#Base.oneunit), [`oftype`](../base/index#Base.oftype).
**Examples**
```
julia> zero(1)
0
julia> zero(big"2.0")
0.0
julia> zero(rand(2,2))
2×2 Matrix{Float64}:
0.0 0.0
0.0 0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L274-L295)###
`Base.im`Constant
```
im
```
The imaginary unit.
See also: [`imag`](../math/index#Base.imag), [`angle`](../math/index#Base.angle), [`complex`](#Base.complex-Tuple%7BComplex%7D).
**Examples**
```
julia> im * im
-1 + 0im
julia> (2.0 + 3im)^2
-5.0 + 12.0im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L20-L35)###
`Base.MathConstants.pi`Constant
```
π
pi
```
The constant pi.
Unicode `π` can be typed by writing `\pi` then pressing tab in the Julia REPL, and in many editors.
See also: [`sinpi`](../math/index#Base.Math.sinpi), [`sincospi`](../math/index#Base.Math.sincospi), [`deg2rad`](../math/index#Base.Math.deg2rad).
**Examples**
```
julia> pi
π = 3.1415926535897...
julia> 1/2pi
0.15915494309189535
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mathconstants.jl#L20-L38)###
`Base.MathConstants.ℯ`Constant
```
ℯ
e
```
The constant ℯ.
Unicode `ℯ` can be typed by writing `\euler` and pressing tab in the Julia REPL, and in many editors.
See also: [`exp`](#), [`cis`](../math/index#Base.cis), [`cispi`](../math/index#Base.cispi).
**Examples**
```
julia> ℯ
ℯ = 2.7182818284590...
julia> log(ℯ)
1
julia> ℯ^(im)π ≈ -1
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mathconstants.jl#L41-L62)###
`Base.MathConstants.catalan`Constant
```
catalan
```
Catalan's constant.
**Examples**
```
julia> Base.MathConstants.catalan
catalan = 0.9159655941772...
julia> sum(log(x)/(1+x^2) for x in 1:0.01:10^6) * 0.01
0.9159466120554123
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mathconstants.jl#L101-L114)###
`Base.MathConstants.eulergamma`Constant
```
γ
eulergamma
```
Euler's constant.
**Examples**
```
julia> Base.MathConstants.eulergamma
γ = 0.5772156649015...
julia> dx = 10^-6;
julia> sum(-exp(-x) * log(x) for x in dx:dx:100) * dx
0.5772078382499133
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mathconstants.jl#L65-L81)###
`Base.MathConstants.golden`Constant
```
φ
golden
```
The golden ratio.
**Examples**
```
julia> Base.MathConstants.golden
φ = 1.6180339887498...
julia> (2ans - 1)^2 ≈ 5
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mathconstants.jl#L84-L98)###
`Base.Inf`Constant
```
Inf, Inf64
```
Positive infinity of type [`Float64`](#Core.Float64).
See also: [`isfinite`](#Base.isfinite), [`typemax`](../base/index#Base.typemax), [`NaN`](#Base.NaN), [`Inf32`](#Base.Inf32).
**Examples**
```
julia> π/0
Inf
julia> +1.0 / -0.0
-Inf
julia> ℯ^-Inf
0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L35-L53)###
`Base.Inf32`Constant
```
Inf32
```
Positive infinity of type [`Float32`](#Core.Float32).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L19-L23)###
`Base.Inf16`Constant
```
Inf16
```
Positive infinity of type [`Float16`](#Core.Float16).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L7-L11)###
`Base.NaN`Constant
```
NaN, NaN64
```
A not-a-number value of type [`Float64`](#Core.Float64).
See also: [`isnan`](#Base.isnan), [`missing`](../base/index#Base.missing), [`NaN32`](#Base.NaN32), [`Inf`](#Base.Inf).
**Examples**
```
julia> 0/0
NaN
julia> Inf - Inf
NaN
julia> NaN == NaN, isequal(NaN, NaN), NaN === NaN
(false, true, true)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L57-L75)###
`Base.NaN32`Constant
```
NaN32
```
A not-a-number value of type [`Float32`](#Core.Float32).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L25-L29)###
`Base.NaN16`Constant
```
NaN16
```
A not-a-number value of type [`Float16`](#Core.Float16).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L13-L17)###
`Base.issubnormal`Function
```
issubnormal(f) -> Bool
```
Test whether a floating point number is subnormal.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L796-L800)###
`Base.isfinite`Function
```
isfinite(f) -> Bool
```
Test whether a number is finite.
**Examples**
```
julia> isfinite(5)
true
julia> isfinite(NaN32)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L64-L77)###
`Base.isinf`Function
```
isinf(f) -> Bool
```
Test whether a number is infinite.
See also: [`Inf`](#Base.Inf), [`iszero`](#Base.iszero), [`isfinite`](#Base.isfinite), [`isnan`](#Base.isnan).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L503-L509)###
`Base.isnan`Function
```
isnan(f) -> Bool
```
Test whether a number value is a NaN, an indeterminate value which is neither an infinity nor a finite number ("not a number").
See also: [`iszero`](#Base.iszero), [`isone`](#Base.isone), [`isinf`](#Base.isinf), [`ismissing`](../base/index#Base.ismissing).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L488-L495)###
`Base.iszero`Function
```
iszero(x)
```
Return `true` if `x == zero(x)`; if `x` is an array, this checks whether all of the elements of `x` are zero.
See also: [`isone`](#Base.isone), [`isinteger`](#Base.isinteger), [`isfinite`](#Base.isfinite), [`isnan`](#Base.isnan).
**Examples**
```
julia> iszero(0.0)
true
julia> iszero([1, 9, 0])
false
julia> iszero([false, 0, 0])
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L22-L41)###
`Base.isone`Function
```
isone(x)
```
Return `true` if `x == one(x)`; if `x` is an array, this checks whether `x` is an identity matrix.
**Examples**
```
julia> isone(1.0)
true
julia> isone([1 0; 0 2])
false
julia> isone([1 0; 0 true])
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L44-L61)###
`Base.nextfloat`Function
```
nextfloat(x::AbstractFloat, n::Integer)
```
The result of `n` iterative applications of `nextfloat` to `x` if `n >= 0`, or `-n` applications of [`prevfloat`](#Base.prevfloat) if `n < 0`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L679-L684)
```
nextfloat(x::AbstractFloat)
```
Return the smallest floating point number `y` of the same type as `x` such `x < y`. If no such `y` exists (e.g. if `x` is `Inf` or `NaN`), then return `x`.
See also: [`prevfloat`](#Base.prevfloat), [`eps`](#), [`issubnormal`](#Base.issubnormal).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L723-L730)###
`Base.prevfloat`Function
```
prevfloat(x::AbstractFloat, n::Integer)
```
The result of `n` iterative applications of `prevfloat` to `x` if `n >= 0`, or `-n` applications of [`nextfloat`](#Base.nextfloat) if `n < 0`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L733-L738)
```
prevfloat(x::AbstractFloat)
```
Return the largest floating point number `y` of the same type as `x` such `y < x`. If no such `y` exists (e.g. if `x` is `-Inf` or `NaN`), then return `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L741-L746)###
`Base.isinteger`Function
```
isinteger(x) -> Bool
```
Test whether `x` is numerically equal to some integer.
**Examples**
```
julia> isinteger(4.0)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L9-L19)###
`Base.isreal`Function
```
isreal(x) -> Bool
```
Test whether `x` or all its elements are numerically equal to some real number including infinities and NaNs. `isreal(x)` is true if `isequal(x, real(x))` is true.
**Examples**
```
julia> isreal(5.)
true
julia> isreal(Inf + 0im)
true
julia> isreal([4.; complex(0,1)])
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L124-L142)###
`Core.Float32`Method
```
Float32(x [, mode::RoundingMode])
```
Create a `Float32` from `x`. If `x` is not exactly representable then `mode` determines how `x` is rounded.
**Examples**
```
julia> Float32(1/3, RoundDown)
0.3333333f0
julia> Float32(1/3, RoundUp)
0.33333334f0
```
See [`RoundingMode`](../math/index#Base.Rounding.RoundingMode) for available rounding modes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1429-L1445)###
`Core.Float64`Method
```
Float64(x [, mode::RoundingMode])
```
Create a `Float64` from `x`. If `x` is not exactly representable then `mode` determines how `x` is rounded.
**Examples**
```
julia> Float64(pi, RoundDown)
3.141592653589793
julia> Float64(pi, RoundUp)
3.1415926535897936
```
See [`RoundingMode`](../math/index#Base.Rounding.RoundingMode) for available rounding modes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1448-L1464)###
`Base.Rounding.rounding`Function
```
rounding(T)
```
Get the current floating point rounding mode for type `T`, controlling the rounding of basic arithmetic functions ([`+`](../math/index#Base.:+), [`-`](#), [`*`](#), [`/`](../math/index#Base.:/) and [`sqrt`](#)) and type conversion.
See [`RoundingMode`](../math/index#Base.Rounding.RoundingMode) for available modes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L143-L151)###
`Base.Rounding.setrounding`Method
```
setrounding(T, mode)
```
Set the rounding mode of floating point type `T`, controlling the rounding of basic arithmetic functions ([`+`](../math/index#Base.:+), [`-`](#), [`*`](#), [`/`](../math/index#Base.:/) and [`sqrt`](#)) and type conversion. Other numerical functions may give incorrect or invalid values when using rounding modes other than the default [`RoundNearest`](../math/index#Base.Rounding.RoundNearest).
Note that this is currently only supported for `T == BigFloat`.
This function is not thread-safe. It will affect code running on all threads, but its behavior is undefined if called concurrently with computations that use the setting.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L124-L140)###
`Base.Rounding.setrounding`Method
```
setrounding(f::Function, T, mode)
```
Change the rounding mode of floating point type `T` for the duration of `f`. It is logically equivalent to:
```
old = rounding(T)
setrounding(T, mode)
f()
setrounding(T, old)
```
See [`RoundingMode`](../math/index#Base.Rounding.RoundingMode) for available rounding modes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L159-L171)###
`Base.Rounding.get_zero_subnormals`Function
```
get_zero_subnormals() -> Bool
```
Return `false` if operations on subnormal floating-point values ("denormals") obey rules for IEEE arithmetic, and `true` if they might be converted to zeros.
This function only affects the current thread.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L237-L246)###
`Base.Rounding.set_zero_subnormals`Function
```
set_zero_subnormals(yes::Bool) -> Bool
```
If `yes` is `false`, subsequent floating-point operations follow rules for IEEE arithmetic on subnormal values ("denormals"). Otherwise, floating-point operations are permitted (but not required) to convert subnormal inputs or outputs to zero. Returns `true` unless `yes==true` but the hardware does not support zeroing of subnormal numbers.
`set_zero_subnormals(true)` can speed up some computations on some hardware. However, it can break identities such as `(x-y==0) == (x==y)`.
This function only affects the current thread.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L220-L234)###
[Integers](#Integers)
###
`Base.count_ones`Function
```
count_ones(x::Integer) -> Integer
```
Number of ones in the binary representation of `x`.
**Examples**
```
julia> count_ones(7)
3
julia> count_ones(Int32(-1))
32
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L394-L407)###
`Base.count_zeros`Function
```
count_zeros(x::Integer) -> Integer
```
Number of zeros in the binary representation of `x`.
**Examples**
```
julia> count_zeros(Int32(2 ^ 16 - 1))
16
julia> count_zeros(-1)
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L436-L449)###
`Base.leading_zeros`Function
```
leading_zeros(x::Integer) -> Integer
```
Number of zeros leading the binary representation of `x`.
**Examples**
```
julia> leading_zeros(Int32(1))
31
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L410-L420)###
`Base.leading_ones`Function
```
leading_ones(x::Integer) -> Integer
```
Number of ones leading the binary representation of `x`.
**Examples**
```
julia> leading_ones(UInt32(2 ^ 32 - 2))
31
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L452-L462)###
`Base.trailing_zeros`Function
```
trailing_zeros(x::Integer) -> Integer
```
Number of zeros trailing the binary representation of `x`.
**Examples**
```
julia> trailing_zeros(2)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L423-L433)###
`Base.trailing_ones`Function
```
trailing_ones(x::Integer) -> Integer
```
Number of ones trailing the binary representation of `x`.
**Examples**
```
julia> trailing_ones(3)
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L465-L475)###
`Base.isodd`Function
```
isodd(x::Number) -> Bool
```
Return `true` if `x` is an odd integer (that is, an integer not divisible by 2), and `false` otherwise.
Non-`Integer` arguments require Julia 1.7 or later.
**Examples**
```
julia> isodd(9)
true
julia> isodd(10)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L99-L115)###
`Base.iseven`Function
```
iseven(x::Number) -> Bool
```
Return `true` if `x` is an even integer (that is, an integer divisible by 2), and `false` otherwise.
Non-`Integer` arguments require Julia 1.7 or later.
**Examples**
```
julia> iseven(9)
false
julia> iseven(10)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L119-L135)###
`Core.@int128_str`Macro
```
@int128_str str
@int128_str(str)
```
`@int128_str` parses a string into a Int128. Throws an `ArgumentError` if the string is not a valid integer.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L656-L662)###
`Core.@uint128_str`Macro
```
@uint128_str str
@uint128_str(str)
```
`@uint128_str` parses a string into a UInt128. Throws an `ArgumentError` if the string is not a valid integer.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L667-L673)
[BigFloats and BigInts](#BigFloats-and-BigInts)
------------------------------------------------
The [`BigFloat`](#Base.MPFR.BigFloat) and [`BigInt`](#Base.GMP.BigInt) types implements arbitrary-precision floating point and integer arithmetic, respectively. For [`BigFloat`](#Base.MPFR.BigFloat) the [GNU MPFR library](https://www.mpfr.org/) is used, and for [`BigInt`](#Base.GMP.BigInt) the [GNU Multiple Precision Arithmetic Library (GMP)](https://gmplib.org) is used.
###
`Base.MPFR.BigFloat`Method
```
BigFloat(x::Union{Real, AbstractString} [, rounding::RoundingMode=rounding(BigFloat)]; [precision::Integer=precision(BigFloat)])
```
Create an arbitrary precision floating point number from `x`, with precision `precision`. The `rounding` argument specifies the direction in which the result should be rounded if the conversion cannot be done exactly. If not provided, these are set by the current global values.
`BigFloat(x::Real)` is the same as `convert(BigFloat,x)`, except if `x` itself is already `BigFloat`, in which case it will return a value with the precision set to the current global precision; `convert` will always return `x`.
`BigFloat(x::AbstractString)` is identical to [`parse`](#Base.parse). This is provided for convenience since decimal literals are converted to `Float64` when parsed, so `BigFloat(2.1)` may not yield what you expect.
See also:
* [`@big_str`](#Core.@big_str)
* [`rounding`](#Base.Rounding.rounding) and [`setrounding`](#Base.Rounding.setrounding-Tuple%7BType,%20Any%7D)
* [`precision`](#Base.precision) and [`setprecision`](#Base.MPFR.setprecision)
`precision` as a keyword argument requires at least Julia 1.1. In Julia 1.0 `precision` is the second positional argument (`BigFloat(x, precision)`).
**Examples**
```
julia> BigFloat(2.1) # 2.1 here is a Float64
2.100000000000000088817841970012523233890533447265625
julia> BigFloat("2.1") # the closest BigFloat to 2.1
2.099999999999999999999999999999999999999999999999999999999999999999999999999986
julia> BigFloat("2.1", RoundUp)
2.100000000000000000000000000000000000000000000000000000000000000000000000000021
julia> BigFloat("2.1", RoundUp, precision=128)
2.100000000000000000000000000000000000007
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mpfr.jl#L139-L177)###
`Base.precision`Function
```
precision(num::AbstractFloat; base::Integer=2)
precision(T::Type; base::Integer=2)
```
Get the precision of a floating point number, as defined by the effective number of bits in the significand, or the precision of a floating-point type `T` (its current default, if `T` is a variable-precision type like [`BigFloat`](#Base.MPFR.BigFloat)).
If `base` is specified, then it returns the maximum corresponding number of significand digits in that base.
The `base` keyword requires at least Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L640-L653)###
`Base.MPFR.setprecision`Function
```
setprecision([T=BigFloat,] precision::Int; base=2)
```
Set the precision (in bits, by default) to be used for `T` arithmetic. If `base` is specified, then the precision is the minimum required to give at least `precision` digits in the given `base`.
This function is not thread-safe. It will affect code running on all threads, but its behavior is undefined if called concurrently with computations that use the setting.
The `base` keyword requires at least Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mpfr.jl#L824-L839)
```
setprecision(f::Function, [T=BigFloat,] precision::Integer; base=2)
```
Change the `T` arithmetic precision (in the given `base`) for the duration of `f`. It is logically equivalent to:
```
old = precision(BigFloat)
setprecision(BigFloat, precision)
f()
setprecision(BigFloat, old)
```
Often used as `setprecision(T, precision) do ... end`
Note: `nextfloat()`, `prevfloat()` do not use the precision mentioned by `setprecision`.
The `base` keyword requires at least Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/mpfr.jl#L940-L958)###
`Base.GMP.BigInt`Method
```
BigInt(x)
```
Create an arbitrary precision integer. `x` may be an `Int` (or anything that can be converted to an `Int`). The usual mathematical operators are defined for this type, and results are promoted to a [`BigInt`](#Base.GMP.BigInt).
Instances can be constructed from strings via [`parse`](#Base.parse), or using the `big` string literal.
**Examples**
```
julia> parse(BigInt, "42")
42
julia> big"313"
313
julia> BigInt(10)^19
10000000000000000000
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gmp.jl#L62-L83)###
`Core.@big_str`Macro
```
@big_str str
@big_str(str)
```
Parse a string into a [`BigInt`](#Base.GMP.BigInt) or [`BigFloat`](#Base.MPFR.BigFloat), and throw an `ArgumentError` if the string is not a valid number. For integers `_` is allowed in the string as a separator.
**Examples**
```
julia> big"123_456"
123456
julia> big"7891.5"
7891.5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L678-L694)
| programming_docs |
julia Sorting and Related Functions Sorting and Related Functions
=============================
Julia has an extensive, flexible API for sorting and interacting with already-sorted arrays of values. By default, Julia picks reasonable algorithms and sorts in standard ascending order:
```
julia> sort([2,3,1])
3-element Vector{Int64}:
1
2
3
```
You can easily sort in reverse order as well:
```
julia> sort([2,3,1], rev=true)
3-element Vector{Int64}:
3
2
1
```
To sort an array in-place, use the "bang" version of the sort function:
```
julia> a = [2,3,1];
julia> sort!(a);
julia> a
3-element Vector{Int64}:
1
2
3
```
Instead of directly sorting an array, you can compute a permutation of the array's indices that puts the array into sorted order:
```
julia> v = randn(5)
5-element Array{Float64,1}:
0.297288
0.382396
-0.597634
-0.0104452
-0.839027
julia> p = sortperm(v)
5-element Array{Int64,1}:
5
3
4
1
2
julia> v[p]
5-element Array{Float64,1}:
-0.839027
-0.597634
-0.0104452
0.297288
0.382396
```
Arrays can easily be sorted according to an arbitrary transformation of their values:
```
julia> sort(v, by=abs)
5-element Array{Float64,1}:
-0.0104452
0.297288
0.382396
-0.597634
-0.839027
```
Or in reverse order by a transformation:
```
julia> sort(v, by=abs, rev=true)
5-element Array{Float64,1}:
-0.839027
-0.597634
0.382396
0.297288
-0.0104452
```
If needed, the sorting algorithm can be chosen:
```
julia> sort(v, alg=InsertionSort)
5-element Array{Float64,1}:
-0.839027
-0.597634
-0.0104452
0.297288
0.382396
```
All the sorting and order related functions rely on a "less than" relation defining a total order on the values to be manipulated. The `isless` function is invoked by default, but the relation can be specified via the `lt` keyword.
[Sorting Functions](#Sorting-Functions)
----------------------------------------
###
`Base.sort!`Function
```
sort!(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Sort the vector `v` in place. [`QuickSort`](#Base.Sort.QuickSort) is used by default for numeric arrays while [`MergeSort`](#Base.Sort.MergeSort) is used for other arrays. You can specify an algorithm to use via the `alg` keyword (see [Sorting Algorithms](#Sorting-Algorithms) for available algorithms). The `by` keyword lets you provide a function that will be applied to each element before comparison; the `lt` keyword allows providing a custom "less than" function (note that for every `x` and `y`, only one of `lt(x,y)` and `lt(y,x)` can return `true`); use `rev=true` to reverse the sorting order. These options are independent and can be used together in all possible combinations: if both `by` and `lt` are specified, the `lt` function is applied to the result of the `by` function; `rev=true` reverses whatever ordering specified via the `by` and `lt` keywords.
**Examples**
```
julia> v = [3, 1, 2]; sort!(v); v
3-element Vector{Int64}:
1
2
3
julia> v = [3, 1, 2]; sort!(v, rev = true); v
3-element Vector{Int64}:
3
2
1
julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[1]); v
3-element Vector{Tuple{Int64, String}}:
(1, "c")
(2, "b")
(3, "a")
julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[2]); v
3-element Vector{Tuple{Int64, String}}:
(3, "a")
(2, "b")
(1, "c")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L664-L703)
```
sort!(A; dims::Integer, alg::Algorithm=defalg(A), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Sort the multidimensional array `A` along dimension `dims`. See [`sort!`](#Base.sort!) for a description of possible keyword arguments.
To sort slices of an array, refer to [`sortslices`](#Base.sortslices).
This function requires at least Julia 1.1.
**Examples**
```
julia> A = [4 3; 1 2]
2×2 Matrix{Int64}:
4 3
1 2
julia> sort!(A, dims = 1); A
2×2 Matrix{Int64}:
1 2
4 3
julia> sort!(A, dims = 2); A
2×2 Matrix{Int64}:
1 2
3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L1058-L1086)###
`Base.sort`Function
```
sort(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Variant of [`sort!`](#Base.sort!) that returns a sorted copy of `v` leaving `v` itself unmodified.
**Examples**
```
julia> v = [3, 1, 2];
julia> sort(v)
3-element Vector{Int64}:
1
2
3
julia> v
3-element Vector{Int64}:
3
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L747-L768)
```
sort(A; dims::Integer, alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Sort a multidimensional array `A` along the given dimension. See [`sort!`](#Base.sort!) for a description of possible keyword arguments.
To sort slices of an array, refer to [`sortslices`](#Base.sortslices).
**Examples**
```
julia> A = [4 3; 1 2]
2×2 Matrix{Int64}:
4 3
1 2
julia> sort(A, dims = 1)
2×2 Matrix{Int64}:
1 2
4 3
julia> sort(A, dims = 2)
2×2 Matrix{Int64}:
3 4
1 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L1000-L1026)###
`Base.sortperm`Function
```
sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Return a permutation vector `I` that puts `v[I]` in sorted order. The order is specified using the same keywords as [`sort!`](#Base.sort!). The permutation is guaranteed to be stable even if the sorting algorithm is unstable, meaning that indices of equal elements appear in ascending order.
See also [`sortperm!`](#Base.Sort.sortperm!), [`partialsortperm`](#Base.Sort.partialsortperm), [`invperm`](../arrays/index#Base.invperm), [`indexin`](../collections/index#Base.indexin).
**Examples**
```
julia> v = [3, 1, 2];
julia> p = sortperm(v)
3-element Vector{Int64}:
2
3
1
julia> v[p]
3-element Vector{Int64}:
1
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L877-L903)###
`Base.Sort.InsertionSort`Constant
```
InsertionSort
```
Indicate that a sorting function should use the insertion sort algorithm. Insertion sort traverses the collection one element at a time, inserting each element into its correct, sorted position in the output list.
Characteristics:
* *stable*: preserves the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case).
* *in-place* in memory.
* *quadratic performance* in the number of elements to be sorted: it is well-suited to small collections but should not be used for large ones.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L443-L458)###
`Base.Sort.MergeSort`Constant
```
MergeSort
```
Indicate that a sorting function should use the merge sort algorithm. Merge sort divides the collection into subcollections and repeatedly merges them, sorting each subcollection at each step, until the entire collection has been recombined in sorted form.
Characteristics:
* *stable*: preserves the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case).
* *not in-place* in memory.
* *divide-and-conquer* sort strategy.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L475-L490)###
`Base.Sort.QuickSort`Constant
```
QuickSort
```
Indicate that a sorting function should use the quick sort algorithm, which is *not* stable.
Characteristics:
* *not stable*: does not preserve the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case).
* *in-place* in memory.
* *divide-and-conquer*: sort strategy similar to [`MergeSort`](#Base.Sort.MergeSort).
* *good performance* for large collections.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L460-L473)###
`Base.Sort.PartialQuickSort`Type
```
PartialQuickSort{T <: Union{Integer,OrdinalRange}}
```
Indicate that a sorting function should use the partial quick sort algorithm. Partial quick sort returns the smallest `k` elements sorted from smallest to largest, finding them and sorting them using [`QuickSort`](#Base.Sort.QuickSort).
Characteristics:
* *not stable*: does not preserve the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case).
* *in-place* in memory.
* *divide-and-conquer*: sort strategy similar to [`MergeSort`](#Base.Sort.MergeSort).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L424-L437)###
`Base.Sort.sortperm!`Function
```
sortperm!(ix, v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false)
```
Like [`sortperm`](#Base.sortperm), but accepts a preallocated index vector `ix`. If `initialized` is `false` (the default), `ix` is initialized to contain the values `1:length(v)`.
**Examples**
```
julia> v = [3, 1, 2]; p = zeros(Int, 3);
julia> sortperm!(p, v); p
3-element Vector{Int64}:
2
3
1
julia> v[p]
3-element Vector{Int64}:
1
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L931-L953)###
`Base.sortslices`Function
```
sortslices(A; dims, alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Sort slices of an array `A`. The required keyword argument `dims` must be either an integer or a tuple of integers. It specifies the dimension(s) over which the slices are sorted.
E.g., if `A` is a matrix, `dims=1` will sort rows, `dims=2` will sort columns. Note that the default comparison function on one dimensional slices sorts lexicographically.
For the remaining keyword arguments, see the documentation of [`sort!`](#Base.sort!).
**Examples**
```
julia> sortslices([7 3 5; -1 6 4; 9 -2 8], dims=1) # Sort rows
3×3 Matrix{Int64}:
-1 6 4
7 3 5
9 -2 8
julia> sortslices([7 3 5; -1 6 4; 9 -2 8], dims=1, lt=(x,y)->isless(x[2],y[2]))
3×3 Matrix{Int64}:
9 -2 8
7 3 5
-1 6 4
julia> sortslices([7 3 5; -1 6 4; 9 -2 8], dims=1, rev=true)
3×3 Matrix{Int64}:
9 -2 8
7 3 5
-1 6 4
julia> sortslices([7 3 5; 6 -1 -4; 9 -2 8], dims=2) # Sort columns
3×3 Matrix{Int64}:
3 5 7
-1 -4 6
-2 8 9
julia> sortslices([7 3 5; 6 -1 -4; 9 -2 8], dims=2, alg=InsertionSort, lt=(x,y)->isless(x[2],y[2]))
3×3 Matrix{Int64}:
5 3 7
-4 -1 6
8 -2 9
julia> sortslices([7 3 5; 6 -1 -4; 9 -2 8], dims=2, rev=true)
3×3 Matrix{Int64}:
7 5 3
6 -4 -1
9 8 -2
```
**Higher dimensions**
`sortslices` extends naturally to higher dimensions. E.g., if `A` is a a 2x2x2 array, `sortslices(A, dims=3)` will sort slices within the 3rd dimension, passing the 2x2 slices `A[:, :, 1]` and `A[:, :, 2]` to the comparison function. Note that while there is no default order on higher-dimensional slices, you may use the `by` or `lt` keyword argument to specify such an order.
If `dims` is a tuple, the order of the dimensions in `dims` is relevant and specifies the linear order of the slices. E.g., if `A` is three dimensional and `dims` is `(1, 2)`, the orderings of the first two dimensions are re-arranged such that the slices (of the remaining third dimension) are sorted. If `dims` is `(2, 1)` instead, the same slices will be taken, but the result order will be row-major instead.
**Higher dimensional examples**
```
julia> A = permutedims(reshape([4 3; 2 1; 'A' 'B'; 'C' 'D'], (2, 2, 2)), (1, 3, 2))
2×2×2 Array{Any, 3}:
[:, :, 1] =
4 3
2 1
[:, :, 2] =
'A' 'B'
'C' 'D'
julia> sortslices(A, dims=(1,2))
2×2×2 Array{Any, 3}:
[:, :, 1] =
1 3
2 4
[:, :, 2] =
'D' 'B'
'C' 'A'
julia> sortslices(A, dims=(2,1))
2×2×2 Array{Any, 3}:
[:, :, 1] =
1 2
3 4
[:, :, 2] =
'D' 'C'
'B' 'A'
julia> sortslices(reshape([5; 4; 3; 2; 1], (1,1,5)), dims=3, by=x->x[1,1])
1×1×5 Array{Int64, 3}:
[:, :, 1] =
1
[:, :, 2] =
2
[:, :, 3] =
3
[:, :, 4] =
4
[:, :, 5] =
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1739-L1855)
[Order-Related Functions](#Order-Related-Functions)
----------------------------------------------------
###
`Base.issorted`Function
```
issorted(v, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
```
Test whether a vector is in sorted order. The `lt`, `by` and `rev` keywords modify what order is considered to be sorted just as they do for [`sort`](#Base.sort).
**Examples**
```
julia> issorted([1, 2, 3])
true
julia> issorted([(1, "b"), (2, "a")], by = x -> x[1])
true
julia> issorted([(1, "b"), (2, "a")], by = x -> x[2])
false
julia> issorted([(1, "b"), (2, "a")], by = x -> x[2], rev=true)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L71-L91)###
`Base.Sort.searchsorted`Function
```
searchsorted(a, x; by=<transform>, lt=<comparison>, rev=false)
```
Return the range of indices of `a` which compare as equal to `x` (using binary search) according to the order specified by the `by`, `lt` and `rev` keywords, assuming that `a` is already sorted in that order. Return an empty range located at the insertion point if `a` does not contain values equal to `x`.
See also: [`insorted`](#Base.Sort.insorted), [`searchsortedfirst`](#Base.Sort.searchsortedfirst), [`sort`](#Base.sort), [`findall`](#).
**Examples**
```
julia> searchsorted([1, 2, 4, 5, 5, 7], 4) # single match
3:3
julia> searchsorted([1, 2, 4, 5, 5, 7], 5) # multiple matches
4:5
julia> searchsorted([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
3:2
julia> searchsorted([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
7:6
julia> searchsorted([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
1:0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L298-L325)###
`Base.Sort.searchsortedfirst`Function
```
searchsortedfirst(a, x; by=<transform>, lt=<comparison>, rev=false)
```
Return the index of the first value in `a` greater than or equal to `x`, according to the specified order. Return `lastindex(a) + 1` if `x` is greater than all values in `a`. `a` is assumed to be sorted.
See also: [`searchsortedlast`](#Base.Sort.searchsortedlast), [`searchsorted`](#Base.Sort.searchsorted), [`findfirst`](#).
**Examples**
```
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 4) # single match
3
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 5) # multiple matches
4
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
3
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
7
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L327-L353)###
`Base.Sort.searchsortedlast`Function
```
searchsortedlast(a, x; by=<transform>, lt=<comparison>, rev=false)
```
Return the index of the last value in `a` less than or equal to `x`, according to the specified order. Return `firstindex(a) - 1` if `x` is less than all values in `a`. `a` is assumed to be sorted.
**Examples**
```
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 4) # single match
3
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 5) # multiple matches
5
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
2
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
6
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L355-L379)###
`Base.Sort.insorted`Function
```
insorted(a, x; by=<transform>, lt=<comparison>, rev=false) -> Bool
```
Determine whether an item is in the given sorted collection, in the sense that it is [`==`](../math/index#Base.:==) to one of the values of the collection according to the order specified by the `by`, `lt` and `rev` keywords, assuming that `a` is already sorted in that order, see [`sort`](#Base.sort) for the keywords.
See also [`in`](../collections/index#Base.in).
**Examples**
```
julia> insorted(4, [1, 2, 4, 5, 5, 7]) # single match
true
julia> insorted(5, [1, 2, 4, 5, 5, 7]) # multiple matches
true
julia> insorted(3, [1, 2, 4, 5, 5, 7]) # no match
false
julia> insorted(9, [1, 2, 4, 5, 5, 7]) # no match
false
julia> insorted(0, [1, 2, 4, 5, 5, 7]) # no match
false
```
`insorted` was added in Julia 1.6.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L381-L411)###
`Base.Sort.partialsort!`Function
```
partialsort!(v, k; by=<transform>, lt=<comparison>, rev=false)
```
Partially sort the vector `v` in place, according to the order specified by `by`, `lt` and `rev` so that the value at index `k` (or range of adjacent values if `k` is a range) occurs at the position where it would appear if the array were fully sorted via a non-stable algorithm. If `k` is a single index, that value is returned; if `k` is a range, an array of values at those indices is returned. Note that `partialsort!` does not fully sort the input array.
**Examples**
```
julia> a = [1, 2, 4, 3, 4]
5-element Vector{Int64}:
1
2
4
3
4
julia> partialsort!(a, 4)
4
julia> a
5-element Vector{Int64}:
1
2
3
4
4
julia> a = [1, 2, 4, 3, 4]
5-element Vector{Int64}:
1
2
4
3
4
julia> partialsort!(a, 4, rev=true)
2
julia> a
5-element Vector{Int64}:
4
4
3
2
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L105-L155)###
`Base.Sort.partialsort`Function
```
partialsort(v, k, by=<transform>, lt=<comparison>, rev=false)
```
Variant of [`partialsort!`](#Base.Sort.partialsort!) which copies `v` before partially sorting it, thereby returning the same thing as `partialsort!` but leaving `v` unmodified.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L160-L165)###
`Base.Sort.partialsortperm`Function
```
partialsortperm(v, k; by=<transform>, lt=<comparison>, rev=false)
```
Return a partial permutation `I` of the vector `v`, so that `v[I]` returns values of a fully sorted version of `v` at index `k`. If `k` is a range, a vector of indices is returned; if `k` is an integer, a single index is returned. The order is specified using the same keywords as `sort!`. The permutation is stable, meaning that indices of equal elements appear in ascending order.
Note that this function is equivalent to, but more efficient than, calling `sortperm(...)[k]`.
**Examples**
```
julia> v = [3, 1, 2, 1];
julia> v[partialsortperm(v, 1)]
1
julia> p = partialsortperm(v, 1:3)
3-element view(::Vector{Int64}, 1:3) with eltype Int64:
2
4
3
julia> v[p]
3-element Vector{Int64}:
1
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L773-L803)###
`Base.Sort.partialsortperm!`Function
```
partialsortperm!(ix, v, k; by=<transform>, lt=<comparison>, rev=false, initialized=false)
```
Like [`partialsortperm`](#Base.Sort.partialsortperm), but accepts a preallocated index vector `ix` the same size as `v`, which is used to store (a permutation of) the indices of `v`.
If the index vector `ix` is initialized with the indices of `v` (or a permutation thereof), `initialized` should be set to `true`.
If `initialized` is `false` (the default), then `ix` is initialized to contain the indices of `v`.
If `initialized` is `true`, but `ix` does not contain (a permutation of) the indices of `v`, the behavior of `partialsortperm!` is undefined.
(Typically, the indices of `v` will be `1:length(v)`, although if `v` has an alternative array type with non-one-based indices, such as an `OffsetArray`, `ix` must also be an `OffsetArray` with the same indices, and must contain as values (a permutation of) these same indices.)
Upon return, `ix` is guaranteed to have the indices `k` in their sorted positions, such that
```
partialsortperm!(ix, v, k);
v[ix[k]] == partialsort(v, k)
```
The return value is the `k`th element of `ix` if `k` is an integer, or view into `ix` if `k` is a range.
**Examples**
```
julia> v = [3, 1, 2, 1];
julia> ix = Vector{Int}(undef, 4);
julia> partialsortperm!(ix, v, 1)
2
julia> ix = [1:4;];
julia> partialsortperm!(ix, v, 2:3, initialized=true)
2-element view(::Vector{Int64}, 2:3) with eltype Int64:
4
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sort.jl#L807-L851)
[Sorting Algorithms](#Sorting-Algorithms)
------------------------------------------
There are currently four sorting algorithms available in base Julia:
* [`InsertionSort`](#Base.Sort.InsertionSort)
* [`QuickSort`](#Base.Sort.QuickSort)
* [`PartialQuickSort(k)`](#Base.Sort.PartialQuickSort)
* [`MergeSort`](#Base.Sort.MergeSort)
`InsertionSort` is an O(n^2) stable sorting algorithm. It is efficient for very small `n`, and is used internally by `QuickSort`.
`QuickSort` is an O(n log n) sorting algorithm which is in-place, very fast, but not stable – i.e. elements which are considered equal will not remain in the same order in which they originally appeared in the array to be sorted. `QuickSort` is the default algorithm for numeric values, including integers and floats.
`PartialQuickSort(k)` is similar to `QuickSort`, but the output array is only sorted up to index `k` if `k` is an integer, or in the range of `k` if `k` is an `OrdinalRange`. For example:
```
x = rand(1:500, 100)
k = 50
k2 = 50:100
s = sort(x; alg=QuickSort)
ps = sort(x; alg=PartialQuickSort(k))
qs = sort(x; alg=PartialQuickSort(k2))
map(issorted, (s, ps, qs)) # => (true, false, false)
map(x->issorted(x[1:k]), (s, ps, qs)) # => (true, true, false)
map(x->issorted(x[k2]), (s, ps, qs)) # => (true, false, true)
s[1:k] == ps[1:k] # => true
s[k2] == qs[k2] # => true
```
`MergeSort` is an O(n log n) stable sorting algorithm but is not in-place – it requires a temporary array of half the size of the input array – and is typically not quite as fast as `QuickSort`. It is the default algorithm for non-numeric data.
The default sorting algorithms are chosen on the basis that they are fast and stable, or *appear* to be so. For numeric types indeed, `QuickSort` is selected as it is faster and indistinguishable in this case from a stable sort (unless the array records its mutations in some way). The stability property comes at a non-negligible cost, so if you don't need it, you may want to explicitly specify your preferred algorithm, e.g. `sort!(v, alg=QuickSort)`.
The mechanism by which Julia picks default sorting algorithms is implemented via the `Base.Sort.defalg` function. It allows a particular algorithm to be registered as the default in all sorting functions for specific arrays. For example, here are the two default methods from [`sort.jl`](https://github.com/JuliaLang/julia/blob/master/base/sort.jl):
```
defalg(v::AbstractArray) = MergeSort
defalg(v::AbstractArray{<:Number}) = QuickSort
```
As for numeric arrays, choosing a non-stable default algorithm for array types for which the notion of a stable sort is meaningless (i.e. when two values comparing equal can not be distinguished) may make sense.
[Alternate orderings](#Alternate-orderings)
--------------------------------------------
By default, `sort` and related functions use [`isless`](../base/index#Base.isless) to compare two elements in order to determine which should come first. The [`Base.Order.Ordering`](#Base.Order.Ordering) abstract type provides a mechanism for defining alternate orderings on the same set of elements. Instances of `Ordering` define a [total order](https://en.wikipedia.org/wiki/Total_order) on a set of elements, so that for any elements `a`, `b`, `c` the following hold:
* Exactly one of the following is true: `a` is less than `b`, `b` is less than `a`, or `a` and `b` are equal (according to [`isequal`](../base/index#Base.isequal)).
* The relation is transitive - if `a` is less than `b` and `b` is less than `c` then `a` is less than `c`.
The [`Base.Order.lt`](#Base.Order.lt) function works as a generalization of `isless` to test whether `a` is less than `b` according to a given order.
###
`Base.Order.Ordering`Type
```
Base.Order.Ordering
```
Abstract type which represents a total order on some set of elements.
Use [`Base.Order.lt`](#Base.Order.lt) to compare two elements according to the ordering.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L21-L27)###
`Base.Order.lt`Function
```
lt(o::Ordering, a, b)
```
Test whether `a` is less than `b` according to the ordering `o`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L112-L116)###
`Base.Order.ord`Function
```
ord(lt, by, rev::Union{Bool, Nothing}, order::Ordering=Forward)
```
Construct an [`Ordering`](#Base.Order.Ordering) object from the same arguments used by [`sort!`](#Base.sort!). Elements are first transformed by the function `by` (which may be [`identity`](../base/index#Base.identity)) and are then compared according to either the function `lt` or an existing ordering `order`. `lt` should be [`isless`](../base/index#Base.isless) or a function which obeys similar rules. Finally, the resulting order is reversed if `rev=true`.
Passing an `lt` other than `isless` along with an `order` other than [`Base.Order.Forward`](#Base.Order.Forward) or [`Base.Order.Reverse`](#Base.Order.Reverse) is not permitted, otherwise all options are independent and can be used together in all possible combinations.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L141-L156)###
`Base.Order.Forward`Constant
```
Base.Order.Forward
```
Default ordering according to [`isless`](../base/index#Base.isless).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L59-L63)###
`Base.Order.ReverseOrdering`Type
```
ReverseOrdering(fwd::Ordering=Forward)
```
A wrapper which reverses an ordering.
For a given `Ordering` `o`, the following holds for all `a`, `b`:
```
lt(ReverseOrdering(o), a, b) == lt(o, b, a)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L32-L40)###
`Base.Order.Reverse`Constant
```
Base.Order.Reverse
```
Reverse ordering according to [`isless`](../base/index#Base.isless).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L66-L70)###
`Base.Order.By`Type
```
By(by, order::Ordering=Forward)
```
`Ordering` which applies `order` to elements after they have been transformed by the function `by`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L73-L78)###
`Base.Order.Lt`Type
```
Lt(lt)
```
`Ordering` which calls `lt(a, b)` to compare elements. `lt` should obey the same rules as implementations of [`isless`](../base/index#Base.isless).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L87-L92)###
`Base.Order.Perm`Type
```
Perm(order::Ordering, data::AbstractVector)
```
`Ordering` on the indices of `data` where `i` is less than `j` if `data[i]` is less than `data[j]` according to `order`. In the case that `data[i]` and `data[j]` are equal, `i` and `j` are compared by numeric value.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ordering.jl#L97-L103)
| programming_docs |
julia Filesystem Filesystem
==========
###
`Base.Filesystem.pwd`Function
```
pwd() -> AbstractString
```
Get the current working directory.
See also: [`cd`](#Base.Filesystem.cd-Tuple%7BAbstractString%7D), [`tempdir`](#Base.Filesystem.tempdir).
**Examples**
```
julia> pwd()
"/home/JuliaUser"
julia> cd("/home/JuliaUser/Projects/julia")
julia> pwd()
"/home/JuliaUser/Projects/julia"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L34-L51)###
`Base.Filesystem.cd`Method
```
cd(dir::AbstractString=homedir())
```
Set the current working directory.
See also: [`pwd`](#Base.Filesystem.pwd), [`mkdir`](#Base.Filesystem.mkdir), [`mkpath`](#Base.Filesystem.mkpath), [`mktempdir`](#Base.Filesystem.mktempdir-Tuple%7BAbstractString%7D).
**Examples**
```
julia> cd("/home/JuliaUser/Projects/julia")
julia> pwd()
"/home/JuliaUser/Projects/julia"
julia> cd()
julia> pwd()
"/home/JuliaUser"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L69-L88)###
`Base.Filesystem.cd`Method
```
cd(f::Function, dir::AbstractString=homedir())
```
Temporarily change the current working directory to `dir`, apply function `f` and finally return to the original directory.
**Examples**
```
julia> pwd()
"/home/JuliaUser"
julia> cd(readdir, "/home/JuliaUser/Projects/julia")
34-element Array{String,1}:
".circleci"
".freebsdci.sh"
".git"
".gitattributes"
".github"
⋮
"test"
"ui"
"usr"
"usr-staging"
julia> pwd()
"/home/JuliaUser"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L119-L146)###
`Base.Filesystem.readdir`Function
```
readdir(dir::AbstractString=pwd();
join::Bool = false,
sort::Bool = true,
) -> Vector{String}
```
Return the names in the directory `dir` or the current working directory if not given. When `join` is false, `readdir` returns just the names in the directory as is; when `join` is true, it returns `joinpath(dir, name)` for each `name` so that the returned strings are full paths. If you want to get absolute paths back, call `readdir` with an absolute directory path and `join` set to true.
By default, `readdir` sorts the list of names it returns. If you want to skip sorting the names and get them in the order that the file system lists them, you can use `readdir(dir, sort=false)` to opt out of sorting.
The `join` and `sort` keyword arguments require at least Julia 1.4.
**Examples**
```
julia> cd("/home/JuliaUser/dev/julia")
julia> readdir()
30-element Array{String,1}:
".appveyor.yml"
".git"
".gitattributes"
⋮
"ui"
"usr"
"usr-staging"
julia> readdir(join=true)
30-element Array{String,1}:
"/home/JuliaUser/dev/julia/.appveyor.yml"
"/home/JuliaUser/dev/julia/.git"
"/home/JuliaUser/dev/julia/.gitattributes"
⋮
"/home/JuliaUser/dev/julia/ui"
"/home/JuliaUser/dev/julia/usr"
"/home/JuliaUser/dev/julia/usr-staging"
julia> readdir("base")
145-element Array{String,1}:
".gitignore"
"Base.jl"
"Enums.jl"
⋮
"version_git.sh"
"views.jl"
"weakkeydict.jl"
julia> readdir("base", join=true)
145-element Array{String,1}:
"base/.gitignore"
"base/Base.jl"
"base/Enums.jl"
⋮
"base/version_git.sh"
"base/views.jl"
"base/weakkeydict.jl"```
julia> readdir(abspath("base"), join=true)
145-element Array{String,1}:
"/home/JuliaUser/dev/julia/base/.gitignore"
"/home/JuliaUser/dev/julia/base/Base.jl"
"/home/JuliaUser/dev/julia/base/Enums.jl"
⋮
"/home/JuliaUser/dev/julia/base/version_git.sh"
"/home/JuliaUser/dev/julia/base/views.jl"
"/home/JuliaUser/dev/julia/base/weakkeydict.jl"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L784-L857)###
`Base.Filesystem.walkdir`Function
```
walkdir(dir; topdown=true, follow_symlinks=false, onerror=throw)
```
Return an iterator that walks the directory tree of a directory. The iterator returns a tuple containing `(rootpath, dirs, files)`. The directory tree can be traversed top-down or bottom-up. If `walkdir` or `stat` encounters a `IOError` it will rethrow the error by default. A custom error handling function can be provided through `onerror` keyword argument. `onerror` is called with a `IOError` as argument.
**Examples**
```
for (root, dirs, files) in walkdir(".")
println("Directories in $root")
for dir in dirs
println(joinpath(root, dir)) # path to directories
end
println("Files in $root")
for file in files
println(joinpath(root, file)) # path to files
end
end
```
```
julia> mkpath("my/test/dir");
julia> itr = walkdir("my");
julia> (root, dirs, files) = first(itr)
("my", ["test"], String[])
julia> (root, dirs, files) = first(itr)
("my/test", ["dir"], String[])
julia> (root, dirs, files) = first(itr)
("my/test/dir", String[], String[])
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L889-L927)###
`Base.Filesystem.mkdir`Function
```
mkdir(path::AbstractString; mode::Unsigned = 0o777)
```
Make a new directory with name `path` and permissions `mode`. `mode` defaults to `0o777`, modified by the current file creation mask. This function never creates more than one directory. If the directory already exists, or some intermediate directories do not exist, this function throws an error. See [`mkpath`](#Base.Filesystem.mkpath) for a function which creates all required intermediate directories. Return `path`.
**Examples**
```
julia> mkdir("testingdir")
"testingdir"
julia> cd("testingdir")
julia> pwd()
"/home/JuliaUser/testingdir"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L156-L176)###
`Base.Filesystem.mkpath`Function
```
mkpath(path::AbstractString; mode::Unsigned = 0o777)
```
Create all intermediate directories in the `path` as required. Directories are created with the permissions `mode` which defaults to `0o777` and is modified by the current file creation mask. Unlike [`mkdir`](#Base.Filesystem.mkdir), `mkpath` does not error if `path` (or parts of it) already exists. However, an error will be thrown if `path` (or parts of it) points to an existing file. Return `path`.
If `path` includes a filename you will probably want to use `mkpath(dirname(path))` to avoid creating a directory using the filename.
**Examples**
```
julia> cd(mktempdir())
julia> mkpath("my/test/dir") # creates three directories
"my/test/dir"
julia> readdir()
1-element Array{String,1}:
"my"
julia> cd("my")
julia> readdir()
1-element Array{String,1}:
"test"
julia> readdir("test")
1-element Array{String,1}:
"dir"
julia> mkpath("intermediate_dir/actually_a_directory.txt") # creates two directories
"intermediate_dir/actually_a_directory.txt"
julia> isdir("intermediate_dir/actually_a_directory.txt")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L194-L234)###
`Base.Filesystem.hardlink`Function
```
hardlink(src::AbstractString, dst::AbstractString)
```
Creates a hard link to an existing source file `src` with the name `dst`. The destination, `dst`, must not exist.
See also: [`symlink`](#Base.Filesystem.symlink).
This method was added in Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L1015-L1025)###
`Base.Filesystem.symlink`Function
```
symlink(target::AbstractString, link::AbstractString; dir_target = false)
```
Creates a symbolic link to `target` with the name `link`.
On Windows, symlinks must be explicitly declared as referring to a directory or not. If `target` already exists, by default the type of `link` will be auto- detected, however if `target` does not exist, this function defaults to creating a file symlink unless `dir_target` is set to `true`. Note that if the user sets `dir_target` but `target` exists and is a file, a directory symlink will still be created, but dereferencing the symlink will fail, just as if the user creates a file symlink (by calling `symlink()` with `dir_target` set to `false` before the directory is created) and tries to dereference it to a directory.
Additionally, there are two methods of making a link on Windows; symbolic links and junction points. Junction points are slightly more efficient, but do not support relative paths, so if a relative directory symlink is requested (as denoted by `isabspath(target)` returning `false`) a symlink will be used, else a junction point will be used. Best practice for creating symlinks on Windows is to create them only after the files/directories they reference are already created.
See also: [`hardlink`](#Base.Filesystem.hardlink).
This function raises an error under operating systems that do not support soft symbolic links, such as Windows XP.
The `dir_target` keyword argument was added in Julia 1.6. Prior to this, symlinks to nonexistant paths on windows would always be file symlinks, and relative symlinks to directories were not supported.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L1035-L1067)###
`Base.Filesystem.readlink`Function
```
readlink(path::AbstractString) -> AbstractString
```
Return the target location a symbolic link `path` points to.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L1111-L1115)###
`Base.Filesystem.chmod`Function
```
chmod(path::AbstractString, mode::Integer; recursive::Bool=false)
```
Change the permissions mode of `path` to `mode`. Only integer `mode`s (e.g. `0o777`) are currently supported. If `recursive=true` and the path is a directory all permissions in that directory will be recursively changed. Return `path`.
Prior to Julia 1.6, this did not correctly manipulate filesystem ACLs on Windows, therefore it would only set read-only bits on files. It now is able to manipulate ACLs.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L1135-L1147)###
`Base.Filesystem.chown`Function
```
chown(path::AbstractString, owner::Integer, group::Integer=-1)
```
Change the owner and/or group of `path` to `owner` and/or `group`. If the value entered for `owner` or `group` is `-1` the corresponding ID will not change. Only integer `owner`s and `group`s are currently supported. Return `path`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L1161-L1167)###
`Base.Libc.RawFD`Type
```
RawFD
```
Primitive type which wraps the native OS file descriptor. `RawFD`s can be passed to methods like [`stat`](#Base.stat) to discover information about the underlying file, and can also be used to open streams, with the `RawFD` describing the OS file backing the stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L22-L30)###
`Base.stat`Function
```
stat(file)
```
Returns a structure whose fields contain information about the file. The fields of the structure are:
| Name | Description |
| --- | --- |
| desc | The path or OS file descriptor |
| size | The size (in bytes) of the file |
| device | ID of the device that contains the file |
| inode | The inode number of the file |
| mode | The protection mode of the file |
| nlink | The number of hard links to the file |
| uid | The user id of the owner of the file |
| gid | The group id of the file owner |
| rdev | If this file refers to a device, the ID of the device it refers to |
| blksize | The file-system preferred block size for the file |
| blocks | The number of such blocks allocated |
| mtime | Unix timestamp of when the file was last modified |
| ctime | Unix timestamp of when the file's metadata was changed |
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L170-L192)###
`Base.Filesystem.diskstat`Function
```
diskstat(path=pwd())
```
Returns statistics in bytes about the disk that contains the file or directory pointed at by `path`. If no argument is passed, statistics about the disk that contains the current working directory are returned.
This method was added in Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L1208-L1217)###
`Base.Filesystem.lstat`Function
```
lstat(file)
```
Like [`stat`](#Base.stat), but for symbolic links gets the info for the link itself rather than the file it refers to. This function must be called on a file path rather than a file object or a file descriptor.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L195-L202)###
`Base.Filesystem.ctime`Function
```
ctime(file)
```
Equivalent to `stat(file).ctime`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L289-L293)###
`Base.Filesystem.mtime`Function
```
mtime(file)
```
Equivalent to `stat(file).mtime`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L282-L286)###
`Base.Filesystem.filemode`Function
```
filemode(file)
```
Equivalent to `stat(file).mode`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L252-L256)###
`Base.filesize`Function
```
filesize(path...)
```
Equivalent to `stat(file).size`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L275-L279)###
`Base.Filesystem.uperm`Function
```
uperm(file)
```
Get the permissions of the owner of the file as a bitfield of
| Value | Description |
| --- | --- |
| 01 | Execute Permission |
| 02 | Write Permission |
| 04 | Read Permission |
For allowed arguments, see [`stat`](#Base.stat).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L405-L417)###
`Base.Filesystem.gperm`Function
```
gperm(file)
```
Like [`uperm`](#Base.Filesystem.uperm) but gets the permissions of the group owning the file.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L420-L424)###
`Base.Filesystem.operm`Function
```
operm(file)
```
Like [`uperm`](#Base.Filesystem.uperm) but gets the permissions for people who neither own the file nor are a member of the group owning the file
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L427-L432)###
`Base.Filesystem.cp`Function
```
cp(src::AbstractString, dst::AbstractString; force::Bool=false, follow_symlinks::Bool=false)
```
Copy the file, link, or directory from `src` to `dst`. `force=true` will first remove an existing `dst`.
If `follow_symlinks=false`, and `src` is a symbolic link, `dst` will be created as a symbolic link. If `follow_symlinks=true` and `src` is a symbolic link, `dst` will be a copy of the file or directory `src` refers to. Return `dst`.
The `cp` function is different from the `cp` command. The `cp` function always operates on the assumption that `dst` is a file, while the command does different things depending on whether `dst` is a directory or a file. Using `force=true` when `dst` is a directory will result in loss of all the contents present in the `dst` directory, and `dst` will become a file that has the contents of `src` instead.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L358-L375)###
`Base.download`Function
```
download(url::AbstractString, [path::AbstractString = tempname()]) -> path
```
Download a file from the given url, saving it to the location `path`, or if not specified, a temporary path. Returns the path of the downloaded file.
Since Julia 1.6, this function is deprecated and is just a thin wrapper around `Downloads.download`. In new code, you should use that function directly instead of calling this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/download.jl#L8-L18)###
`Base.Filesystem.mv`Function
```
mv(src::AbstractString, dst::AbstractString; force::Bool=false)
```
Move the file, link, or directory from `src` to `dst`. `force=true` will first remove an existing `dst`. Return `dst`.
**Examples**
```
julia> write("hello.txt", "world");
julia> mv("hello.txt", "goodbye.txt")
"goodbye.txt"
julia> "hello.txt" in readdir()
false
julia> readline("goodbye.txt")
"world"
julia> write("hello.txt", "world2");
julia> mv("hello.txt", "goodbye.txt")
ERROR: ArgumentError: 'goodbye.txt' exists. `force=true` is required to remove 'goodbye.txt' before moving.
Stacktrace:
[1] #checkfor_mv_cp_cptree#10(::Bool, ::Function, ::String, ::String, ::String) at ./file.jl:293
[...]
julia> mv("hello.txt", "goodbye.txt", force=true)
"goodbye.txt"
julia> rm("goodbye.txt");
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L389-L423)###
`Base.Filesystem.rm`Function
```
rm(path::AbstractString; force::Bool=false, recursive::Bool=false)
```
Delete the file, link, or empty directory at the given path. If `force=true` is passed, a non-existing path is not treated as error. If `recursive=true` is passed and the path is a directory, then all contents are removed recursively.
**Examples**
```
julia> mkpath("my/test/dir");
julia> rm("my", recursive=true)
julia> rm("this_file_does_not_exist", force=true)
julia> rm("this_file_does_not_exist")
ERROR: IOError: unlink("this_file_does_not_exist"): no such file or directory (ENOENT)
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L252-L272)###
`Base.Filesystem.touch`Function
```
touch(path::AbstractString)
```
Update the last-modified timestamp on a file to the current time.
If the file does not exist a new file is created.
Return `path`.
**Examples**
```
julia> write("my_little_file", 2);
julia> mtime("my_little_file")
1.5273815391135583e9
julia> touch("my_little_file");
julia> mtime("my_little_file")
1.527381559163435e9
```
We can see the [`mtime`](#Base.Filesystem.mtime) has been modified by `touch`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L430-L453)###
`Base.Filesystem.tempname`Function
```
tempname(parent=tempdir(); cleanup=true) -> String
```
Generate a temporary file path. This function only returns a path; no file is created. The path is likely to be unique, but this cannot be guaranteed due to the very remote posibility of two simultaneous calls to `tempname` generating the same file name. The name is guaranteed to differ from all files already existing at the time of the call to `tempname`.
When called with no arguments, the temporary name will be an absolute path to a temporary name in the system temporary directory as given by `tempdir()`. If a `parent` directory argument is given, the temporary path will be in that directory instead.
The `cleanup` option controls whether the process attempts to delete the returned path automatically when the process exits. Note that the `tempname` function does not create any file or directory at the returned location, so there is nothing to cleanup unless you create a file or directory there. If you do and `clean` is `true` it will be deleted upon process termination.
The `parent` and `cleanup` arguments were added in 1.4. Prior to Julia 1.4 the path `tempname` would never be cleaned up at process termination.
This can lead to security holes if another process obtains the same file name and creates the file before you are able to. Open the file with `JL_O_EXCL` if this is a concern. Using [`mktemp()`](#Base.Filesystem.mktemp-Tuple%7BAbstractString%7D) is also recommended instead.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L631-L661)###
`Base.Filesystem.tempdir`Function
```
tempdir()
```
Gets the path of the temporary directory. On Windows, `tempdir()` uses the first environment variable found in the ordered list `TMP`, `TEMP`, `USERPROFILE`. On all other operating systems, `tempdir()` uses the first environment variable found in the ordered list `TMPDIR`, `TMP`, `TEMP`, and `TEMPDIR`. If none of these are found, the path `"/tmp"` is used.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L470-L477)###
`Base.Filesystem.mktemp`Method
```
mktemp(parent=tempdir(); cleanup=true) -> (path, io)
```
Return `(path, io)`, where `path` is the path of a new temporary file in `parent` and `io` is an open file object for this path. The `cleanup` option controls whether the temporary file is automatically deleted when the process exits.
The `cleanup` keyword argument was added in Julia 1.3. Relatedly, starting from 1.3, Julia will remove the temporary paths created by `mktemp` when the Julia process exits, unless `cleanup` is explicitly set to `false`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L664-L675)###
`Base.Filesystem.mktemp`Method
```
mktemp(f::Function, parent=tempdir())
```
Apply the function `f` to the result of [`mktemp(parent)`](#Base.Filesystem.mktemp-Tuple%7BAbstractString%7D) and remove the temporary file upon completion.
See also: [`mktempdir`](#Base.Filesystem.mktempdir-Tuple%7BAbstractString%7D).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L725-L732)###
`Base.Filesystem.mktempdir`Method
```
mktempdir(parent=tempdir(); prefix="jl_", cleanup=true) -> path
```
Create a temporary directory in the `parent` directory with a name constructed from the given prefix and a random suffix, and return its path. Additionally, any trailing `X` characters may be replaced with random characters. If `parent` does not exist, throw an error. The `cleanup` option controls whether the temporary directory is automatically deleted when the process exits.
The `prefix` keyword argument was added in Julia 1.2.
The `cleanup` keyword argument was added in Julia 1.3. Relatedly, starting from 1.3, Julia will remove the temporary paths created by `mktempdir` when the Julia process exits, unless `cleanup` is explicitly set to `false`.
See also: [`mktemp`](#Base.Filesystem.mktemp-Tuple%7BAbstractString%7D), [`mkdir`](#Base.Filesystem.mkdir).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L678-L696)###
`Base.Filesystem.mktempdir`Method
```
mktempdir(f::Function, parent=tempdir(); prefix="jl_")
```
Apply the function `f` to the result of [`mktempdir(parent; prefix)`](#Base.Filesystem.mktempdir-Tuple%7BAbstractString%7D) and remove the temporary directory all of its contents upon completion.
See also: [`mktemp`](#Base.Filesystem.mktemp-Tuple%7BAbstractString%7D), [`mkdir`](#Base.Filesystem.mkdir).
The `prefix` keyword argument was added in Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/file.jl#L749-L759)###
`Base.Filesystem.isblockdev`Function
```
isblockdev(path) -> Bool
```
Return `true` if `path` is a block device, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L339-L343)###
`Base.Filesystem.ischardev`Function
```
ischardev(path) -> Bool
```
Return `true` if `path` is a character device, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L314-L318)###
`Base.Filesystem.isdir`Function
```
isdir(path) -> Bool
```
Return `true` if `path` is a directory, `false` otherwise.
**Examples**
```
julia> isdir(homedir())
true
julia> isdir("not/a/directory")
false
```
See also [`isfile`](#Base.Filesystem.isfile) and [`ispath`](#Base.Filesystem.ispath).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L321-L336)###
`Base.Filesystem.isfifo`Function
```
isfifo(path) -> Bool
```
Return `true` if `path` is a FIFO, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L307-L311)###
`Base.Filesystem.isfile`Function
```
isfile(path) -> Bool
```
Return `true` if `path` is a regular file, `false` otherwise.
**Examples**
```
julia> isfile(homedir())
false
julia> f = open("test_file.txt", "w");
julia> isfile(f)
true
julia> close(f); rm("test_file.txt")
```
See also [`isdir`](#Base.Filesystem.isdir) and [`ispath`](#Base.Filesystem.ispath).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L346-L365)###
`Base.Filesystem.islink`Function
```
islink(path) -> Bool
```
Return `true` if `path` is a symbolic link, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L368-L372)###
`Base.Filesystem.ismount`Function
```
ismount(path) -> Bool
```
Return `true` if `path` is a mount point, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L473-L477)###
`Base.Filesystem.ispath`Function
```
ispath(path) -> Bool
```
Return `true` if a valid filesystem entity exists at `path`, otherwise returns `false`. This is the generalization of [`isfile`](#Base.Filesystem.isfile), [`isdir`](#Base.Filesystem.isdir) etc.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L298-L304)###
`Base.Filesystem.issetgid`Function
```
issetgid(path) -> Bool
```
Return `true` if `path` has the setgid flag set, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L391-L395)###
`Base.Filesystem.issetuid`Function
```
issetuid(path) -> Bool
```
Return `true` if `path` has the setuid flag set, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L384-L388)###
`Base.Filesystem.issocket`Function
```
issocket(path) -> Bool
```
Return `true` if `path` is a socket, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L375-L379)###
`Base.Filesystem.issticky`Function
```
issticky(path) -> Bool
```
Return `true` if `path` has the sticky bit set, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stat.jl#L398-L402)###
`Base.Filesystem.homedir`Function
```
homedir() -> String
```
Return the current user's home directory.
`homedir` determines the home directory via `libuv`'s `uv_os_homedir`. For details (for example on how to specify the home directory via environment variables), see the [`uv_os_homedir` documentation](http://docs.libuv.org/en/v1.x/misc.html#c.uv_os_homedir).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L54-L63)###
`Base.Filesystem.dirname`Function
```
dirname(path::AbstractString) -> AbstractString
```
Get the directory part of a path. Trailing characters ('/' or '\') in the path are counted as part of the path.
**Examples**
```
julia> dirname("/home/myuser")
"/home"
julia> dirname("/home/myuser/")
"/home/myuser"
```
See also [`basename`](#Base.Filesystem.basename).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L147-L163)###
`Base.Filesystem.basename`Function
```
basename(path::AbstractString) -> AbstractString
```
Get the file name part of a path.
This function differs slightly from the Unix `basename` program, where trailing slashes are ignored, i.e. `$ basename /foo/bar/` returns `bar`, whereas `basename` in Julia returns an empty string `""`.
**Examples**
```
julia> basename("/home/myuser/example.jl")
"example.jl"
julia> basename("/home/myuser/")
""
```
See also [`dirname`](#Base.Filesystem.dirname).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L166-L185)###
`Base.Filesystem.isabspath`Function
```
isabspath(path::AbstractString) -> Bool
```
Determine whether a path is absolute (begins at the root directory).
**Examples**
```
julia> isabspath("/home")
true
julia> isabspath("home")
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L87-L100)###
`Base.Filesystem.isdirpath`Function
```
isdirpath(path::AbstractString) -> Bool
```
Determine whether a path refers to a directory (for example, ends with a path separator).
**Examples**
```
julia> isdirpath("/home")
false
julia> isdirpath("/home/")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L103-L116)###
`Base.Filesystem.joinpath`Function
```
joinpath(parts::AbstractString...) -> String
joinpath(parts::Vector{AbstractString}) -> String
joinpath(parts::Tuple{AbstractString}) -> String
```
Join path components into a full path. If some argument is an absolute path or (on Windows) has a drive specification that doesn't match the drive computed for the join of the preceding paths, then prior components are dropped.
Note on Windows since there is a current directory for each drive, `joinpath("c:", "foo")` represents a path relative to the current directory on drive "c:" so this is equal to "c:foo", not "c:\foo". Furthermore, `joinpath` treats this as a non-absolute path and ignores the drive letter casing, hence `joinpath("C:\A","c:b") = "C:\A\b"`.
**Examples**
```
julia> joinpath("/home/myuser", "example.jl")
"/home/myuser/example.jl"
```
```
julia> joinpath(["/home/myuser", "example.jl"])
"/home/myuser/example.jl"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L329-L353)###
`Base.Filesystem.abspath`Function
```
abspath(path::AbstractString) -> String
```
Convert a path to an absolute path by adding the current directory if necessary. Also normalizes the path as in [`normpath`](#Base.Filesystem.normpath).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L413-L418)
```
abspath(path::AbstractString, paths::AbstractString...) -> String
```
Convert a set of paths to an absolute path by joining them together and adding the current directory if necessary. Equivalent to `abspath(joinpath(path, paths...))`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L433-L438)###
`Base.Filesystem.normpath`Function
```
normpath(path::AbstractString) -> String
```
Normalize a path, removing "." and ".." entries and changing "/" to the canonical path separator for the system.
**Examples**
```
julia> normpath("/home/myuser/../example.jl")
"/home/example.jl"
julia> normpath("Documents/Julia") == joinpath("Documents", "Julia")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L356-L370)
```
normpath(path::AbstractString, paths::AbstractString...) -> String
```
Convert a set of paths to a normalized path by joining them together and removing "." and ".." entries. Equivalent to `normpath(joinpath(path, paths...))`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L405-L410)###
`Base.Filesystem.realpath`Function
```
realpath(path::AbstractString) -> String
```
Canonicalize a path by expanding symbolic links and removing "." and ".." entries. On case-insensitive case-preserving filesystems (typically Mac and Windows), the filesystem's stored case for the path is returned.
(This function throws an exception if `path` does not exist in the filesystem.)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L460-L468)###
`Base.Filesystem.relpath`Function
```
relpath(path::AbstractString, startpath::AbstractString = ".") -> AbstractString
```
Return a relative filepath to `path` either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of `path` or `startpath`.
On Windows, case sensitivity is applied to every part of the path except drive letters. If `path` and `startpath` refer to different drives, the absolute path of `path` is returned.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L530-L539)###
`Base.Filesystem.expanduser`Function
```
expanduser(path::AbstractString) -> AbstractString
```
On Unix systems, replace a tilde character at the start of a path with the current user's home directory.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L515-L519)###
`Base.Filesystem.splitdir`Function
```
splitdir(path::AbstractString) -> (AbstractString, AbstractString)
```
Split a path into a tuple of the directory name and file name.
**Examples**
```
julia> splitdir("/home/myuser")
("/home", "myuser")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L119-L129)###
`Base.Filesystem.splitdrive`Function
```
splitdrive(path::AbstractString) -> (AbstractString, AbstractString)
```
On Windows, split a path into the drive letter part and the path part. On Unix systems, the first component is always the empty string.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L46-L51)###
`Base.Filesystem.splitext`Function
```
splitext(path::AbstractString) -> (AbstractString, AbstractString)
```
If the last component of a path contains one or more dots, split the path into everything before the last dot and everything including and after the dot. Otherwise, return a tuple of the argument unmodified and the empty string. "splitext" is short for "split extension".
**Examples**
```
julia> splitext("/home/myuser/example.jl")
("/home/myuser/example", ".jl")
julia> splitext("/home/myuser/example.tar.gz")
("/home/myuser/example.tar", ".gz")
julia> splitext("/home/my.user/example")
("/home/my.user/example", "")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L188-L206)###
`Base.Filesystem.splitpath`Function
```
splitpath(path::AbstractString) -> Vector{String}
```
Split a file path into all its path components. This is the opposite of `joinpath`. Returns an array of substrings, one for each directory or file in the path, including the root directory if present.
This function requires at least Julia 1.1.
**Examples**
```
julia> splitpath("/home/myuser/example.jl")
4-element Vector{String}:
"/"
"home"
"myuser"
"example.jl"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/path.jl#L217-L236)
| programming_docs |
julia Constants Constants
=========
###
`Core.nothing`Constant
```
nothing
```
The singleton instance of type [`Nothing`](../base/index#Core.Nothing), used by convention when there is no value to return (as in a C `void` function) or when a variable or field holds no value.
See also: [`isnothing`](../base/index#Base.isnothing), [`something`](../base/index#Base.something), [`missing`](../base/index#Base.missing).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1289-L1296)###
`Base.PROGRAM_FILE`Constant
```
PROGRAM_FILE
```
A string containing the script name passed to Julia from the command line. Note that the script name remains unchanged from within included files. Alternatively see [`@__FILE__`](../base/index#Base.@__FILE__).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L5-L11)###
`Base.ARGS`Constant
```
ARGS
```
An array of the command line arguments passed to Julia, as strings.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L14-L18)###
`Base.C_NULL`Constant
```
C_NULL
```
The C null pointer constant, sometimes used when calling external code.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L13-L17)###
`Base.VERSION`Constant
```
VERSION
```
A [`VersionNumber`](../base/index#Base.VersionNumber) object describing which version of Julia is in use. See also [Version Number Literals](../../manual/strings/index#man-version-number-literals).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/version.jl#L235-L240)###
`Base.DEPOT_PATH`Constant
```
DEPOT_PATH
```
A stack of "depot" locations where the package manager, as well as Julia's code loading mechanisms, look for package registries, installed packages, named environments, repo clones, cached compiled package images, and configuration files. By default it includes:
1. `~/.julia` where `~` is the user home as appropriate on the system;
2. an architecture-specific shared system directory, e.g. `/usr/local/share/julia`;
3. an architecture-independent shared system directory, e.g. `/usr/share/julia`.
So `DEPOT_PATH` might be:
```
[joinpath(homedir(), ".julia"), "/usr/local/share/julia", "/usr/share/julia"]
```
The first entry is the "user depot" and should be writable by and owned by the current user. The user depot is where: registries are cloned, new package versions are installed, named environments are created and updated, package repos are cloned, newly compiled package image files are saved, log files are written, development packages are checked out by default, and global configuration data is saved. Later entries in the depot path are treated as read-only and are appropriate for registries, packages, etc. installed and managed by system administrators.
`DEPOT_PATH` is populated based on the [`JULIA_DEPOT_PATH`](../../manual/environment-variables/index#JULIA_DEPOT_PATH) environment variable if set.
**DEPOT\_PATH contents**
Each entry in `DEPOT_PATH` is a path to a directory which contains subdirectories used by Julia for various purposes. Here is an overview of some of the subdirectories that may exist in a depot:
* `clones`: Contains full clones of package repos. Maintained by `Pkg.jl` and used as a cache.
* `compiled`: Contains precompiled `*.ji` files for packages. Maintained by Julia.
* `dev`: Default directory for `Pkg.develop`. Maintained by `Pkg.jl` and the user.
* `environments`: Default package environments. For instance the global environment for a specific julia version. Maintained by `Pkg.jl`.
* `logs`: Contains logs of `Pkg` and `REPL` operations. Maintained by `Pkg.jl` and `Julia`.
* `packages`: Contains packages, some of which were explicitly installed and some which are implicit dependencies. Maintained by `Pkg.jl`.
* `registries`: Contains package registries. By default only `General`. Maintained by `Pkg.jl`.
See also [`JULIA_DEPOT_PATH`](../../manual/environment-variables/index#JULIA_DEPOT_PATH), and [Code Loading](../../manual/code-loading/index#code-loading).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L44-L86)###
`Base.LOAD_PATH`Constant
```
LOAD_PATH
```
An array of paths for `using` and `import` statements to consider as project environments or package directories when loading code. It is populated based on the [`JULIA_LOAD_PATH`](../../manual/environment-variables/index#JULIA_LOAD_PATH) environment variable if set; otherwise it defaults to `["@", "@v#.#", "@stdlib"]`. Entries starting with `@` have special meanings:
* `@` refers to the "current active environment", the initial value of which is initially determined by the [`JULIA_PROJECT`](../../manual/environment-variables/index#JULIA_PROJECT) environment variable or the `--project` command-line option.
* `@stdlib` expands to the absolute path of the current Julia installation's standard library directory.
* `@name` refers to a named environment, which are stored in depots (see [`JULIA_DEPOT_PATH`](../../manual/environment-variables/index#JULIA_DEPOT_PATH)) under the `environments` subdirectory. The user's named environments are stored in `~/.julia/environments` so `@name` would refer to the environment in `~/.julia/environments/name` if it exists and contains a `Project.toml` file. If `name` contains `#` characters, then they are replaced with the major, minor and patch components of the Julia version number. For example, if you are running Julia 1.2 then `@v#.#` expands to `@v1.2` and will look for an environment by that name, typically at `~/.julia/environments/v1.2`.
The fully expanded value of `LOAD_PATH` that is searched for projects and packages can be seen by calling the `Base.load_path()` function.
See also [`JULIA_LOAD_PATH`](../../manual/environment-variables/index#JULIA_LOAD_PATH), [`JULIA_PROJECT`](../../manual/environment-variables/index#JULIA_PROJECT), [`JULIA_DEPOT_PATH`](../../manual/environment-variables/index#JULIA_DEPOT_PATH), and [Code Loading](../../manual/code-loading/index#code-loading).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L134-L168)###
`Base.Sys.BINDIR`Constant
```
Sys.BINDIR::String
```
A string containing the full path to the directory containing the `julia` executable.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L40-L44)###
`Base.Sys.CPU_THREADS`Constant
```
Sys.CPU_THREADS::Int
```
The number of logical CPU cores available in the system, i.e. the number of threads that the CPU can run concurrently. Note that this is not necessarily the number of CPU cores, for example, in the presence of [hyper-threading](https://en.wikipedia.org/wiki/Hyper-threading).
See Hwloc.jl or CpuId.jl for extended information, including number of physical cores.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L59-L68)###
`Base.Sys.WORD_SIZE`Constant
```
Sys.WORD_SIZE::Int
```
Standard word size on the current machine, in bits.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L93-L97)###
`Base.Sys.KERNEL`Constant
```
Sys.KERNEL::Symbol
```
A symbol representing the name of the operating system, as returned by `uname` of the build configuration.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L79-L83)###
`Base.Sys.ARCH`Constant
```
Sys.ARCH::Symbol
```
A symbol representing the architecture of the build configuration.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L71-L75)###
`Base.Sys.MACHINE`Constant
```
Sys.MACHINE::String
```
A string containing the build triple.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L86-L90)See also:
* [`stdin`](../io-network/index#Base.stdin)
* [`stdout`](../io-network/index#Base.stdout)
* [`stderr`](../io-network/index#Base.stderr)
* [`ENV`](../base/index#Base.ENV)
* [`ENDIAN_BOM`](../io-network/index#Base.ENDIAN_BOM)
* `Libc.MS_ASYNC`
* `Libc.MS_INVALIDATE`
* `Libc.MS_SYNC`
julia StackTraces StackTraces
===========
###
`Base.StackTraces.StackFrame`Type
```
StackFrame
```
Stack information representing execution context, with the following fields:
* `func::Symbol`
The name of the function containing the execution context.
* `linfo::Union{Core.MethodInstance, CodeInfo, Nothing}`
The MethodInstance containing the execution context (if it could be found).
* `file::Symbol`
The path to the file containing the execution context.
* `line::Int`
The line number in the file containing the execution context.
* `from_c::Bool`
True if the code is from C.
* `inlined::Bool`
True if the code is from an inlined frame.
* `pointer::UInt64`
Representation of the pointer to the execution context as returned by `backtrace`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L14-L47)###
`Base.StackTraces.StackTrace`Type
```
StackTrace
```
An alias for `Vector{StackFrame}` provided for convenience; returned by calls to `stacktrace`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L68-L73)###
`Base.StackTraces.stacktrace`Function
```
stacktrace([trace::Vector{Ptr{Cvoid}},] [c_funcs::Bool=false]) -> StackTrace
```
Returns a stack trace in the form of a vector of `StackFrame`s. (By default stacktrace doesn't return C functions, but this can be enabled.) When called without specifying a trace, `stacktrace` first calls `backtrace`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L153-L159)The following methods and types in `Base.StackTraces` are not exported and need to be called e.g. as `StackTraces.lookup(ptr)`.
###
`Base.StackTraces.lookup`Function
```
lookup(pointer::Ptr{Cvoid}) -> Vector{StackFrame}
```
Given a pointer to an execution context (usually generated by a call to `backtrace`), looks up stack frame context information. Returns an array of frame information for all functions inlined at that point, innermost function first.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L99-L105)###
`Base.StackTraces.remove_frames!`Function
```
remove_frames!(stack::StackTrace, name::Symbol)
```
Takes a `StackTrace` (a vector of `StackFrames`) and a function name (a `Symbol`) and removes the `StackFrame` specified by the function name from the `StackTrace` (also removing all frames above the specified function). Primarily used to remove `StackTraces` functions from the `StackTrace` prior to returning it.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L182-L189)
```
remove_frames!(stack::StackTrace, m::Module)
```
Returns the `StackTrace` with all `StackFrame`s from the provided `Module` removed.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L200-L204)
julia Mathematics Mathematics
===========
[Mathematical Operators](#math-ops)
------------------------------------
###
`Base.:-`Method
```
-(x)
```
Unary minus operator.
See also: [`abs`](#Base.abs), [`flipsign`](#Base.flipsign).
**Examples**
```
julia> -1
-1
julia> -(2)
-2
julia> -[1 2; 3 4]
2×2 Matrix{Int64}:
-1 -2
-3 -4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2365-L2385)###
`Base.:+`Function
```
+(x, y...)
```
Addition operator. `x+y+z+...` calls this function with all arguments, i.e. `+(x, y, z, ...)`.
**Examples**
```
julia> 1 + 20 + 4
25
julia> +(1, 20, 4)
25
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2349-L2362)
```
dt::Date + t::Time -> DateTime
```
The addition of a `Date` with a `Time` produces a `DateTime`. The hour, minute, second, and millisecond parts of the `Time` are used along with the year, month, and day of the `Date` to create the new `DateTime`. Non-zero microseconds or nanoseconds in the `Time` type will result in an `InexactError` being thrown.
###
`Base.:-`Method
```
-(x, y)
```
Subtraction operator.
**Examples**
```
julia> 2 - 3
-1
julia> -(2, 4.5)
-2.5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2388-L2401)###
`Base.:*`Method
```
*(x, y...)
```
Multiplication operator. `x*y*z*...` calls this function with all arguments, i.e. `*(x, y, z, ...)`.
**Examples**
```
julia> 2 * 7 * 8
112
julia> *(2, 7, 8)
112
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2404-L2417)###
`Base.:/`Function
```
/(x, y)
```
Right division operator: multiplication of `x` by the inverse of `y` on the right. Gives floating-point results for integer arguments.
**Examples**
```
julia> 1/2
0.5
julia> 4/2
2.0
julia> 4.5/2
2.25
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2420-L2437)
```
A / B
```
Matrix right-division: `A / B` is equivalent to `(B' \ A')'` where [`\`](#Base.:%5C%5C-Tuple%7BAny,%20Any%7D) is the left-division operator. For square matrices, the result `X` is such that `A == X*B`.
See also: [`rdiv!`](../../stdlib/linearalgebra/index#LinearAlgebra.rdiv!).
**Examples**
```
julia> A = Float64[1 4 5; 3 9 2]; B = Float64[1 4 2; 3 4 2; 8 7 1];
julia> X = A / B
2×3 Matrix{Float64}:
-0.65 3.75 -1.2
3.25 -2.75 1.0
julia> isapprox(A, X*B)
true
julia> isapprox(X, A*pinv(B))
true
```
###
`Base.:\`Method
```
\(x, y)
```
Left division operator: multiplication of `y` by the inverse of `x` on the left. Gives floating-point results for integer arguments.
**Examples**
```
julia> 3 \ 6
2.0
julia> inv(3) * 6
2.0
julia> A = [4 3; 2 1]; x = [5, 6];
julia> A \ x
2-element Vector{Float64}:
6.5
-7.0
julia> inv(A) * x
2-element Vector{Float64}:
6.5
-7.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L602-L628)###
`Base.:^`Method
```
^(x, y)
```
Exponentiation operator. If `x` is a matrix, computes matrix exponentiation.
If `y` is an `Int` literal (e.g. `2` in `x^2` or `-3` in `x^-3`), the Julia code `x^y` is transformed by the compiler to `Base.literal_pow(^, x, Val(y))`, to enable compile-time specialization on the value of the exponent. (As a default fallback we have `Base.literal_pow(^, x, Val(y)) = ^(x,y)`, where usually `^ == Base.^` unless `^` has been defined in the calling namespace.) If `y` is a negative integer literal, then `Base.literal_pow` transforms the operation to `inv(x)^-y` by default, where `-y` is positive.
**Examples**
```
julia> 3^5
243
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> A^3
2×2 Matrix{Int64}:
37 54
81 118
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/promotion.jl#L393-L421)###
`Base.fma`Function
```
fma(x, y, z)
```
Computes `x*y+z` without rounding the intermediate result `x*y`. On some systems this is significantly more expensive than `x*y+z`. `fma` is used to improve accuracy in certain algorithms. See [`muladd`](#Base.muladd).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/floatfuncs.jl#L336-L342)###
`Base.muladd`Function
```
muladd(x, y, z)
```
Combined multiply-add: computes `x*y+z`, but allowing the add and multiply to be merged with each other or with surrounding operations for performance. For example, this may be implemented as an [`fma`](#Base.fma) if the hardware supports it efficiently. The result can be different on different machines and can also be different on the same machine due to constant propagation or other optimizations. See [`fma`](#Base.fma).
**Examples**
```
julia> muladd(3, 2, 1)
7
julia> 3 * 2 + 1
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L1291-L1310)
```
muladd(A, y, z)
```
Combined multiply-add, `A*y .+ z`, for matrix-matrix or matrix-vector multiplication. The result is always the same size as `A*y`, but `z` may be smaller, or a scalar.
These methods require Julia 1.6 or later.
**Examples**
```
julia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; z=[0, 100];
julia> muladd(A, B, z)
2×2 Matrix{Float64}:
3.0 3.0
107.0 107.0
```
###
`Base.inv`Method
```
inv(x)
```
Return the multiplicative inverse of `x`, such that `x*inv(x)` or `inv(x)*x` yields [`one(x)`](../numbers/index#Base.one) (the multiplicative identity) up to roundoff errors.
If `x` is a number, this is essentially the same as `one(x)/x`, but for some types `inv(x)` may be slightly more efficient.
**Examples**
```
julia> inv(2)
0.5
julia> inv(1 + 2im)
0.2 - 0.4im
julia> inv(1 + 2im) * (1 + 2im)
1.0 + 0.0im
julia> inv(2//3)
3//2
```
`inv(::Missing)` requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L216-L242)###
`Base.div`Function
```
div(x, y)
÷(x, y)
```
The quotient from Euclidean (integer) division. Generally equivalent to a mathematical operation x/y without a fractional part.
See also: [`cld`](#Base.cld), [`fld`](#Base.fld), [`rem`](#Base.rem), [`divrem`](#Base.divrem).
**Examples**
```
julia> 9 ÷ 4
2
julia> -5 ÷ 3
-1
julia> 5.0 ÷ 2
2.0
julia> div.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
-1 -1 -1 0 0 0 0 0 1 1 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L780-L804)###
`Base.fld`Function
```
fld(x, y)
```
Largest integer less than or equal to `x/y`. Equivalent to `div(x, y, RoundDown)`.
See also [`div`](#Base.div), [`cld`](#Base.cld), [`fld1`](#Base.fld1).
**Examples**
```
julia> fld(7.3,5.5)
1.0
julia> fld.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
-2 -2 -1 -1 -1 0 0 0 1 1 1
```
Because `fld(x, y)` implements strictly correct floored rounding based on the true value of floating-point numbers, unintuitive situations can arise. For example:
```
julia> fld(6.0,0.1)
59.0
julia> 6.0/0.1
60.0
julia> 6.0/big(0.1)
59.99999999999999666933092612453056361837965690217069245739573412231113406246995
```
What is happening here is that the true value of the floating-point number written as `0.1` is slightly larger than the numerical value 1/10 while `6.0` represents the number 6 precisely. Therefore the true value of `6.0 / 0.1` is slightly less than 60. When doing division, this is rounded to precisely `60.0`, but `fld(6.0, 0.1)` always takes the floor of the true value, so the result is `59.0`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/div.jl#L89-L120)###
`Base.cld`Function
```
cld(x, y)
```
Smallest integer larger than or equal to `x/y`. Equivalent to `div(x, y, RoundUp)`.
See also [`div`](#Base.div), [`fld`](#Base.fld).
**Examples**
```
julia> cld(5.5,2.2)
3.0
julia> cld.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
-1 -1 -1 0 0 0 1 1 1 2 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/div.jl#L123-L139)###
`Base.mod`Function
```
mod(x::Integer, r::AbstractUnitRange)
```
Find `y` in the range `r` such that $x ≡ y (mod n)$, where `n = length(r)`, i.e. `y = mod(x - first(r), n) + first(r)`.
See also [`mod1`](#Base.mod1).
**Examples**
```
julia> mod(0, Base.OneTo(3)) # mod1(0, 3)
3
julia> mod(3, 0:2) # mod(3, 3)
0
```
This method requires at least Julia 1.3.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L1457-L1476)
```
mod(x, y)
rem(x, y, RoundDown)
```
The reduction of `x` modulo `y`, or equivalently, the remainder of `x` after floored division by `y`, i.e. `x - y*fld(x,y)` if computed without intermediate rounding.
The result will have the same sign as `y`, and magnitude less than `abs(y)` (with some exceptions, see note below).
When used with floating point values, the exact result may not be representable by the type, and so rounding error may occur. In particular, if the exact result is very close to `y`, then it may be rounded to `y`.
See also: [`rem`](#Base.rem), [`div`](#Base.div), [`fld`](#Base.fld), [`mod1`](#Base.mod1), [`invmod`](#Base.invmod).
```
julia> mod(8, 3)
2
julia> mod(9, 3)
0
julia> mod(8.9, 3)
2.9000000000000004
julia> mod(eps(), 3)
2.220446049250313e-16
julia> mod(-eps(), 3)
3.0
julia> mod.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
1 2 0 1 2 0 1 2 0 1 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L239-L277)
```
rem(x::Integer, T::Type{<:Integer}) -> T
mod(x::Integer, T::Type{<:Integer}) -> T
%(x::Integer, T::Type{<:Integer}) -> T
```
Find `y::T` such that `x` ≡ `y` (mod n), where n is the number of integers representable in `T`, and `y` is an integer in `[typemin(T),typemax(T)]`. If `T` can represent any integer (e.g. `T == BigInt`), then this operation corresponds to a conversion to `T`.
**Examples**
```
julia> 129 % Int8
-127
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L562-L577)###
`Base.rem`Function
```
rem(x, y)
%(x, y)
```
Remainder from Euclidean division, returning a value of the same sign as `x`, and smaller in magnitude than `y`. This value is always exact.
See also: [`div`](#Base.div), [`mod`](#Base.mod), [`mod1`](#Base.mod1), [`divrem`](#Base.divrem).
**Examples**
```
julia> x = 15; y = 4;
julia> x % y
3
julia> x == div(x, y) * y + rem(x, y)
true
julia> rem.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
-2 -1 0 -2 -1 0 1 2 0 1 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L753-L776)###
`Base.Math.rem2pi`Function
```
rem2pi(x, r::RoundingMode)
```
Compute the remainder of `x` after integer division by `2π`, with the quotient rounded according to the rounding mode `r`. In other words, the quantity
```
x - 2π*round(x/(2π),r)
```
without any intermediate rounding. This internally uses a high precision approximation of 2π, and so will give a more accurate result than `rem(x,2π,r)`
* if `r == RoundNearest`, then the result is in the interval $[-π, π]$. This will generally be the most accurate result. See also [`RoundNearest`](#Base.Rounding.RoundNearest).
* if `r == RoundToZero`, then the result is in the interval $[0, 2π]$ if `x` is positive,. or $[-2π, 0]$ otherwise. See also [`RoundToZero`](#Base.Rounding.RoundToZero).
* if `r == RoundDown`, then the result is in the interval $[0, 2π]$. See also [`RoundDown`](#Base.Rounding.RoundDown).
* if `r == RoundUp`, then the result is in the interval $[-2π, 0]$. See also [`RoundUp`](#Base.Rounding.RoundUp).
**Examples**
```
julia> rem2pi(7pi/4, RoundNearest)
-0.7853981633974485
julia> rem2pi(7pi/4, RoundDown)
5.497787143782138
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L1110-L1140)###
`Base.Math.mod2pi`Function
```
mod2pi(x)
```
Modulus after division by `2π`, returning in the range $[0,2π)$.
This function computes a floating point representation of the modulus after division by numerically exact `2π`, and is therefore not exactly the same as `mod(x,2π)`, which would compute the modulus of `x` relative to division by the floating-point number `2π`.
Depending on the format of the input value, the closest representable value to 2π may be less than 2π. For example, the expression `mod2pi(2π)` will not return `0`, because the intermediate value of `2*π` is a `Float64` and `2*Float64(π) < 2*big(π)`. See [`rem2pi`](#Base.Math.rem2pi) for more refined control of this behavior.
**Examples**
```
julia> mod2pi(9*pi/4)
0.7853981633974481
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L1266-L1286)###
`Base.divrem`Function
```
divrem(x, y, r::RoundingMode=RoundToZero)
```
The quotient and remainder from Euclidean division. Equivalent to `(div(x,y,r), rem(x,y,r))`. Equivalently, with the default value of `r`, this call is equivalent to `(x÷y, x%y)`.
See also: [`fldmod`](#Base.fldmod), [`cld`](#Base.cld).
**Examples**
```
julia> divrem(3,7)
(0, 3)
julia> divrem(7,3)
(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/div.jl#L143-L160)###
`Base.fldmod`Function
```
fldmod(x, y)
```
The floored quotient and modulus after division. A convenience wrapper for `divrem(x, y, RoundDown)`. Equivalent to `(fld(x,y), mod(x,y))`.
See also: [`fld`](#Base.fld), [`cld`](#Base.cld), [`fldmod1`](#Base.fldmod1).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/div.jl#L243-L250)###
`Base.fld1`Function
```
fld1(x, y)
```
Flooring division, returning a value consistent with `mod1(x,y)`
See also [`mod1`](#Base.mod1), [`fldmod1`](#Base.fldmod1).
**Examples**
```
julia> x = 15; y = 4;
julia> fld1(x, y)
4
julia> x == fld(x, y) * y + mod(x, y)
true
julia> x == (fld1(x, y) - 1) * y + mod1(x, y)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L837-L857)###
`Base.mod1`Function
```
mod1(x, y)
```
Modulus after flooring division, returning a value `r` such that `mod(r, y) == mod(x, y)` in the range $(0, y]$ for positive `y` and in the range $[y,0)$ for negative `y`.
With integer arguments and positive `y`, this is equal to `mod(x, 1:y)`, and hence natural for 1-based indexing. By comparison, `mod(x, y) == mod(x, 0:y-1)` is natural for computations with offsets or strides.
See also [`mod`](#Base.mod), [`fld1`](#Base.fld1), [`fldmod1`](#Base.fldmod1).
**Examples**
```
julia> mod1(4, 2)
2
julia> mod1.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
1 2 3 1 2 3 1 2 3 1 2
julia> mod1.([-0.1, 0, 0.1, 1, 2, 2.9, 3, 3.1]', 3)
1×8 Matrix{Float64}:
2.9 3.0 0.1 1.0 2.0 2.9 3.0 0.1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L808-L833)###
`Base.fldmod1`Function
```
fldmod1(x, y)
```
Return `(fld1(x,y), mod1(x,y))`.
See also [`fld1`](#Base.fld1), [`mod1`](#Base.mod1).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L864-L870)###
`Base.://`Function
```
//(num, den)
```
Divide two integers or rational numbers, giving a [`Rational`](../numbers/index#Base.Rational) result.
**Examples**
```
julia> 3 // 5
3//5
julia> (3 // 5) // (2 // 1)
3//10
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rational.jl#L48-L61)###
`Base.rationalize`Function
```
rationalize([T<:Integer=Int,] x; tol::Real=eps(x))
```
Approximate floating point number `x` as a [`Rational`](../numbers/index#Base.Rational) number with components of the given integer type. The result will differ from `x` by no more than `tol`.
**Examples**
```
julia> rationalize(5.6)
28//5
julia> a = rationalize(BigInt, 10.3)
103//10
julia> typeof(numerator(a))
BigInt
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rational.jl#L139-L156)###
`Base.numerator`Function
```
numerator(x)
```
Numerator of the rational representation of `x`.
**Examples**
```
julia> numerator(2//3)
2
julia> numerator(4)
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rational.jl#L222-L235)###
`Base.denominator`Function
```
denominator(x)
```
Denominator of the rational representation of `x`.
**Examples**
```
julia> denominator(2//3)
3
julia> denominator(4)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rational.jl#L239-L252)###
`Base.:<<`Function
```
<<(x, n)
```
Left bit shift operator, `x << n`. For `n >= 0`, the result is `x` shifted left by `n` bits, filling with `0`s. This is equivalent to `x * 2^n`. For `n < 0`, this is equivalent to `x >> -n`.
**Examples**
```
julia> Int8(3) << 2
12
julia> bitstring(Int8(3))
"00000011"
julia> bitstring(Int8(12))
"00001100"
```
See also [`>>`](#Base.:>>), [`>>>`](#Base.:>>>), [`exp2`](#Base.exp2), [`ldexp`](#Base.Math.ldexp).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L635-L654)
```
<<(B::BitVector, n) -> BitVector
```
Left bit shift operator, `B << n`. For `n >= 0`, the result is `B` with elements shifted `n` positions backwards, filling with `false` values. If `n < 0`, elements are shifted forwards. Equivalent to `B >> -n`.
**Examples**
```
julia> B = BitVector([true, false, true, false, false])
5-element BitVector:
1
0
1
0
0
julia> B << 1
5-element BitVector:
0
1
0
0
0
julia> B << -1
5-element BitVector:
0
1
0
1
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L1378-L1412)###
`Base.:>>`Function
```
>>(x, n)
```
Right bit shift operator, `x >> n`. For `n >= 0`, the result is `x` shifted right by `n` bits, where `n >= 0`, filling with `0`s if `x >= 0`, `1`s if `x < 0`, preserving the sign of `x`. This is equivalent to `fld(x, 2^n)`. For `n < 0`, this is equivalent to `x << -n`.
**Examples**
```
julia> Int8(13) >> 2
3
julia> bitstring(Int8(13))
"00001101"
julia> bitstring(Int8(3))
"00000011"
julia> Int8(-14) >> 2
-4
julia> bitstring(Int8(-14))
"11110010"
julia> bitstring(Int8(-4))
"11111100"
```
See also [`>>>`](#Base.:>>>), [`<<`](#Base.:<<).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L670-L699)
```
>>(B::BitVector, n) -> BitVector
```
Right bit shift operator, `B >> n`. For `n >= 0`, the result is `B` with elements shifted `n` positions forward, filling with `false` values. If `n < 0`, elements are shifted backwards. Equivalent to `B << -n`.
**Examples**
```
julia> B = BitVector([true, false, true, false, false])
5-element BitVector:
1
0
1
0
0
julia> B >> 1
5-element BitVector:
0
1
0
1
0
julia> B >> -1
5-element BitVector:
0
1
0
0
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L1340-L1374)###
`Base.:>>>`Function
```
>>>(x, n)
```
Unsigned right bit shift operator, `x >>> n`. For `n >= 0`, the result is `x` shifted right by `n` bits, where `n >= 0`, filling with `0`s. For `n < 0`, this is equivalent to `x << -n`.
For [`Unsigned`](../numbers/index#Core.Unsigned) integer types, this is equivalent to [`>>`](#Base.:>>). For [`Signed`](../numbers/index#Core.Signed) integer types, this is equivalent to `signed(unsigned(x) >> n)`.
**Examples**
```
julia> Int8(-14) >>> 2
60
julia> bitstring(Int8(-14))
"11110010"
julia> bitstring(Int8(60))
"00111100"
```
[`BigInt`](../numbers/index#Base.GMP.BigInt)s are treated as if having infinite size, so no filling is required and this is equivalent to [`>>`](#Base.:>>).
See also [`>>`](#Base.:>>), [`<<`](#Base.:<<).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L711-L737)
```
>>>(B::BitVector, n) -> BitVector
```
Unsigned right bitshift operator, `B >>> n`. Equivalent to `B >> n`. See [`>>`](#Base.:>>) for details and examples.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L1415-L1420)###
`Base.bitrotate`Function
```
bitrotate(x::Base.BitInteger, k::Integer)
```
`bitrotate(x, k)` implements bitwise rotation. It returns the value of `x` with its bits rotated left `k` times. A negative value of `k` will rotate to the right instead.
This function requires Julia 1.5 or later.
See also: [`<<`](#Base.:<<), [`circshift`](../arrays/index#Base.circshift), [`BitArray`](../arrays/index#Base.BitArray).
```
julia> bitrotate(UInt8(114), 2)
0xc9
julia> bitstring(bitrotate(0b01110010, 2))
"11001001"
julia> bitstring(bitrotate(0b01110010, -2))
"10011100"
julia> bitstring(bitrotate(0b01110010, 8))
"01110010"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L528-L553)###
`Base.::`Function
```
(:)(start::CartesianIndex, [step::CartesianIndex], stop::CartesianIndex)
```
Construct [`CartesianIndices`](../arrays/index#Base.IteratorsMD.CartesianIndices) from two `CartesianIndex` and an optional step.
This method requires at least Julia 1.1.
The step range method start:step:stop requires at least Julia 1.6.
**Examples**
```
julia> I = CartesianIndex(2,1);
julia> J = CartesianIndex(3,3);
julia> I:J
CartesianIndices((2:3, 1:3))
julia> I:CartesianIndex(1, 2):J
CartesianIndices((2:1:3, 1:2:3))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L278-L301)
```
(:)(start, [step], stop)
```
Range operator. `a:b` constructs a range from `a` to `b` with a step size of 1 (a [`UnitRange`](../collections/index#Base.UnitRange)) , and `a:s:b` is similar but uses a step size of `s` (a [`StepRange`](../collections/index#Base.StepRange)).
`:` is also used in indexing to select whole dimensions and for [`Symbol`](../base/index#Core.Symbol) literals, as in e.g. `:hello`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L31-L39)###
`Base.range`Function
```
range(start, stop, length)
range(start, stop; length, step)
range(start; length, stop, step)
range(;start, length, stop, step)
```
Construct a specialized array with evenly spaced elements and optimized storage (an [`AbstractRange`](../collections/index#Base.AbstractRange)) from the arguments. Mathematically a range is uniquely determined by any three of `start`, `step`, `stop` and `length`. Valid invocations of range are:
* Call `range` with any three of `start`, `step`, `stop`, `length`.
* Call `range` with two of `start`, `stop`, `length`. In this case `step` will be assumed to be one. If both arguments are Integers, a [`UnitRange`](../collections/index#Base.UnitRange) will be returned.
* Call `range` with one of `stop` or `length`. `start` and `step` will be assumed to be one.
See Extended Help for additional details on the returned type.
**Examples**
```
julia> range(1, length=100)
1:100
julia> range(1, stop=100)
1:100
julia> range(1, step=5, length=100)
1:5:496
julia> range(1, step=5, stop=100)
1:5:96
julia> range(1, 10, length=101)
1.0:0.09:10.0
julia> range(1, 100, step=5)
1:5:96
julia> range(stop=10, length=5)
6:10
julia> range(stop=10, step=1, length=5)
6:1:10
julia> range(start=1, step=1, stop=10)
1:1:10
julia> range(; length = 10)
Base.OneTo(10)
julia> range(; stop = 6)
Base.OneTo(6)
julia> range(; stop = 6.5)
1.0:1.0:6.0
```
If `length` is not specified and `stop - start` is not an integer multiple of `step`, a range that ends before `stop` will be produced.
```
julia> range(1, 3.5, step=2)
1.0:2.0:3.0
```
Special care is taken to ensure intermediate values are computed rationally. To avoid this induced overhead, see the [`LinRange`](../collections/index#Base.LinRange) constructor.
`stop` as a positional argument requires at least Julia 1.1.
The versions without keyword arguments and `start` as a keyword argument require at least Julia 1.7.
The versions with `stop` as a sole keyword argument, or `length` as a sole keyword argument require at least Julia 1.8.
**Extended Help**
`range` will produce a `Base.OneTo` when the arguments are Integers and
* Only `length` is provided
* Only `stop` is provided
`range` will produce a `UnitRange` when the arguments are Integers and
* Only `start` and `stop` are provided
* Only `length` and `stop` are provided
A `UnitRange` is not produced if `step` is provided even if specified as one.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L49-L135)###
`Base.OneTo`Type
```
Base.OneTo(n)
```
Define an `AbstractUnitRange` that behaves like `1:n`, with the added distinction that the lower limit is guaranteed (by the type system) to be 1.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L428-L434)###
`Base.StepRangeLen`Type
```
StepRangeLen( ref::R, step::S, len, [offset=1]) where { R,S}
StepRangeLen{T,R,S}( ref::R, step::S, len, [offset=1]) where {T,R,S}
StepRangeLen{T,R,S,L}(ref::R, step::S, len, [offset=1]) where {T,R,S,L}
```
A range `r` where `r[i]` produces values of type `T` (in the first form, `T` is deduced automatically), parameterized by a `ref`erence value, a `step`, and the `len`gth. By default `ref` is the starting value `r[1]`, but alternatively you can supply it as the value of `r[offset]` for some other index `1 <= offset <= len`. In conjunction with `TwicePrecision` this can be used to implement ranges that are free of roundoff error.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L459-L471)###
`Base.:==`Function
```
==(x, y)
```
Generic equality operator. Falls back to [`===`](../base/index#Core.:===). Should be implemented for all types with a notion of equality, based on the abstract value that an instance represents. For example, all numeric types are compared by numeric value, ignoring type. Strings are compared as sequences of characters, ignoring encoding. For collections, `==` is generally called recursively on all contents, though other properties (like the shape for arrays) may also be taken into account.
This operator follows IEEE semantics for floating-point numbers: `0.0 == -0.0` and `NaN != NaN`.
The result is of type `Bool`, except when one of the operands is [`missing`](../base/index#Base.missing), in which case `missing` is returned ([three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic)). For collections, `missing` is returned if at least one of the operands contains a `missing` value and all non-missing values are equal. Use [`isequal`](../base/index#Base.isequal) or [`===`](../base/index#Core.:===) to always get a `Bool` result.
**Implementation**
New numeric types should implement this function for two arguments of the new type, and handle comparison to other types via promotion rules where possible.
[`isequal`](../base/index#Base.isequal) falls back to `==`, so new methods of `==` will be used by the [`Dict`](../collections/index#Base.Dict) type to compare keys. If your type will be used as a dictionary key, it should therefore also implement [`hash`](../base/index#Base.hash).
If some type defines `==`, [`isequal`](../base/index#Base.isequal), and [`isless`](../base/index#Base.isless) then it should also implement [`<`](#Base.:<) to ensure consistency of comparisons.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L55-L85)###
`Base.:!=`Function
```
!=(x, y)
≠(x,y)
```
Not-equals comparison operator. Always gives the opposite answer as [`==`](#Base.:==).
**Implementation**
New types should generally not implement this, and rely on the fallback definition `!=(x,y) = !(x==y)` instead.
**Examples**
```
julia> 3 != 2
true
julia> "foo" ≠ "foo"
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L263-L281)
```
!=(x)
```
Create a function that compares its argument to `x` using [`!=`](#Base.:!=), i.e. a function equivalent to `y -> y != x`. The returned function is of type `Base.Fix2{typeof(!=)}`, which can be used to implement specialized methods.
This functionality requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1137-L1147)###
`Base.:!==`Function
```
!==(x, y)
≢(x,y)
```
Always gives the opposite answer as [`===`](../base/index#Core.:===).
**Examples**
```
julia> a = [1, 2]; b = [1, 2];
julia> a ≢ b
true
julia> a ≢ a
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L312-L328)###
`Base.:<`Function
```
<(x, y)
```
Less-than comparison operator. Falls back to [`isless`](../base/index#Base.isless). Because of the behavior of floating-point NaN values, this operator implements a partial order.
**Implementation**
New numeric types with a canonical partial order should implement this function for two arguments of the new type. Types with a canonical total order should implement [`isless`](../base/index#Base.isless) instead.
**Examples**
```
julia> 'a' < 'b'
true
julia> "abc" < "abd"
true
julia> 5 < 3
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L332-L355)
```
<(x)
```
Create a function that compares its argument to `x` using [`<`](#Base.:<), i.e. a function equivalent to `y -> y < x`. The returned function is of type `Base.Fix2{typeof(<)}`, which can be used to implement specialized methods.
This functionality requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1189-L1199)###
`Base.:<=`Function
```
<=(x, y)
≤(x,y)
```
Less-than-or-equals comparison operator. Falls back to `(x < y) | (x == y)`.
**Examples**
```
julia> 'a' <= 'b'
true
julia> 7 ≤ 7 ≤ 9
true
julia> "abc" ≤ "abc"
true
julia> 5 <= 3
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L384-L404)
```
<=(x)
```
Create a function that compares its argument to `x` using [`<=`](#Base.:<=), i.e. a function equivalent to `y -> y <= x`. The returned function is of type `Base.Fix2{typeof(<=)}`, which can be used to implement specialized methods.
This functionality requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1163-L1173)###
`Base.:>`Function
```
>(x, y)
```
Greater-than comparison operator. Falls back to `y < x`.
**Implementation**
Generally, new types should implement [`<`](#Base.:<) instead of this function, and rely on the fallback definition `>(x, y) = y < x`.
**Examples**
```
julia> 'a' > 'b'
false
julia> 7 > 3 > 1
true
julia> "abc" > "abd"
false
julia> 5 > 3
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L358-L381)
```
>(x)
```
Create a function that compares its argument to `x` using [`>`](#Base.:>), i.e. a function equivalent to `y -> y > x`. The returned function is of type `Base.Fix2{typeof(>)}`, which can be used to implement specialized methods.
This functionality requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1176-L1186)###
`Base.:>=`Function
```
>=(x, y)
≥(x,y)
```
Greater-than-or-equals comparison operator. Falls back to `y <= x`.
**Examples**
```
julia> 'a' >= 'b'
false
julia> 7 ≥ 7 ≥ 3
true
julia> "abc" ≥ "abc"
true
julia> 5 >= 3
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L408-L428)
```
>=(x)
```
Create a function that compares its argument to `x` using [`>=`](#Base.:>=), i.e. a function equivalent to `y -> y >= x`. The returned function is of type `Base.Fix2{typeof(>=)}`, which can be used to implement specialized methods.
This functionality requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1150-L1160)###
`Base.cmp`Function
```
cmp(x,y)
```
Return -1, 0, or 1 depending on whether `x` is less than, equal to, or greater than `y`, respectively. Uses the total order implemented by `isless`.
**Examples**
```
julia> cmp(1, 2)
-1
julia> cmp(2, 1)
1
julia> cmp(2+im, 3-im)
ERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64})
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L436-L454)
```
cmp(<, x, y)
```
Return -1, 0, or 1 depending on whether `x` is less than, equal to, or greater than `y`, respectively. The first argument specifies a less-than comparison function to use.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L457-L462)
```
cmp(a::AbstractString, b::AbstractString) -> Int
```
Compare two strings. Return `0` if both strings have the same length and the character at each index is the same in both strings. Return `-1` if `a` is a prefix of `b`, or if `a` comes before `b` in alphabetical order. Return `1` if `b` is a prefix of `a`, or if `b` comes before `a` in alphabetical order (technically, lexicographical order by Unicode code points).
**Examples**
```
julia> cmp("abc", "abc")
0
julia> cmp("ab", "abc")
-1
julia> cmp("abc", "ab")
1
julia> cmp("ab", "ac")
-1
julia> cmp("ac", "ab")
1
julia> cmp("α", "a")
1
julia> cmp("b", "β")
-1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L266-L298)###
`Base.:~`Function
```
~(x)
```
Bitwise not.
See also: [`!`](#Base.:!), [`&`](#Base.:&), [`|`](#Base.:%7C).
**Examples**
```
julia> ~4
-5
julia> ~10
-11
julia> ~true
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L295-L313)###
`Base.:&`Function
```
x & y
```
Bitwise and. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), returning [`missing`](../base/index#Base.missing) if one operand is `missing` and the other is `true`. Add parentheses for function application form: `(&)(x, y)`.
See also: [`|`](#Base.:%7C), [`xor`](#Base.xor), [`&&`](#&&).
**Examples**
```
julia> 4 & 10
0
julia> 4 & 12
4
julia> true & missing
missing
julia> false & missing
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L316-L339)###
`Base.:|`Function
```
x | y
```
Bitwise or. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), returning [`missing`](../base/index#Base.missing) if one operand is `missing` and the other is `false`.
See also: [`&`](#Base.:&), [`xor`](#Base.xor), [`||`](#%7C%7C).
**Examples**
```
julia> 4 | 10
14
julia> 4 | 1
5
julia> true | missing
true
julia> false | missing
missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L342-L364)###
`Base.xor`Function
```
xor(x, y)
⊻(x, y)
```
Bitwise exclusive or of `x` and `y`. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), returning [`missing`](../base/index#Base.missing) if one of the arguments is `missing`.
The infix operation `a ⊻ b` is a synonym for `xor(a,b)`, and `⊻` can be typed by tab-completing `\xor` or `\veebar` in the Julia REPL.
**Examples**
```
julia> xor(true, false)
true
julia> xor(true, true)
false
julia> xor(true, missing)
missing
julia> false ⊻ false
false
julia> [true; true; false] .⊻ [true; false; false]
3-element BitVector:
0
1
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bool.jl#L41-L72)###
`Base.nand`Function
```
nand(x, y)
⊼(x, y)
```
Bitwise nand (not and) of `x` and `y`. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), returning [`missing`](../base/index#Base.missing) if one of the arguments is `missing`.
The infix operation `a ⊼ b` is a synonym for `nand(a,b)`, and `⊼` can be typed by tab-completing `\nand` or `\barwedge` in the Julia REPL.
**Examples**
```
julia> nand(true, false)
true
julia> nand(true, true)
false
julia> nand(true, missing)
missing
julia> false ⊼ false
true
julia> [true; true; false] .⊼ [true; false; false]
3-element BitVector:
0
1
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bool.jl#L75-L106)###
`Base.nor`Function
```
nor(x, y)
⊽(x, y)
```
Bitwise nor (not or) of `x` and `y`. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), returning [`missing`](../base/index#Base.missing) if one of the arguments is `missing`.
The infix operation `a ⊽ b` is a synonym for `nor(a,b)`, and `⊽` can be typed by tab-completing `\nor` or `\barvee` in the Julia REPL.
**Examples**
```
julia> nor(true, false)
false
julia> nor(true, true)
false
julia> nor(true, missing)
false
julia> false ⊽ false
true
julia> [true; true; false] .⊽ [true; false; false]
3-element BitVector:
0
0
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bool.jl#L109-L140)###
`Base.:!`Function
```
!(x)
```
Boolean not. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), returning [`missing`](../base/index#Base.missing) if `x` is `missing`.
See also [`~`](#Base.:~) for bitwise not.
**Examples**
```
julia> !true
false
julia> !false
true
julia> !missing
missing
julia> .![true false true]
1×3 BitMatrix:
0 1 0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bool.jl#L11-L34)
```
!f::Function
```
Predicate function negation: when the argument of `!` is a function, it returns a function which computes the boolean negation of `f`.
See also [`∘`](#).
**Examples**
```
julia> str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"
"∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"
julia> filter(isletter, str)
"εδxyδfxfyε"
julia> filter(!isletter, str)
"∀ > 0, ∃ > 0: |-| < ⇒ |()-()| < "
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1057-L1076)###
`&&`Keyword
```
x && y
```
Short-circuiting boolean AND.
See also [`&`](#Base.:&), the ternary operator `? :`, and the manual section on [control flow](../../manual/control-flow/index#man-conditional-evaluation).
**Examples**
```
julia> x = 3;
julia> x > 1 && x < 10 && x isa Int
true
julia> x < 0 && error("expected positive x")
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1026-L1043)###
`||`Keyword
```
x || y
```
Short-circuiting boolean OR.
See also: [`|`](#Base.:%7C), [`xor`](#Base.xor), [`&&`](#&&).
**Examples**
```
julia> pi < 3 || ℯ < 3
true
julia> false || true || println("neither is true!")
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1046-L1061)
[Mathematical Functions](#Mathematical-Functions)
--------------------------------------------------
###
`Base.isapprox`Function
```
isapprox(x, y; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps, nans::Bool=false[, norm::Function])
```
Inexact equality comparison. Two numbers compare equal if their relative distance *or* their absolute distance is within tolerance bounds: `isapprox` returns `true` if `norm(x-y) <= max(atol, rtol*max(norm(x), norm(y)))`. The default `atol` is zero and the default `rtol` depends on the types of `x` and `y`. The keyword argument `nans` determines whether or not NaN values are considered equal (defaults to false).
For real or complex floating-point values, if an `atol > 0` is not specified, `rtol` defaults to the square root of [`eps`](#) of the type of `x` or `y`, whichever is bigger (least precise). This corresponds to requiring equality of about half of the significant digits. Otherwise, e.g. for integer arguments or if an `atol > 0` is supplied, `rtol` defaults to zero.
The `norm` keyword defaults to `abs` for numeric `(x,y)` and to `LinearAlgebra.norm` for arrays (where an alternative `norm` choice is sometimes useful). When `x` and `y` are arrays, if `norm(x-y)` is not finite (i.e. `±Inf` or `NaN`), the comparison falls back to checking whether all elements of `x` and `y` are approximately equal component-wise.
The binary operator `≈` is equivalent to `isapprox` with the default arguments, and `x ≉ y` is equivalent to `!isapprox(x,y)`.
Note that `x ≈ 0` (i.e., comparing to zero with the default tolerances) is equivalent to `x == 0` since the default `atol` is `0`. In such cases, you should either supply an appropriate `atol` (or use `norm(x) ≤ atol`) or rearrange your code (e.g. use `x ≈ y` rather than `x - y ≈ 0`). It is not possible to pick a nonzero `atol` automatically because it depends on the overall scaling (the "units") of your problem: for example, in `x - y ≈ 0`, `atol=1e-9` is an absurdly small tolerance if `x` is the [radius of the Earth](https://en.wikipedia.org/wiki/Earth_radius) in meters, but an absurdly large tolerance if `x` is the [radius of a Hydrogen atom](https://en.wikipedia.org/wiki/Bohr_radius) in meters.
Passing the `norm` keyword argument when comparing numeric (non-array) arguments requires Julia 1.6 or later.
**Examples**
```
julia> isapprox(0.1, 0.15; atol=0.05)
true
julia> isapprox(0.1, 0.15; rtol=0.34)
true
julia> isapprox(0.1, 0.15; rtol=0.33)
false
julia> 0.1 + 1e-10 ≈ 0.1
true
julia> 1e-10 ≈ 0
false
julia> isapprox(1e-10, 0, atol=1e-8)
true
julia> isapprox([10.0^9, 1.0], [10.0^9, 2.0]) # using `norm`
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/floatfuncs.jl#L239-L299)
```
isapprox(x; kwargs...) / ≈(x; kwargs...)
```
Create a function that compares its argument to `x` using `≈`, i.e. a function equivalent to `y -> y ≈ x`.
The keyword arguments supported here are the same as those in the 2-argument `isapprox`.
This method requires Julia 1.5 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/floatfuncs.jl#L306-L315)###
`Base.sin`Method
```
sin(x)
```
Compute sine of `x`, where `x` is in radians.
See also [`sind`], [`sinpi`], [`sincos`], [`cis`].
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L440-L446)###
`Base.cos`Method
```
cos(x)
```
Compute cosine of `x`, where `x` is in radians.
See also [`cosd`], [`cospi`], [`sincos`], [`cis`].
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L449-L455)###
`Base.Math.sincos`Method
```
sincos(x)
```
Simultaneously compute the sine and cosine of `x`, where `x` is in radians, returning a tuple `(sine, cosine)`.
See also [`cis`](#Base.cis), [`sincospi`](#Base.Math.sincospi), [`sincosd`](#Base.Math.sincosd).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L166-L173)###
`Base.tan`Method
```
tan(x)
```
Compute tangent of `x`, where `x` is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L458-L462)###
`Base.Math.sind`Function
```
sind(x)
```
Compute sine of `x`, where `x` is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1267-L1275)###
`Base.Math.cosd`Function
```
cosd(x)
```
Compute cosine of `x`, where `x` is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1267-L1275)###
`Base.Math.tand`Function
```
tand(x)
```
Compute tangent of `x`, where `x` is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1267-L1275)###
`Base.Math.sincosd`Function
```
sincosd(x)
```
Simultaneously compute the sine and cosine of `x`, where `x` is in degrees.
This function requires at least Julia 1.3.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1249-L1256)###
`Base.Math.sinpi`Function
```
sinpi(x)
```
Compute $\sin(\pi x)$ more accurately than `sin(pi*x)`, especially for large `x`.
See also [`sind`](#Base.Math.sind), [`cospi`](#Base.Math.cospi), [`sincospi`](#Base.Math.sincospi).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L743-L749)###
`Base.Math.cospi`Function
```
cospi(x)
```
Compute $\cos(\pi x)$ more accurately than `cos(pi*x)`, especially for large `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L808-L812)###
`Base.Math.sincospi`Function
```
sincospi(x)
```
Simultaneously compute [`sinpi(x)`](#Base.Math.sinpi) and [`cospi(x)`](#Base.Math.cospi) (the sine and cosine of `π*x`, where `x` is in radians), returning a tuple `(sine, cosine)`.
This function requires Julia 1.6 or later.
See also: [`cispi`](#Base.cispi), [`sincosd`](#Base.Math.sincosd), [`sinpi`](#Base.Math.sinpi).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L862-L872)###
`Base.sinh`Method
```
sinh(x)
```
Compute hyperbolic sine of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L389-L393)###
`Base.cosh`Method
```
cosh(x)
```
Compute hyperbolic cosine of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L396-L400)###
`Base.tanh`Method
```
tanh(x)
```
Compute hyperbolic tangent of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L403-L407)###
`Base.asin`Method
```
asin(x)
```
Compute the inverse sine of `x`, where the output is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L465-L469)###
`Base.acos`Method
```
acos(x)
```
Compute the inverse cosine of `x`, where the output is in radians
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L472-L476)###
`Base.atan`Method
```
atan(y)
atan(y, x)
```
Compute the inverse tangent of `y` or `y/x`, respectively.
For one argument, this is the angle in radians between the positive *x*-axis and the point (1, *y*), returning a value in the interval $[-\pi/2, \pi/2]$.
For two arguments, this is the angle in radians between the positive *x*-axis and the point (*x*, *y*), returning a value in the interval $[-\pi, \pi]$. This corresponds to a standard [`atan2`](https://en.wikipedia.org/wiki/Atan2) function. Note that by convention `atan(0.0,x)` is defined as $\pi$ and `atan(-0.0,x)` is defined as $-\pi$ when `x < 0`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L410-L423)###
`Base.Math.asind`Function
```
asind(x)
```
Compute the inverse sine of `x`, where the output is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1286-L1294)###
`Base.Math.acosd`Function
```
acosd(x)
```
Compute the inverse cosine of `x`, where the output is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1286-L1294)###
`Base.Math.atand`Function
```
atand(y)
atand(y,x)
```
Compute the inverse tangent of `y` or `y/x`, respectively, where the output is in degrees.
The one-argument method supports square matrix arguments as of Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1299-L1307)###
`Base.Math.sec`Method
```
sec(x)
```
Compute the secant of `x`, where `x` is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1138-L1142)###
`Base.Math.csc`Method
```
csc(x)
```
Compute the cosecant of `x`, where `x` is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1138-L1142)###
`Base.Math.cot`Method
```
cot(x)
```
Compute the cotangent of `x`, where `x` is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1138-L1142)###
`Base.Math.secd`Function
```
secd(x)
```
Compute the secant of `x`, where `x` is in degrees.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1148-L1152)###
`Base.Math.cscd`Function
```
cscd(x)
```
Compute the cosecant of `x`, where `x` is in degrees.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1148-L1152)###
`Base.Math.cotd`Function
```
cotd(x)
```
Compute the cotangent of `x`, where `x` is in degrees.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1148-L1152)###
`Base.Math.asec`Method
```
asec(x)
```
Compute the inverse secant of `x`, where the output is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1162-L1164)###
`Base.Math.acsc`Method
```
acsc(x)
```
Compute the inverse cosecant of `x`, where the output is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1162-L1164)###
`Base.Math.acot`Method
```
acot(x)
```
Compute the inverse cotangent of `x`, where the output is in radians.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1162-L1164)###
`Base.Math.asecd`Function
```
asecd(x)
```
Compute the inverse secant of `x`, where the output is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1286-L1294)###
`Base.Math.acscd`Function
```
acscd(x)
```
Compute the inverse cosecant of `x`, where the output is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1286-L1294)###
`Base.Math.acotd`Function
```
acotd(x)
```
Compute the inverse cotangent of `x`, where the output is in degrees. If `x` is a matrix, `x` needs to be a square matrix.
Matrix arguments require Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1286-L1294)###
`Base.Math.sech`Method
```
sech(x)
```
Compute the hyperbolic secant of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1143-L1147)###
`Base.Math.csch`Method
```
csch(x)
```
Compute the hyperbolic cosecant of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1143-L1147)###
`Base.Math.coth`Method
```
coth(x)
```
Compute the hyperbolic cotangent of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1143-L1147)###
`Base.asinh`Method
```
asinh(x)
```
Compute the inverse hyperbolic sine of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L426-L430)###
`Base.acosh`Method
```
acosh(x)
```
Compute the inverse hyperbolic cosine of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L479-L483)###
`Base.atanh`Method
```
atanh(x)
```
Compute the inverse hyperbolic tangent of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L486-L490)###
`Base.Math.asech`Method
```
asech(x)
```
Compute the inverse hyperbolic secant of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1165-L1167)###
`Base.Math.acsch`Method
```
acsch(x)
```
Compute the inverse hyperbolic cosecant of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1165-L1167)###
`Base.Math.acoth`Method
```
acoth(x)
```
Compute the inverse hyperbolic cotangent of `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1165-L1167)###
`Base.Math.sinc`Function
```
sinc(x)
```
Compute $\sin(\pi x) / (\pi x)$ if $x \neq 0$, and $1$ if $x = 0$.
See also [`cosc`](#Base.Math.cosc), its derivative.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1074-L1080)###
`Base.Math.cosc`Function
```
cosc(x)
```
Compute $\cos(\pi x) / x - \sin(\pi x) / (\pi x^2)$ if $x \neq 0$, and $0$ if $x = 0$. This is the derivative of `sinc(x)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/trig.jl#L1091-L1096)###
`Base.Math.deg2rad`Function
```
deg2rad(x)
```
Convert `x` from degrees to radians.
See also: [`rad2deg`](#Base.Math.rad2deg), [`sind`](#Base.Math.sind).
**Examples**
```
julia> deg2rad(90)
1.5707963267948966
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L320-L332)###
`Base.Math.rad2deg`Function
```
rad2deg(x)
```
Convert `x` from radians to degrees.
**Examples**
```
julia> rad2deg(pi)
180.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L307-L317)###
`Base.Math.hypot`Function
```
hypot(x, y)
```
Compute the hypotenuse $\sqrt{|x|^2+|y|^2}$ avoiding overflow and underflow.
This code is an implementation of the algorithm described in: An Improved Algorithm for `hypot(a,b)` by Carlos F. Borges The article is available online at ArXiv at the link https://arxiv.org/abs/1904.09481
```
hypot(x...)
```
Compute the hypotenuse $\sqrt{\sum |x\_i|^2}$ avoiding overflow and underflow.
See also `norm` in the [`LinearAlgebra`](../../stdlib/linearalgebra/index#man-linalg) standard library.
**Examples**
```
julia> a = Int64(10)^10;
julia> hypot(a, a)
1.4142135623730951e10
julia> √(a^2 + a^2) # a^2 overflows
ERROR: DomainError with -2.914184810805068e18:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
julia> hypot(3, 4im)
5.0
julia> hypot(-5.7)
5.7
julia> hypot(3, 4im, 12.0)
13.0
julia> using LinearAlgebra
julia> norm([a, a, a, a]) == hypot(a, a, a, a)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L628-L672)###
`Base.log`Method
```
log(x)
```
Compute the natural logarithm of `x`. Throws [`DomainError`](../base/index#Core.DomainError) for negative [`Real`](../numbers/index#Core.Real) arguments. Use complex negative arguments to obtain complex results.
See also [`log1p`], [`log2`], [`log10`].
**Examples**
```
julia> log(2)
0.6931471805599453
julia> log(-3)
ERROR: DomainError with -3.0:
log will only return a complex result if called with a complex argument. Try log(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L493-L513)###
`Base.log`Method
```
log(b,x)
```
Compute the base `b` logarithm of `x`. Throws [`DomainError`](../base/index#Core.DomainError) for negative [`Real`](../numbers/index#Core.Real) arguments.
**Examples**
```
julia> log(4,8)
1.5
julia> log(4,2)
0.5
julia> log(-2, 3)
ERROR: DomainError with -2.0:
log will only return a complex result if called with a complex argument. Try log(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
julia> log(2, -3)
ERROR: DomainError with -3.0:
log will only return a complex result if called with a complex argument. Try log(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
```
If `b` is a power of 2 or 10, [`log2`](#Base.log2) or [`log10`](#Base.log10) should be used, as these will typically be faster and more accurate. For example,
```
julia> log(100,1000000)
2.9999999999999996
julia> log10(1000000)/2
3.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L341-L381)###
`Base.log2`Function
```
log2(x)
```
Compute the logarithm of `x` to base 2. Throws [`DomainError`](../base/index#Core.DomainError) for negative [`Real`](../numbers/index#Core.Real) arguments.
See also: [`exp2`](#Base.exp2), [`ldexp`](#Base.Math.ldexp), [`ispow2`](#Base.ispow2).
**Examples**
```
julia> log2(4)
2.0
julia> log2(10)
3.321928094887362
julia> log2(-2)
ERROR: DomainError with -2.0:
log2 will only return a complex result if called with a complex argument. Try log2(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(f::Symbol, x::Float64) at ./math.jl:31
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L516-L539)###
`Base.log10`Function
```
log10(x)
```
Compute the logarithm of `x` to base 10. Throws [`DomainError`](../base/index#Core.DomainError) for negative [`Real`](../numbers/index#Core.Real) arguments.
**Examples**
```
julia> log10(100)
2.0
julia> log10(2)
0.3010299956639812
julia> log10(-2)
ERROR: DomainError with -2.0:
log10 will only return a complex result if called with a complex argument. Try log10(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(f::Symbol, x::Float64) at ./math.jl:31
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L542-L563)###
`Base.log1p`Function
```
log1p(x)
```
Accurate natural logarithm of `1+x`. Throws [`DomainError`](../base/index#Core.DomainError) for [`Real`](../numbers/index#Core.Real) arguments less than -1.
**Examples**
```
julia> log1p(-0.5)
-0.6931471805599453
julia> log1p(0)
0.0
julia> log1p(-2)
ERROR: DomainError with -2.0:
log1p will only return a complex result if called with a complex argument. Try log1p(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L566-L587)###
`Base.Math.frexp`Function
```
frexp(val)
```
Return `(x,exp)` such that `x` has a magnitude in the interval $[1/2, 1)$ or 0, and `val` is equal to $x \times 2^{exp}$.
**Examples**
```
julia> frexp(12.8)
(0.8, 4)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L909-L919)###
`Base.exp`Method
```
exp(x)
```
Compute the natural base exponential of `x`, in other words $ℯ^x$.
See also [`exp2`](#Base.exp2), [`exp10`](#Base.exp10) and [`cis`](#Base.cis).
**Examples**
```
julia> exp(1.0)
2.718281828459045
julia> exp(im * pi) ≈ cis(pi)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/exp.jl#L331-L346)###
`Base.exp2`Function
```
exp2(x)
```
Compute the base 2 exponential of `x`, in other words $2^x$.
See also [`ldexp`](#Base.Math.ldexp), [`<<`](#Base.:<<).
**Examples**
```
julia> exp2(5)
32.0
julia> 2^5
32
julia> exp2(63) > typemax(Int)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/exp.jl#L348-L366)###
`Base.exp10`Function
```
exp10(x)
```
Compute the base 10 exponential of `x`, in other words $10^x$.
**Examples**
```
julia> exp10(2)
100.0
julia> 10^2
100
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/exp.jl#L369-L382)###
`Base.Math.ldexp`Function
```
ldexp(x, n)
```
Compute $x \times 2^n$.
**Examples**
```
julia> ldexp(5., 2)
20.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L772-L782)###
`Base.Math.modf`Function
```
modf(x)
```
Return a tuple `(fpart, ipart)` of the fractional and integral parts of a number. Both parts have the same sign as the argument.
**Examples**
```
julia> modf(3.5)
(0.5, 3.0)
julia> modf(-3.5)
(-0.5, -3.0)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L972-L986)###
`Base.expm1`Function
```
expm1(x)
```
Accurately compute $e^x-1$. It avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small values of x.
**Examples**
```
julia> expm1(1e-16)
1.0e-16
julia> exp(1e-16) - 1
0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/exp.jl#L487-L500)###
`Base.round`Method
```
round([T,] x, [r::RoundingMode])
round(x, [r::RoundingMode]; digits::Integer=0, base = 10)
round(x, [r::RoundingMode]; sigdigits::Integer, base = 10)
```
Rounds the number `x`.
Without keyword arguments, `x` is rounded to an integer value, returning a value of type `T`, or of the same type of `x` if no `T` is provided. An [`InexactError`](../base/index#Core.InexactError) will be thrown if the value is not representable by `T`, similar to [`convert`](../base/index#Base.convert).
If the `digits` keyword argument is provided, it rounds to the specified number of digits after the decimal place (or before if negative), in base `base`.
If the `sigdigits` keyword argument is provided, it rounds to the specified number of significant digits, in base `base`.
The [`RoundingMode`](#Base.Rounding.RoundingMode) `r` controls the direction of the rounding; the default is [`RoundNearest`](#Base.Rounding.RoundNearest), which rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer. Note that `round` may give incorrect results if the global rounding mode is changed (see [`rounding`](../numbers/index#Base.Rounding.rounding)).
**Examples**
```
julia> round(1.7)
2.0
julia> round(Int, 1.7)
2
julia> round(1.5)
2.0
julia> round(2.5)
2.0
julia> round(pi; digits=2)
3.14
julia> round(pi; digits=3, base=2)
3.125
julia> round(123.456; sigdigits=2)
120.0
julia> round(357.913; sigdigits=4, base=2)
352.0
```
Rounding to specified digits in bases other than 2 can be inexact when operating on binary floating point numbers. For example, the [`Float64`](../numbers/index#Core.Float64) value represented by `1.15` is actually *less* than 1.15, yet will be rounded to 1.2. For example:
```
julia> x = 1.15
1.15
julia> @sprintf "%.20f" x
"1.14999999999999991118"
julia> x < 115//100
true
julia> round(x, digits=1)
1.2
```
**Extensions**
To extend `round` to new numeric types, it is typically sufficient to define `Base.round(x::NewType, r::RoundingMode)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/floatfuncs.jl#L47-L119)###
`Base.Rounding.RoundingMode`Type
```
RoundingMode
```
A type used for controlling the rounding mode of floating point operations (via [`rounding`](../numbers/index#Base.Rounding.rounding)/[`setrounding`](#) functions), or as optional arguments for rounding to the nearest integer (via the [`round`](#Base.round-Tuple%7BType,%20Any%7D) function).
Currently supported rounding modes are:
* [`RoundNearest`](#Base.Rounding.RoundNearest) (default)
* [`RoundNearestTiesAway`](#Base.Rounding.RoundNearestTiesAway)
* [`RoundNearestTiesUp`](#Base.Rounding.RoundNearestTiesUp)
* [`RoundToZero`](#Base.Rounding.RoundToZero)
* [`RoundFromZero`](#Base.Rounding.RoundFromZero) ([`BigFloat`](../numbers/index#Base.MPFR.BigFloat) only)
* [`RoundUp`](#Base.Rounding.RoundUp)
* [`RoundDown`](#Base.Rounding.RoundDown)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L26-L43)###
`Base.Rounding.RoundNearest`Constant
```
RoundNearest
```
The default rounding mode. Rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L46-L51)###
`Base.Rounding.RoundNearestTiesAway`Constant
```
RoundNearestTiesAway
```
Rounds to nearest integer, with ties rounded away from zero (C/C++ [`round`](#Base.round-Tuple%7BType,%20Any%7D) behaviour).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L89-L94)###
`Base.Rounding.RoundNearestTiesUp`Constant
```
RoundNearestTiesUp
```
Rounds to nearest integer, with ties rounded toward positive infinity (Java/JavaScript [`round`](#Base.round-Tuple%7BType,%20Any%7D) behaviour).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L97-L102)###
`Base.Rounding.RoundToZero`Constant
```
RoundToZero
```
[`round`](#Base.round-Tuple%7BType,%20Any%7D) using this rounding mode is an alias for [`trunc`](#Base.trunc).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L54-L58)###
`Base.Rounding.RoundFromZero`Constant
```
RoundFromZero
```
Rounds away from zero. This rounding mode may only be used with `T == BigFloat` inputs to [`round`](#Base.round-Tuple%7BType,%20Any%7D).
**Examples**
```
julia> BigFloat("1.0000000000000001", 5, RoundFromZero)
1.06
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L75-L86)###
`Base.Rounding.RoundUp`Constant
```
RoundUp
```
[`round`](#Base.round-Tuple%7BType,%20Any%7D) using this rounding mode is an alias for [`ceil`](#Base.ceil).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L61-L65)###
`Base.Rounding.RoundDown`Constant
```
RoundDown
```
[`round`](#Base.round-Tuple%7BType,%20Any%7D) using this rounding mode is an alias for [`floor`](#Base.floor).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/rounding.jl#L68-L72)###
`Base.round`Method
```
round(z::Complex[, RoundingModeReal, [RoundingModeImaginary]])
round(z::Complex[, RoundingModeReal, [RoundingModeImaginary]]; digits=, base=10)
round(z::Complex[, RoundingModeReal, [RoundingModeImaginary]]; sigdigits=, base=10)
```
Return the nearest integral value of the same type as the complex-valued `z` to `z`, breaking ties using the specified [`RoundingMode`](#Base.Rounding.RoundingMode)s. The first [`RoundingMode`](#Base.Rounding.RoundingMode) is used for rounding the real components while the second is used for rounding the imaginary components.
**Example**
```
julia> round(3.14 + 4.5im)
3.0 + 4.0im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L1064-L1079)###
`Base.ceil`Function
```
ceil([T,] x)
ceil(x; digits::Integer= [, base = 10])
ceil(x; sigdigits::Integer= [, base = 10])
```
`ceil(x)` returns the nearest integral value of the same type as `x` that is greater than or equal to `x`.
`ceil(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is not representable.
Keywords `digits`, `sigdigits` and `base` work as for [`round`](#Base.round-Tuple%7BType,%20Any%7D).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L634-L646)###
`Base.floor`Function
```
floor([T,] x)
floor(x; digits::Integer= [, base = 10])
floor(x; sigdigits::Integer= [, base = 10])
```
`floor(x)` returns the nearest integral value of the same type as `x` that is less than or equal to `x`.
`floor(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is not representable.
Keywords `digits`, `sigdigits` and `base` work as for [`round`](#Base.round-Tuple%7BType,%20Any%7D).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L619-L631)###
`Base.trunc`Function
```
trunc([T,] x)
trunc(x; digits::Integer= [, base = 10])
trunc(x; sigdigits::Integer= [, base = 10])
```
`trunc(x)` returns the nearest integral value of the same type as `x` whose absolute value is less than or equal to the absolute value of `x`.
`trunc(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is not representable.
Keywords `digits`, `sigdigits` and `base` work as for [`round`](#Base.round-Tuple%7BType,%20Any%7D).
See also: [`%`](#Base.rem), [`floor`](#Base.floor), [`unsigned`](../numbers/index#Base.unsigned), [`unsafe_trunc`](#Base.unsafe_trunc).
**Examples**
```
julia> trunc(2.22)
2.0
julia> trunc(-2.22, digits=1)
-2.2
julia> trunc(Int, -2.22)
-2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L590-L616)###
`Base.unsafe_trunc`Function
```
unsafe_trunc(T, x)
```
Return the nearest integral value of type `T` whose absolute value is less than or equal to the absolute value of `x`. If the value is not representable by `T`, an arbitrary value will be returned. See also [`trunc`](#Base.trunc).
**Examples**
```
julia> unsafe_trunc(Int, -2.2)
-2
julia> unsafe_trunc(Int, NaN)
-9223372036854775808
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L289-L305)###
`Base.min`Function
```
min(x, y, ...)
```
Return the minimum of the arguments (with respect to [`isless`](../base/index#Base.isless)). See also the [`minimum`](../collections/index#Base.minimum) function to take the minimum element from a collection.
**Examples**
```
julia> min(2, 5, 1)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L482-L493)###
`Base.max`Function
```
max(x, y, ...)
```
Return the maximum of the arguments (with respect to [`isless`](../base/index#Base.isless)). See also the [`maximum`](../collections/index#Base.maximum) function to take the maximum element from a collection.
**Examples**
```
julia> max(2, 5, 1)
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L468-L479)###
`Base.minmax`Function
```
minmax(x, y)
```
Return `(min(x,y), max(x,y))`.
See also [`extrema`](../collections/index#Base.extrema) that returns `(minimum(x), maximum(x))`.
**Examples**
```
julia> minmax('c','b')
('b', 'c')
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L496-L508)###
`Base.Math.clamp`Function
```
clamp(x, lo, hi)
```
Return `x` if `lo <= x <= hi`. If `x > hi`, return `hi`. If `x < lo`, return `lo`. Arguments are promoted to a common type.
See also [`clamp!`](#Base.Math.clamp!), [`min`](#Base.min), [`max`](#Base.max).
`missing` as the first argument requires at least Julia 1.3.
**Examples**
```
julia> clamp.([pi, 1.0, big(10)], 2.0, 9.0)
3-element Vector{BigFloat}:
3.141592653589793238462643383279502884197169399375105820974944592307816406286198
2.0
9.0
julia> clamp.([11, 8, 5], 10, 6) # an example where lo > hi
3-element Vector{Int64}:
6
6
10
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L63-L88)
```
clamp(x, T)::T
```
Clamp `x` between `typemin(T)` and `typemax(T)` and convert the result to type `T`.
See also [`trunc`](#Base.trunc).
**Examples**
```
julia> clamp(200, Int8)
127
julia> clamp(-200, Int8)
-128
julia> trunc(Int, 4pi^2)
39
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L95-L113)
```
clamp(x::Integer, r::AbstractUnitRange)
```
Clamp `x` to lie within range `r`.
This method requires at least Julia 1.6.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L146-L153)###
`Base.Math.clamp!`Function
```
clamp!(array::AbstractArray, lo, hi)
```
Restrict values in `array` to the specified range, in-place. See also [`clamp`](#Base.Math.clamp).
`missing` entries in `array` require at least Julia 1.3.
**Examples**
```
julia> row = collect(-4:4)';
julia> clamp!(row, 0, Inf)
1×9 adjoint(::Vector{Int64}) with eltype Int64:
0 0 0 0 0 1 2 3 4
julia> clamp.((-4:4)', 0, Inf)
1×9 Matrix{Float64}:
0.0 0.0 0.0 0.0 0.0 1.0 2.0 3.0 4.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L117-L138)###
`Base.abs`Function
```
abs(x)
```
The absolute value of `x`.
When `abs` is applied to signed integers, overflow may occur, resulting in the return of a negative value. This overflow occurs only when `abs` is applied to the minimum representable value of a signed integer. That is, when `x == typemin(typeof(x))`, `abs(x) == x < 0`, not `-x` as might be expected.
See also: [`abs2`](#Base.abs2), [`unsigned`](../numbers/index#Base.unsigned), [`sign`](#Base.sign).
**Examples**
```
julia> abs(-3)
3
julia> abs(1 + im)
1.4142135623730951
julia> abs(typemin(Int64))
-9223372036854775808
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L156-L180)###
`Base.Checked.checked_abs`Function
```
Base.checked_abs(x)
```
Calculates `abs(x)`, checking for overflow errors where applicable. For example, standard two's complement signed integers (e.g. `Int`) cannot represent `abs(typemin(Int))`, thus leading to an overflow.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L105-L113)###
`Base.Checked.checked_neg`Function
```
Base.checked_neg(x)
```
Calculates `-x`, checking for overflow errors where applicable. For example, standard two's complement signed integers (e.g. `Int`) cannot represent `-typemin(Int)`, thus leading to an overflow.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L77-L85)###
`Base.Checked.checked_add`Function
```
Base.checked_add(x, y)
```
Calculates `x+y`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L157-L163)###
`Base.Checked.checked_sub`Function
```
Base.checked_sub(x, y)
```
Calculates `x-y`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L214-L220)###
`Base.Checked.checked_mul`Function
```
Base.checked_mul(x, y)
```
Calculates `x*y`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L279-L285)###
`Base.Checked.checked_div`Function
```
Base.checked_div(x, y)
```
Calculates `div(x,y)`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L308-L314)###
`Base.Checked.checked_rem`Function
```
Base.checked_rem(x, y)
```
Calculates `x%y`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L317-L323)###
`Base.Checked.checked_fld`Function
```
Base.checked_fld(x, y)
```
Calculates `fld(x,y)`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L326-L332)###
`Base.Checked.checked_mod`Function
```
Base.checked_mod(x, y)
```
Calculates `mod(x,y)`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L335-L341)###
`Base.Checked.checked_cld`Function
```
Base.checked_cld(x, y)
```
Calculates `cld(x,y)`, checking for overflow errors where applicable.
The overflow protection may impose a perceptible performance penalty.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L344-L350)###
`Base.Checked.add_with_overflow`Function
```
Base.add_with_overflow(x, y) -> (r, f)
```
Calculates `r = x+y`, with the flag `f` indicating whether overflow has occurred.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L127-L131)###
`Base.Checked.sub_with_overflow`Function
```
Base.sub_with_overflow(x, y) -> (r, f)
```
Calculates `r = x-y`, with the flag `f` indicating whether overflow has occurred.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L189-L193)###
`Base.Checked.mul_with_overflow`Function
```
Base.mul_with_overflow(x, y) -> (r, f)
```
Calculates `r = x*y`, with the flag `f` indicating whether overflow has occurred.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L229-L233)###
`Base.abs2`Function
```
abs2(x)
```
Squared absolute value of `x`.
**Examples**
```
julia> abs2(-3)
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L166-L176)###
`Base.copysign`Function
```
copysign(x, y) -> z
```
Return `z` which has the magnitude of `x` and the same sign as `y`.
**Examples**
```
julia> copysign(1, -2)
-1
julia> copysign(-1, 2)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L195-L208)###
`Base.sign`Function
```
sign(x)
```
Return zero if `x==0` and $x/|x|$ otherwise (i.e., ±1 for real `x`).
See also [`signbit`](#Base.signbit), [`zero`](../numbers/index#Base.zero), [`copysign`](#Base.copysign), [`flipsign`](#Base.flipsign).
**Examples**
```
julia> sign(-4.0)
-1.0
julia> sign(99)
1
julia> sign(-0.0)
-0.0
julia> sign(0 + im)
0.0 + 1.0im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L139-L160)###
`Base.signbit`Function
```
signbit(x)
```
Returns `true` if the value of the sign of `x` is negative, otherwise `false`.
See also [`sign`](#Base.sign) and [`copysign`](#Base.copysign).
**Examples**
```
julia> signbit(-4)
true
julia> signbit(5)
false
julia> signbit(5.5)
false
julia> signbit(-4.1)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L115-L136)###
`Base.flipsign`Function
```
flipsign(x, y)
```
Return `x` with its sign flipped if `y` is negative. For example `abs(x) = flipsign(x,x)`.
**Examples**
```
julia> flipsign(5, 3)
5
julia> flipsign(5, -3)
-5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L179-L192)###
`Base.sqrt`Method
```
sqrt(x)
```
Return $\sqrt{x}$. Throws [`DomainError`](../base/index#Core.DomainError) for negative [`Real`](../numbers/index#Core.Real) arguments. Use complex negative arguments instead. The prefix operator `√` is equivalent to `sqrt`.
See also: [`hypot`](#Base.Math.hypot).
**Examples**
```
julia> sqrt(big(81))
9.0
julia> sqrt(big(-81))
ERROR: DomainError with -81.0:
NaN result for non-NaN input.
Stacktrace:
[1] sqrt(::BigFloat) at ./mpfr.jl:501
[...]
julia> sqrt(big(complex(-81)))
0.0 + 9.0im
julia> .√(1:4)
4-element Vector{Float64}:
1.0
1.4142135623730951
1.7320508075688772
2.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L595-L625)###
`Base.isqrt`Function
```
isqrt(n::Integer)
```
Integer square root: the largest integer `m` such that `m*m <= n`.
```
julia> isqrt(5)
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L960-L969)###
`Base.Math.cbrt`Function
```
cbrt(x::Real)
```
Return the cube root of `x`, i.e. $x^{1/3}$. Negative values are accepted (returning the negative real root when $x < 0$).
The prefix operator `∛` is equivalent to `cbrt`.
**Examples**
```
julia> cbrt(big(27))
3.0
julia> cbrt(big(-27))
-3.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/special/cbrt.jl#L17-L33)###
`Base.real`Function
```
real(z)
```
Return the real part of the complex number `z`.
See also: [`imag`](#Base.imag), [`reim`](#Base.reim), [`complex`](#), [`isreal`](../numbers/index#Base.isreal), [`Real`](../numbers/index#Core.Real).
**Examples**
```
julia> real(1 + 3im)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L59-L71)
```
real(T::Type)
```
Return the type that represents the real part of a value of type `T`. e.g: for `T == Complex{R}`, returns `R`. Equivalent to `typeof(real(zero(T)))`.
**Examples**
```
julia> real(Complex{Int})
Int64
julia> real(Float64)
Float64
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L104-L119)
```
real(A::AbstractArray)
```
Return an array containing the real part of each entry in array `A`.
Equivalent to `real.(A)`, except that when `eltype(A) <: Real` `A` is returned without copying, and that when `A` has zero dimensions, a 0-dimensional array is returned (rather than a scalar).
**Examples**
```
julia> real([1, 2im, 3 + 4im])
3-element Vector{Int64}:
1
0
3
julia> real(fill(2 - im))
0-dimensional Array{Int64, 0}:
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L148-L169)###
`Base.imag`Function
```
imag(z)
```
Return the imaginary part of the complex number `z`.
See also: [`conj`](#Base.conj), [`reim`](#Base.reim), [`adjoint`](../../stdlib/linearalgebra/index#Base.adjoint), [`angle`](#Base.angle).
**Examples**
```
julia> imag(1 + 3im)
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L74-L86)
```
imag(A::AbstractArray)
```
Return an array containing the imaginary part of each entry in array `A`.
Equivalent to `imag.(A)`, except that when `A` has zero dimensions, a 0-dimensional array is returned (rather than a scalar).
**Examples**
```
julia> imag([1, 2im, 3 + 4im])
3-element Vector{Int64}:
0
2
4
julia> imag(fill(2 - im))
0-dimensional Array{Int64, 0}:
-1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L173-L193)###
`Base.reim`Function
```
reim(z)
```
Return a tuple of the real and imaginary parts of the complex number `z`.
**Examples**
```
julia> reim(1 + 3im)
(1, 3)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L91-L101)
```
reim(A::AbstractArray)
```
Return a tuple of two arrays containing respectively the real and the imaginary part of each entry in `A`.
Equivalent to `(real.(A), imag.(A))`, except that when `eltype(A) <: Real` `A` is returned without copying to represent the real part, and that when `A` has zero dimensions, a 0-dimensional array is returned (rather than a scalar).
**Examples**
```
julia> reim([1, 2im, 3 + 4im])
([1, 0, 3], [0, 2, 4])
julia> reim(fill(2 - im))
(fill(2), fill(-1))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L197-L215)###
`Base.conj`Function
```
conj(z)
```
Compute the complex conjugate of a complex number `z`.
See also: [`angle`](#Base.angle), [`adjoint`](../../stdlib/linearalgebra/index#Base.adjoint).
**Examples**
```
julia> conj(1 + 3im)
1 - 3im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L263-L275)
```
conj(A::AbstractArray)
```
Return an array containing the complex conjugate of each entry in array `A`.
Equivalent to `conj.(A)`, except that when `eltype(A) <: Real` `A` is returned without copying, and that when `A` has zero dimensions, a 0-dimensional array is returned (rather than a scalar).
**Examples**
```
julia> conj([1, 2im, 3 + 4im])
3-element Vector{Complex{Int64}}:
1 + 0im
0 - 2im
3 - 4im
julia> conj(fill(2 - im))
0-dimensional Array{Complex{Int64}, 0}:
2 + 1im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L123-L144)###
`Base.angle`Function
```
angle(z)
```
Compute the phase angle in radians of a complex number `z`.
See also: [`atan`](#Base.atan-Tuple%7BNumber%7D), [`cis`](#Base.cis).
**Examples**
```
julia> rad2deg(angle(1 + im))
45.0
julia> rad2deg(angle(1 - im))
-45.0
julia> rad2deg(angle(-1 - im))
-135.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L608-L626)###
`Base.cis`Function
```
cis(x)
```
More efficient method for `exp(im*x)` by using Euler's formula: $cos(x) + i sin(x) = \exp(i x)$.
See also [`cispi`](#Base.cispi), [`sincos`](#Base.Math.sincos-Tuple%7BFloat64%7D), [`exp`](#Base.exp-Tuple%7BFloat64%7D), [`angle`](#Base.angle).
**Examples**
```
julia> cis(π) ≈ -1
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L556-L568)###
`Base.cispi`Function
```
cispi(x)
```
More accurate method for `cis(pi*x)` (especially for large `x`).
See also [`cis`](#Base.cis), [`sincospi`](#Base.Math.sincospi), [`exp`](#Base.exp-Tuple%7BFloat64%7D), [`angle`](#Base.angle).
**Examples**
```
julia> cispi(10000)
1.0 + 0.0im
julia> cispi(0.25 + 1im)
0.030556854645952924 + 0.030556854645952924im
```
This function requires Julia 1.6 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/complex.jl#L581-L599)###
`Base.binomial`Function
```
binomial(n::Integer, k::Integer)
```
The *binomial coefficient* $\binom{n}{k}$, being the coefficient of the $k$th term in the polynomial expansion of $(1+x)^n$.
If $n$ is non-negative, then it is the number of ways to choose `k` out of `n` items:
\[\binom{n}{k} = \frac{n!}{k! (n-k)!}\]
where $n!$ is the [`factorial`](#Base.factorial) function.
If $n$ is negative, then it is defined in terms of the identity
\[\binom{n}{k} = (-1)^k \binom{k-n-1}{k}\]
See also [`factorial`](#Base.factorial).
**Examples**
```
julia> binomial(5, 3)
10
julia> factorial(5) ÷ (factorial(5-3) * factorial(3))
10
julia> binomial(-5, 3)
-35
```
**External links**
* [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) on Wikipedia.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L1016-L1049)###
`Base.factorial`Function
```
factorial(n::Integer)
```
Factorial of `n`. If `n` is an [`Integer`](../numbers/index#Core.Integer), the factorial is computed as an integer (promoted to at least 64 bits). Note that this may overflow if `n` is not small, but you can use `factorial(big(n))` to compute the result exactly in arbitrary precision.
See also [`binomial`](#Base.binomial).
**Examples**
```
julia> factorial(6)
720
julia> factorial(21)
ERROR: OverflowError: 21 is too large to look up in the table; consider using `factorial(big(21))` instead
Stacktrace:
[...]
julia> factorial(big(21))
51090942171709440000
```
**External links**
* [Factorial](https://en.wikipedia.org/wiki/Factorial) on Wikipedia.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L981-L1006)###
`Base.gcd`Function
```
gcd(x, y...)
```
Greatest common (positive) divisor (or zero if all arguments are zero). The arguments may be integer and rational numbers.
Rational arguments require Julia 1.4 or later.
**Examples**
```
julia> gcd(6, 9)
3
julia> gcd(6, -9)
3
julia> gcd(6, 0)
6
julia> gcd(0, 0)
0
julia> gcd(1//3, 2//3)
1//3
julia> gcd(1//3, -2//3)
1//3
julia> gcd(1//3, 2)
1//3
julia> gcd(0, 0, 10, 15)
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L5-L40)###
`Base.lcm`Function
```
lcm(x, y...)
```
Least common (positive) multiple (or zero if any argument is zero). The arguments may be integer and rational numbers.
Rational arguments require Julia 1.4 or later.
**Examples**
```
julia> lcm(2, 3)
6
julia> lcm(-2, 3)
6
julia> lcm(0, 3)
0
julia> lcm(0, 0)
0
julia> lcm(1//3, 2//3)
2//3
julia> lcm(1//3, -2//3)
2//3
julia> lcm(1//3, 2)
2//1
julia> lcm(1, 3, 5, 7)
105
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L83-L118)###
`Base.gcdx`Function
```
gcdx(a, b)
```
Computes the greatest common (positive) divisor of `a` and `b` and their Bézout coefficients, i.e. the integer coefficients `u` and `v` that satisfy $ua+vb = d = gcd(a, b)$. $gcdx(a, b)$ returns $(d, u, v)$.
The arguments may be integer and rational numbers.
Rational arguments require Julia 1.4 or later.
**Examples**
```
julia> gcdx(12, 42)
(6, -3, 1)
julia> gcdx(240, 46)
(2, -9, 47)
```
Bézout coefficients are *not* uniquely defined. `gcdx` returns the minimal Bézout coefficients that are computed by the extended Euclidean algorithm. (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) For signed integers, these coefficients `u` and `v` are minimal in the sense that $|u| < |y/d|$ and $|v| < |x/d|$. Furthermore, the signs of `u` and `v` are chosen so that `d` is positive. For unsigned integers, the coefficients `u` and `v` might be near their `typemax`, and the identity then holds only via the unsigned integers' modulo arithmetic.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L156-L187)###
`Base.ispow2`Function
```
ispow2(n::Number) -> Bool
```
Test whether `n` is an integer power of two.
See also [`count_ones`](../numbers/index#Base.count_ones), [`prevpow`](#Base.prevpow), [`nextpow`](#Base.nextpow).
**Examples**
```
julia> ispow2(4)
true
julia> ispow2(5)
false
julia> ispow2(4.5)
false
julia> ispow2(0.25)
true
julia> ispow2(1//8)
true
```
Support for non-`Integer` arguments was added in Julia 1.6.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L401-L428)###
`Base.nextpow`Function
```
nextpow(a, x)
```
The smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be greater than 1, and `x` must be greater than 0.
See also [`prevpow`](#Base.prevpow).
**Examples**
```
julia> nextpow(2, 7)
8
julia> nextpow(2, 9)
16
julia> nextpow(5, 20)
25
julia> nextpow(4, 16)
16
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L433-L455)###
`Base.prevpow`Function
```
prevpow(a, x)
```
The largest `a^n` not greater than `x`, where `n` is a non-negative integer. `a` must be greater than 1, and `x` must not be less than 1.
See also [`nextpow`](#Base.nextpow), [`isqrt`](#Base.isqrt).
**Examples**
```
julia> prevpow(2, 7)
4
julia> prevpow(2, 9)
8
julia> prevpow(5, 20)
5
julia> prevpow(4, 16)
16
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L470-L492)###
`Base.nextprod`Function
```
nextprod(factors::Union{Tuple,AbstractVector}, n)
```
Next integer greater than or equal to `n` that can be written as $\prod k\_i^{p\_i}$ for integers $p\_1$, $p\_2$, etcetera, for factors $k\_i$ in `factors`.
**Examples**
```
julia> nextprod((2, 3), 105)
108
julia> 2^2 * 3^3
108
```
The method that accepts a tuple requires Julia 1.6 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/combinatorics.jl#L311-L328)###
`Base.invmod`Function
```
invmod(n, m)
```
Take the inverse of `n` modulo `m`: `y` such that $n y = 1 \pmod m$, and $div(y,m) = 0$. This will throw an error if $m = 0$, or if $gcd(n,m) \neq 1$.
**Examples**
```
julia> invmod(2, 5)
3
julia> invmod(2, 3)
2
julia> invmod(5, 6)
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L209-L227)###
`Base.powermod`Function
```
powermod(x::Integer, p::Integer, m)
```
Compute $x^p \pmod m$.
**Examples**
```
julia> powermod(2, 6, 5)
4
julia> mod(2^6, 5)
4
julia> powermod(5, 2, 20)
5
julia> powermod(5, 2, 19)
6
julia> powermod(5, 3, 19)
11
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L350-L372)###
`Base.ndigits`Function
```
ndigits(n::Integer; base::Integer=10, pad::Integer=1)
```
Compute the number of digits in integer `n` written in base `base` (`base` must not be in `[-1, 0, 1]`), optionally padded with zeros to a specified size (the result will never be less than `pad`).
See also [`digits`](../numbers/index#Base.digits), [`count_ones`](../numbers/index#Base.count_ones).
**Examples**
```
julia> ndigits(12345)
5
julia> ndigits(1022, base=16)
3
julia> string(1022, base=16)
"3fe"
julia> ndigits(123, pad=5)
5
julia> ndigits(-123)
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/intfuncs.jl#L631-L657)###
`Base.add_sum`Function
```
Base.add_sum(x, y)
```
The reduction operator used in `sum`. The main difference from [`+`](#Base.:+) is that small integers are promoted to `Int`/`UInt`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L18-L23)###
`Base.widemul`Function
```
widemul(x, y)
```
Multiply `x` and `y`, giving the result as a larger type.
See also [`promote`](../base/index#Base.promote), [`Base.add_sum`](#Base.add_sum).
**Examples**
```
julia> widemul(Float32(3.0), 4.0) isa BigFloat
true
julia> typemax(Int8) * typemax(Int8)
1
julia> widemul(typemax(Int8), typemax(Int8)) # == 127^2
16129
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/number.jl#L246-L264)###
`Base.Math.evalpoly`Function
```
evalpoly(x, p)
```
Evaluate the polynomial $\sum\_k x^{k-1} p[k]$ for the coefficients `p[1]`, `p[2]`, ...; that is, the coefficients are given in ascending order by power of `x`. Loops are unrolled at compile time if the number of coefficients is statically known, i.e. when `p` is a `Tuple`. This function generates efficient code using Horner's method if `x` is real, or using a Goertzel-like [[DK62]](#footnote-DK62) algorithm if `x` is complex.
This function requires Julia 1.4 or later.
**Example**
```
julia> evalpoly(2, (1, 2, 3))
17
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L156-L176)###
`Base.Math.@evalpoly`Macro
```
@evalpoly(z, c...)
```
Evaluate the polynomial $\sum\_k z^{k-1} c[k]$ for the coefficients `c[1]`, `c[2]`, ...; that is, the coefficients are given in ascending order by power of `z`. This macro expands to efficient inline code that uses either Horner's method or, for complex `z`, a more efficient Goertzel-like algorithm.
See also [`evalpoly`](#Base.Math.evalpoly).
**Examples**
```
julia> @evalpoly(3, 1, 0, 1)
10
julia> @evalpoly(2, 1, 0, 1)
5
julia> @evalpoly(2, 1, 1, 1)
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/math.jl#L267-L288)###
`Base.FastMath.@fastmath`Macro
```
@fastmath expr
```
Execute a transformed version of the expression, which calls functions that may violate strict IEEE semantics. This allows the fastest possible operation, but results are undefined – be careful when doing this, as it may change numerical results.
This sets the [LLVM Fast-Math flags](http://llvm.org/docs/LangRef.html#fast-math-flags), and corresponds to the `-ffast-math` option in clang. See [the notes on performance annotations](../../manual/performance-tips/index#man-performance-annotations) for more details.
**Examples**
```
julia> @fastmath 1+2
3
julia> @fastmath(sin(3))
0.1411200080598672
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/fastmath.jl#L133-L153)
[Customizable binary operators](#Customizable-binary-operators)
----------------------------------------------------------------
Some unicode characters can be used to define new binary operators that support infix notation. For example `⊗(x,y) = kron(x,y)` defines the `⊗` (otimes) function to be the Kronecker product, and one can call it as binary operator using infix syntax: `C = A ⊗ B` as well as with the usual prefix syntax `C = ⊗(A,B)`.
Other characters that support such extensions include \odot `⊙` and \oplus `⊕`
The complete list is in the parser code: <https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm>
Those that are parsed like `*` (in terms of precedence) include `* / ÷ % & ⋅ ∘ × |\\| ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇ ⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻ ⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗` and those that are parsed like `+` include `+ - |\|| ⊕ ⊖ ⊞ ⊟ |++| ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦ ⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣` There are many others that are related to arrows, comparisons, and powers.
* [DK62](#citeref-DK62)Donald Knuth, Art of Computer Programming, Volume 2: Seminumerical Algorithms, Sec. 4.6.4.
| programming_docs |
julia I/O and Network I/O and Network
===============
[General I/O](#General-I/O)
----------------------------
###
`Base.stdout`Constant
```
stdout::IO
```
Global variable referring to the standard out stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libuv.jl#L139-L143)###
`Base.stderr`Constant
```
stderr::IO
```
Global variable referring to the standard error stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libuv.jl#L146-L150)###
`Base.stdin`Constant
```
stdin::IO
```
Global variable referring to the standard input stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libuv.jl#L132-L136)###
`Base.open`Function
```
open(f::Function, args...; kwargs...)
```
Apply the function `f` to the result of `open(args...; kwargs...)` and close the resulting file descriptor upon completion.
**Examples**
```
julia> open("myfile.txt", "w") do io
write(io, "Hello world!")
end;
julia> open(f->read(f, String), "myfile.txt")
"Hello world!"
julia> rm("myfile.txt")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L363-L380)
```
open(filename::AbstractString; lock = true, keywords...) -> IOStream
```
Open a file in a mode specified by five boolean keyword arguments:
| Keyword | Description | Default |
| --- | --- | --- |
| `read` | open for reading | `!write` |
| `write` | open for writing | `truncate | append` |
| `create` | create if non-existent | `!read & write | truncate | append` |
| `truncate` | truncate to zero size | `!read & write` |
| `append` | seek to end | `false` |
The default when no keywords are passed is to open files for reading only. Returns a stream for accessing the opened file.
The `lock` keyword argument controls whether operations will be locked for safe multi-threaded access.
The `lock` argument is available as of Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L253-L274)
```
open(filename::AbstractString, [mode::AbstractString]; lock = true) -> IOStream
```
Alternate syntax for open, where a string-based mode specifier is used instead of the five booleans. The values of `mode` correspond to those from `fopen(3)` or Perl `open`, and are equivalent to setting the following boolean groups:
| Mode | Description | Keywords |
| --- | --- | --- |
| `r` | read | none |
| `w` | write, create, truncate | `write = true` |
| `a` | write, create, append | `append = true` |
| `r+` | read, write | `read = true, write = true` |
| `w+` | read, write, create, truncate | `truncate = true, read = true` |
| `a+` | read, write, create, append | `append = true, read = true` |
The `lock` keyword argument controls whether operations will be locked for safe multi-threaded access.
**Examples**
```
julia> io = open("myfile.txt", "w");
julia> write(io, "Hello world!");
julia> close(io);
julia> io = open("myfile.txt", "r");
julia> read(io, String)
"Hello world!"
julia> write(io, "This file is read only")
ERROR: ArgumentError: write failed, IOStream is not writeable
[...]
julia> close(io)
julia> io = open("myfile.txt", "a");
julia> write(io, "This stream is not read only")
28
julia> close(io)
julia> rm("myfile.txt")
```
The `lock` argument is available as of Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L304-L354)
```
open(fd::OS_HANDLE) -> IO
```
Take a raw file descriptor wrap it in a Julia-aware IO type, and take ownership of the fd handle. Call `open(Libc.dup(fd))` to avoid the ownership capture of the original handle.
Do not call this on a handle that's already owned by some other part of the system.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L318-L329)
```
open(command, mode::AbstractString, stdio=devnull)
```
Run `command` asynchronously. Like `open(command, stdio; read, write)` except specifying the read and write flags via a mode string instead of keyword arguments. Possible mode strings are:
| Mode | Description | Keywords |
| --- | --- | --- |
| `r` | read | none |
| `w` | write | `write = true` |
| `r+` | read, write | `read = true, write = true` |
| `w+` | read, write | `read = true, write = true` |
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L346-L359)
```
open(command, stdio=devnull; write::Bool = false, read::Bool = !write)
```
Start running `command` asynchronously, and return a `process::IO` object. If `read` is true, then reads from the process come from the process's standard output and `stdio` optionally specifies the process's standard input stream. If `write` is true, then writes go to the process's standard input and `stdio` optionally specifies the process's standard output stream. The process's standard error stream is connected to the current global `stderr`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L373-L382)
```
open(f::Function, command, args...; kwargs...)
```
Similar to `open(command, args...; kwargs...)`, but calls `f(stream)` on the resulting process stream, then closes the input stream and waits for the process to complete. Return the value returned by `f` on success. Throw an error if the process failed, or if the process attempts to print anything to stdout.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L406-L413)###
`Base.IOStream`Type
```
IOStream
```
A buffered IO stream wrapping an OS file descriptor. Mostly used to represent files returned by [`open`](#Base.open).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L7-L12)###
`Base.IOBuffer`Type
```
IOBuffer([data::AbstractVector{UInt8}]; keywords...) -> IOBuffer
```
Create an in-memory I/O stream, which may optionally operate on a pre-existing array.
It may take optional keyword arguments:
* `read`, `write`, `append`: restricts operations to the buffer; see `open` for details.
* `truncate`: truncates the buffer size to zero length.
* `maxsize`: specifies a size beyond which the buffer may not be grown.
* `sizehint`: suggests a capacity of the buffer (`data` must implement `sizehint!(data, size)`).
When `data` is not given, the buffer will be both readable and writable by default.
**Examples**
```
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56
julia> String(take!(io))
"JuliaLang is a GitHub organization. It has many members."
julia> io = IOBuffer(b"JuliaLang is a GitHub organization.")
IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=35, maxsize=Inf, ptr=1, mark=-1)
julia> read(io, String)
"JuliaLang is a GitHub organization."
julia> write(io, "This isn't writable.")
ERROR: ArgumentError: ensureroom failed, IOBuffer is not writeable
julia> io = IOBuffer(UInt8[], read=true, write=true, maxsize=34)
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=34, ptr=1, mark=-1)
julia> write(io, "JuliaLang is a GitHub organization.")
34
julia> String(take!(io))
"JuliaLang is a GitHub organization"
julia> length(read(IOBuffer(b"data", read=true, truncate=false)))
4
julia> length(read(IOBuffer(b"data", read=true, truncate=true)))
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iobuffer.jl#L35-L82)
```
IOBuffer(string::String)
```
Create a read-only `IOBuffer` on the data underlying the given string.
**Examples**
```
julia> io = IOBuffer("Haho");
julia> String(take!(io))
"Haho"
julia> String(take!(io))
"Haho"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L288-L303)###
`Base.take!`Method
```
take!(b::IOBuffer)
```
Obtain the contents of an `IOBuffer` as an array. Afterwards, the `IOBuffer` is reset to its initial state.
**Examples**
```
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56
julia> String(take!(io))
"JuliaLang is a GitHub organization. It has many members."
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iobuffer.jl#L359-L374)###
`Base.fdio`Function
```
fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream
```
Create an [`IOStream`](#Base.IOStream) object from an integer file descriptor. If `own` is `true`, closing this object will close the underlying descriptor. By default, an `IOStream` is closed when it is garbage collected. `name` allows you to associate the descriptor with a named file.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L238-L244)###
`Base.flush`Function
```
flush(stream)
```
Commit all currently buffered writes to the given stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L87-L91)###
`Base.close`Function
```
close(stream)
```
Close an I/O stream. Performs a [`flush`](#Base.flush) first.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L57-L61)###
`Base.closewrite`Function
```
closewrite(stream)
```
Shutdown the write half of a full-duplex I/O stream. Performs a [`flush`](#Base.flush) first. Notify the other end that no more data will be written to the underlying file. This is not supported by all IO types.
**Examples**
```
julia> io = Base.BufferStream(); # this never blocks, so we can read and write on the same Task
julia> write(io, "request");
julia> # calling `read(io)` here would block forever
julia> closewrite(io);
julia> read(io, String)
"request"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L64-L84)###
`Base.write`Function
```
write(io::IO, x)
write(filename::AbstractString, x)
```
Write the canonical binary representation of a value to the given I/O stream or file. Return the number of bytes written into the stream. See also [`print`](#Base.print) to write a text representation (with an encoding that may depend upon `io`).
The endianness of the written value depends on the endianness of the host system. Convert to/from a fixed endianness when writing/reading (e.g. using [`htol`](#Base.htol) and [`ltoh`](#Base.ltoh)) to get results that are consistent across platforms.
You can write multiple values with the same `write` call. i.e. the following are equivalent:
```
write(io, x, y...)
write(io, x) + write(io, y...)
```
**Examples**
Consistent serialization:
```
julia> fname = tempname(); # random temporary filename
julia> open(fname,"w") do f
# Make sure we write 64bit integer in little-endian byte order
write(f,htol(Int64(42)))
end
8
julia> open(fname,"r") do f
# Convert back to host byte order and host integer type
Int(ltoh(read(f,Int64)))
end
42
```
Merging write calls:
```
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56
julia> String(take!(io))
"JuliaLang is a GitHub organization. It has many members."
julia> write(io, "Sometimes those members") + write(io, " write documentation.")
44
julia> String(take!(io))
"Sometimes those members write documentation."
```
User-defined plain-data types without `write` methods can be written when wrapped in a `Ref`:
```
julia> struct MyStruct; x::Float64; end
julia> io = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)
julia> write(io, Ref(MyStruct(42.0)))
8
julia> seekstart(io); read!(io, Ref(MyStruct(NaN)))
Base.RefValue{MyStruct}(MyStruct(42.0))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L210-L274)###
`Base.read`Function
```
read(io::IO, T)
```
Read a single value of type `T` from `io`, in canonical binary representation.
Note that Julia does not convert the endianness for you. Use [`ntoh`](#Base.ntoh) or [`ltoh`](#Base.ltoh) for this purpose.
```
read(io::IO, String)
```
Read the entirety of `io`, as a `String` (see also [`readchomp`](#Base.readchomp)).
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization");
julia> read(io, Char)
'J': ASCII/Unicode U+004A (category Lu: Letter, uppercase)
julia> io = IOBuffer("JuliaLang is a GitHub organization");
julia> read(io, String)
"JuliaLang is a GitHub organization"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L183-L207)
```
read(filename::AbstractString, args...)
```
Open a file and read its contents. `args` is passed to `read`: this is equivalent to `open(io->read(io, args...), filename)`.
```
read(filename::AbstractString, String)
```
Read the entire contents of a file as a string.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L450-L459)
```
read(s::IO, nb=typemax(Int))
```
Read at most `nb` bytes from `s`, returning a `Vector{UInt8}` of the bytes read.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L991-L995)
```
read(s::IOStream, nb::Integer; all=true)
```
Read at most `nb` bytes from `s`, returning a `Vector{UInt8}` of the bytes read.
If `all` is `true` (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. If `all` is `false`, at most one `read` call is performed, and the amount of data returned is device-dependent. Note that not all stream types support the `all` option.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L550-L559)
```
read(command::Cmd)
```
Run `command` and return the resulting output as an array of bytes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L441-L445)
```
read(command::Cmd, String)
```
Run `command` and return the resulting output as a `String`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L453-L457)###
`Base.read!`Function
```
read!(stream::IO, array::AbstractArray)
read!(filename::AbstractString, array::AbstractArray)
```
Read binary data from an I/O stream or file, filling in `array`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L464-L469)###
`Base.readbytes!`Function
```
readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))
```
Read at most `nb` bytes from `stream` into `b`, returning the number of bytes read. The size of `b` will be increased if needed (i.e. if `nb` is greater than `length(b)` and enough bytes could be read), but it will never be decreased.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L965-L971)
```
readbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)
```
Read at most `nb` bytes from `stream` into `b`, returning the number of bytes read. The size of `b` will be increased if needed (i.e. if `nb` is greater than `length(b)` and enough bytes could be read), but it will never be decreased.
If `all` is `true` (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. If `all` is `false`, at most one `read` call is performed, and the amount of data returned is device-dependent. Note that not all stream types support the `all` option.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L500-L511)###
`Base.unsafe_read`Function
```
unsafe_read(io::IO, ref, nbytes::UInt)
```
Copy `nbytes` from the `IO` stream object into `ref` (converted to a pointer).
It is recommended that subtypes `T<:IO` override the following method signature to provide more efficient implementations: `unsafe_read(s::T, p::Ptr{UInt8}, n::UInt)`
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L297-L305)###
`Base.unsafe_write`Function
```
unsafe_write(io::IO, ref, nbytes::UInt)
```
Copy `nbytes` from `ref` (converted to a pointer) into the `IO` object.
It is recommended that subtypes `T<:IO` override the following method signature to provide more efficient implementations: `unsafe_write(s::T, p::Ptr{UInt8}, n::UInt)`
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L280-L288)###
`Base.readeach`Function
```
readeach(io::IO, T)
```
Return an iterable object yielding [`read(io, T)`](#Base.read).
See also [`skipchars`](#Base.skipchars), [`eachline`](#Base.eachline), [`readuntil`](#Base.readuntil).
`readeach` requires Julia 1.6 or later.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization.\n It has many members.\n");
julia> for c in readeach(io, Char)
c == '\n' && break
print(c)
end
JuliaLang is a GitHub organization.
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1185-L1205)###
`Base.peek`Function
```
peek(stream[, T=UInt8])
```
Read and return a value of type `T` from a stream without advancing the current position in the stream.
**Examples**
```
julia> b = IOBuffer("julia");
julia> peek(b)
0x6a
julia> position(b)
0
julia> peek(b, Char)
'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)
```
The method which accepts a type requires Julia 1.5 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L845-L868)###
`Base.position`Function
```
position(s)
```
Get the current position of a stream.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> seek(io, 5);
julia> position(io)
5
julia> skip(io, 10);
julia> position(io)
15
julia> seekend(io);
julia> position(io)
35
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L191-L215)###
`Base.seek`Function
```
seek(s, pos)
```
Seek a stream to the given position.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> seek(io, 5);
julia> read(io, Char)
'L': ASCII/Unicode U+004C (category Lu: Letter, uppercase)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L112-L126)###
`Base.seekstart`Function
```
seekstart(s)
```
Seek a stream to its beginning.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> seek(io, 5);
julia> read(io, Char)
'L': ASCII/Unicode U+004C (category Lu: Letter, uppercase)
julia> seekstart(io);
julia> read(io, Char)
'J': ASCII/Unicode U+004A (category Lu: Letter, uppercase)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L134-L153)###
`Base.seekend`Function
```
seekend(s)
```
Seek a stream to its end.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L156-L160)###
`Base.skip`Function
```
skip(s, offset)
```
Seek a stream relative to the current position.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> seek(io, 5);
julia> skip(io, 10);
julia> read(io, Char)
'G': ASCII/Unicode U+0047 (category Lu: Letter, uppercase)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L167-L183)###
`Base.mark`Function
```
mark(s::IO)
```
Add a mark at the current position of stream `s`. Return the marked position.
See also [`unmark`](#Base.unmark), [`reset`](#Base.reset-Tuple%7BIO%7D), [`ismarked`](#Base.ismarked).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1222-L1228)###
`Base.unmark`Function
```
unmark(s::IO)
```
Remove a mark from stream `s`. Return `true` if the stream was marked, `false` otherwise.
See also [`mark`](#Base.mark), [`reset`](#Base.reset-Tuple%7BIO%7D), [`ismarked`](#Base.ismarked).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1233-L1239)###
`Base.reset`Method
```
reset(s::IO)
```
Reset a stream `s` to a previously marked position, and remove the mark. Return the previously marked position. Throw an error if the stream is not marked.
See also [`mark`](#Base.mark), [`unmark`](#Base.unmark), [`ismarked`](#Base.ismarked).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1246-L1253)###
`Base.ismarked`Function
```
ismarked(s::IO)
```
Return `true` if stream `s` is marked.
See also [`mark`](#Base.mark), [`unmark`](#Base.unmark), [`reset`](#Base.reset-Tuple%7BIO%7D).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1262-L1268)###
`Base.eof`Function
```
eof(stream) -> Bool
```
Test whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this function will block to wait for more data if necessary, and then return `false`. Therefore it is always safe to read one byte after seeing `eof` return `false`. `eof` will return `false` as long as buffered data is still available, even if the remote end of a connection is closed.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L168-L176)###
`Base.isreadonly`Function
```
isreadonly(io) -> Bool
```
Determine whether a stream is read-only.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization");
julia> isreadonly(io)
true
julia> io = IOBuffer();
julia> isreadonly(io)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L650-L667)###
`Base.iswritable`Function
```
iswritable(io) -> Bool
```
Return `false` if the specified IO object is not writable.
**Examples**
```
julia> open("myfile.txt", "w") do io
print(io, "Hello world!");
iswritable(io)
end
true
julia> open("myfile.txt", "r") do io
iswritable(io)
end
false
julia> rm("myfile.txt")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L145-L165)###
`Base.isreadable`Function
```
isreadable(io) -> Bool
```
Return `false` if the specified IO object is not readable.
**Examples**
```
julia> open("myfile.txt", "w") do io
print(io, "Hello world!");
isreadable(io)
end
false
julia> open("myfile.txt", "r") do io
isreadable(io)
end
true
julia> rm("myfile.txt")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L122-L142)###
`Base.isopen`Function
```
isopen(object) -> Bool
```
Determine whether an object - such as a stream or timer – is not yet closed. Once an object is closed, it will never produce a new event. However, since a closed stream may still have data to read in its buffer, use [`eof`](#Base.eof) to check for the ability to read data. Use the `FileWatching` package to be notified when a stream might be writable or readable.
**Examples**
```
julia> io = open("my_file.txt", "w+");
julia> isopen(io)
true
julia> close(io)
julia> isopen(io)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L33-L54)###
`Base.fd`Function
```
fd(stream)
```
Return the file descriptor backing the stream or file. Note that this function only applies to synchronous `File`'s and `IOStream`'s not to any of the asynchronous streams.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L49-L54)###
`Base.redirect_stdio`Function
```
redirect_stdio(;stdin=stdin, stderr=stderr, stdout=stdout)
```
Redirect a subset of the streams `stdin`, `stderr`, `stdout`. Each argument must be an `IOStream`, `TTY`, `Pipe`, socket, or `devnull`.
`redirect_stdio` requires Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1307-L1315)
```
redirect_stdio(f; stdin=nothing, stderr=nothing, stdout=nothing)
```
Redirect a subset of the streams `stdin`, `stderr`, `stdout`, call `f()` and restore each stream.
Possible values for each stream are:
* `nothing` indicating the stream should not be redirected.
* `path::AbstractString` redirecting the stream to the file at `path`.
* `io` an `IOStream`, `TTY`, `Pipe`, socket, or `devnull`.
**Examples**
```
julia> redirect_stdio(stdout="stdout.txt", stderr="stderr.txt") do
print("hello stdout")
print(stderr, "hello stderr")
end
julia> read("stdout.txt", String)
"hello stdout"
julia> read("stderr.txt", String)
"hello stderr"
```
**Edge cases**
It is possible to pass the same argument to `stdout` and `stderr`:
```
julia> redirect_stdio(stdout="log.txt", stderr="log.txt", stdin=devnull) do
...
end
```
However it is not supported to pass two distinct descriptors of the same file.
```
julia> io1 = open("same/path", "w")
julia> io2 = open("same/path", "w")
julia> redirect_stdio(f, stdout=io1, stderr=io2) # not suppored
```
Also the `stdin` argument may not be the same descriptor as `stdout` or `stderr`.
```
julia> io = open(...)
julia> redirect_stdio(f, stdout=io, stdin=io) # not supported
```
`redirect_stdio` requires Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1322-L1373)###
`Base.redirect_stdout`Function
```
redirect_stdout([stream]) -> stream
```
Create a pipe to which all C and Julia level [`stdout`](#Base.stdout) output will be redirected. Return a stream representing the pipe ends. Data written to [`stdout`](#Base.stdout) may now be read from the `rd` end of the pipe.
`stream` must be a compatible objects, such as an `IOStream`, `TTY`, `Pipe`, socket, or `devnull`.
See also [`redirect_stdio`](#Base.redirect_stdio).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1264-L1277)###
`Base.redirect_stdout`Method
```
redirect_stdout(f::Function, stream)
```
Run the function `f` while redirecting [`stdout`](#Base.stdout) to `stream`. Upon completion, [`stdout`](#Base.stdout) is restored to its prior setting.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1434-L1439)###
`Base.redirect_stderr`Function
```
redirect_stderr([stream]) -> stream
```
Like [`redirect_stdout`](#Base.redirect_stdout), but for [`stderr`](#Base.stderr).
`stream` must be a compatible objects, such as an `IOStream`, `TTY`, `Pipe`, socket, or `devnull`.
See also [`redirect_stdio`](#Base.redirect_stdio).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1280-L1290)###
`Base.redirect_stderr`Method
```
redirect_stderr(f::Function, stream)
```
Run the function `f` while redirecting [`stderr`](#Base.stderr) to `stream`. Upon completion, [`stderr`](#Base.stderr) is restored to its prior setting.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1442-L1447)###
`Base.redirect_stdin`Function
```
redirect_stdin([stream]) -> stream
```
Like [`redirect_stdout`](#Base.redirect_stdout), but for [`stdin`](#Base.stdin). Note that the direction of the stream is reversed.
`stream` must be a compatible objects, such as an `IOStream`, `TTY`, `Pipe`, socket, or `devnull`.
See also [`redirect_stdio`](#Base.redirect_stdio).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1293-L1304)###
`Base.redirect_stdin`Method
```
redirect_stdin(f::Function, stream)
```
Run the function `f` while redirecting [`stdin`](#Base.stdin) to `stream`. Upon completion, [`stdin`](#Base.stdin) is restored to its prior setting.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L1450-L1455)###
`Base.readchomp`Function
```
readchomp(x)
```
Read the entirety of `x` as a string and remove a single trailing newline if there is one. Equivalent to `chomp(read(x, String))`.
**Examples**
```
julia> open("my_file.txt", "w") do io
write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
end;
julia> readchomp("my_file.txt")
"JuliaLang is a GitHub organization.\nIt has many members."
julia> rm("my_file.txt");
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L943-L960)###
`Base.truncate`Function
```
truncate(file, n)
```
Resize the file or buffer given by the first argument to exactly `n` bytes, filling previously unallocated space with '\0' if the file or buffer is grown.
**Examples**
```
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.")
35
julia> truncate(io, 15)
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=15, maxsize=Inf, ptr=16, mark=-1)
julia> String(take!(io))
"JuliaLang is a "
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.");
julia> truncate(io, 40);
julia> String(take!(io))
"JuliaLang is a GitHub organization.\0\0\0\0\0"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iostream.jl#L77-L105)###
`Base.skipchars`Function
```
skipchars(predicate, io::IO; linecomment=nothing)
```
Advance the stream `io` such that the next-read character will be the first remaining for which `predicate` returns `false`. If the keyword argument `linecomment` is specified, all characters from that character until the start of the next line are ignored.
**Examples**
```
julia> buf = IOBuffer(" text")
IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=8, maxsize=Inf, ptr=1, mark=-1)
julia> skipchars(isspace, buf)
IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=8, maxsize=Inf, ptr=5, mark=-1)
julia> String(readavailable(buf))
"text"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1276-L1294)###
`Base.countlines`Function
```
countlines(io::IO; eol::AbstractChar = '\n')
```
Read `io` until the end of the stream/file and count the number of lines. To specify a file pass the filename as the first argument. EOL markers other than `'\n'` are supported by passing them as the second argument. The last non-empty line of `io` is counted even if it does not end with the EOL, matching the length returned by [`eachline`](#Base.eachline) and [`readlines`](#Base.readlines).
To count lines of a `String`, `countlines(IOBuffer(str))` can be used.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization.\n");
julia> countlines(io)
1
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> countlines(io)
1
julia> eof(io) # counting lines moves the file pointer
true
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> countlines(io, eol = '.')
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1307-L1337)###
`Base.PipeBuffer`Function
```
PipeBuffer(data::Vector{UInt8}=UInt8[]; maxsize::Integer = typemax(Int))
```
An [`IOBuffer`](#Base.IOBuffer) that allows reading and performs writes by appending. Seeking and truncating are not supported. See [`IOBuffer`](#Base.IOBuffer) for the available constructors. If `data` is given, creates a `PipeBuffer` to operate on a data vector, optionally specifying a size beyond which the underlying `Array` may not be grown.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iobuffer.jl#L127-L135)###
`Base.readavailable`Function
```
readavailable(stream)
```
Read available buffered data from a stream. Actual I/O is performed only if no data has already been buffered. The result is a `Vector{UInt8}`.
The amount of data returned is implementation-dependent; for example it can depend on the internal choice of buffer size. Other functions such as [`read`](#Base.read) should generally be used instead.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L109-L119)###
`Base.IOContext`Type
```
IOContext
```
`IOContext` provides a mechanism for passing output configuration settings among [`show`](#Base.show-Tuple%7BIO,%20Any%7D) methods.
In short, it is an immutable dictionary that is a subclass of `IO`. It supports standard dictionary operations such as [`getindex`](../collections/index#Base.getindex), and can also be used as an I/O stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L217-L224)###
`Base.IOContext`Method
```
IOContext(io::IO, KV::Pair...)
```
Create an `IOContext` that wraps a given stream, adding the specified `key=>value` pairs to the properties of that stream (note that `io` can itself be an `IOContext`).
* use `(key => value) in io` to see if this particular combination is in the properties set
* use `get(io, key, default)` to retrieve the most recent value for a particular key
The following properties are in common use:
* `:compact`: Boolean specifying that values should be printed more compactly, e.g. that numbers should be printed with fewer digits. This is set when printing array elements. `:compact` output should not contain line breaks.
* `:limit`: Boolean specifying that containers should be truncated, e.g. showing `…` in place of most elements.
* `:displaysize`: A `Tuple{Int,Int}` giving the size in rows and columns to use for text output. This can be used to override the display size for called functions, but to get the size of the screen use the `displaysize` function.
* `:typeinfo`: a `Type` characterizing the information already printed concerning the type of the object about to be displayed. This is mainly useful when displaying a collection of objects of the same type, so that redundant type information can be avoided (e.g. `[Float16(0)]` can be shown as "Float16[0.0]" instead of "Float16[Float16(0.0)]" : while displaying the elements of the array, the `:typeinfo` property will be set to `Float16`).
* `:color`: Boolean specifying whether ANSI color/escape codes are supported/expected. By default, this is determined by whether `io` is a compatible terminal and by any `--color` command-line flag when `julia` was launched.
**Examples**
```
julia> io = IOBuffer();
julia> printstyled(IOContext(io, :color => true), "string", color=:red)
julia> String(take!(io))
"\e[31mstring\e[39m"
julia> printstyled(io, "string", color=:red)
julia> String(take!(io))
"string"
```
```
julia> print(IOContext(stdout, :compact => false), 1.12341234)
1.12341234
julia> print(IOContext(stdout, :compact => true), 1.12341234)
1.12341
```
```
julia> function f(io::IO)
if get(io, :short, false)
print(io, "short")
else
print(io, "loooooong")
end
end
f (generic function with 1 method)
julia> f(stdout)
loooooong
julia> f(IOContext(stdout, :short => true))
short
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L260-L327)###
`Base.IOContext`Method
```
IOContext(io::IO, context::IOContext)
```
Create an `IOContext` that wraps an alternate `IO` but inherits the properties of `context`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L253-L257)
[Text I/O](#Text-I/O)
----------------------
###
`Base.show`Method
```
show([io::IO = stdout], x)
```
Write a text representation of a value `x` to the output stream `io`. New types `T` should overload `show(io::IO, x::T)`. The representation used by `show` generally includes Julia-specific formatting and type information, and should be parseable Julia code when possible.
[`repr`](#Base.repr-Tuple%7BMIME,%20Any%7D) returns the output of `show` as a string.
To customize human-readable text output for objects of type `T`, define `show(io::IO, ::MIME"text/plain", ::T)` instead. Checking the `:compact` [`IOContext`](#Base.IOContext) property of `io` in such methods is recommended, since some containers show their elements by calling this method with `:compact => true`.
See also [`print`](#Base.print), which writes un-decorated representations.
**Examples**
```
julia> show("Hello World!")
"Hello World!"
julia> print("Hello World!")
Hello World!
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L365-L390)###
`Base.summary`Function
```
summary(io::IO, x)
str = summary(x)
```
Print to a stream `io`, or return a string `str`, giving a brief description of a value. By default returns `string(typeof(x))`, e.g. [`Int64`](../numbers/index#Core.Int64).
For arrays, returns a string of size and type info, e.g. `10-element Array{Int64,1}`.
**Examples**
```
julia> summary(1)
"Int64"
julia> summary(zeros(2))
"2-element Vector{Float64}"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L2777-L2795)###
`Base.print`Function
```
print([io::IO], xs...)
```
Write to `io` (or to the default output stream [`stdout`](#Base.stdout) if `io` is not given) a canonical (un-decorated) text representation. The representation used by `print` includes minimal formatting and tries to avoid Julia-specific details.
`print` falls back to calling `show`, so most types should just define `show`. Define `print` if your type has a separate "plain" representation. For example, `show` displays strings with quotes, and `print` displays strings without quotes.
See also [`println`](#Base.println), [`string`](../strings/index#Base.string), [`printstyled`](#Base.printstyled).
**Examples**
```
julia> print("Hello World!")
Hello World!
julia> io = IOBuffer();
julia> print(io, "Hello", ' ', :World!)
julia> String(take!(io))
"Hello World!"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L5-L31)###
`Base.println`Function
```
println([io::IO], xs...)
```
Print (using [`print`](#Base.print)) `xs` to `io` followed by a newline. If `io` is not supplied, prints to the default output stream [`stdout`](#Base.stdout).
See also [`printstyled`](#Base.printstyled) to add colors etc.
**Examples**
```
julia> println("Hello, world")
Hello, world
julia> io = IOBuffer();
julia> println(io, "Hello", ',', " world.")
julia> String(take!(io))
"Hello, world.\n"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L54-L74)###
`Base.printstyled`Function
```
printstyled([io], xs...; bold::Bool=false, underline::Bool=false, blink::Bool=false, reverse::Bool=false, hidden::Bool=false, color::Union{Symbol,Int}=:normal)
```
Print `xs` in a color specified as a symbol or integer, optionally in bold.
Keyword `color` may take any of the values `:normal`, `:default`, `:bold`, `:black`, `:blink`, `:blue`, `:cyan`, `:green`, `:hidden`, `:light_black`, `:light_blue`, `:light_cyan`, `:light_green`, `:light_magenta`, `:light_red`, `:light_white`, `:light_yellow`, `:magenta`, `:nothing`, `:red`, `:reverse`, `:underline`, `:white`, or `:yellow` or an integer between 0 and 255 inclusive. Note that not all terminals support 256 colors.
Keywords `bold=true`, `underline=true`, `blink=true` are self-explanatory. Keyword `reverse=true` prints with foreground and background colors exchanged, and `hidden=true` should be invisibe in the terminal but can still be copied. These properties can be used in any combination.
See also [`print`](#Base.print), [`println`](#Base.println), [`show`](#Base.show-Tuple%7BIO,%20Any%7D).
Keywords except `color` and `bold` were added in Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/util.jl#L112-L129)###
`Base.sprint`Function
```
sprint(f::Function, args...; context=nothing, sizehint=0)
```
Call the given function with an I/O stream and the supplied extra arguments. Everything written to this I/O stream is returned as a string. `context` can be an [`IOContext`](#Base.IOContext) whose properties will be used, a `Pair` specifying a property and its value, or a tuple of `Pair` specifying multiple properties and their values. `sizehint` suggests the capacity of the buffer (in bytes).
The optional keyword argument `context` can be set to a `:key=>value` pair, a tuple of `:key=>value` pairs, or an `IO` or [`IOContext`](#Base.IOContext) object whose attributes are used for the I/O stream passed to `f`. The optional `sizehint` is a suggested size (in bytes) to allocate for the buffer used to write the string.
Passing a tuple to keyword `context` requires Julia 1.7 or later.
**Examples**
```
julia> sprint(show, 66.66666; context=:compact => true)
"66.6667"
julia> sprint(showerror, BoundsError([1], 100))
"BoundsError: attempt to access 1-element Vector{Int64} at index [100]"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/io.jl#L79-L106)###
`Base.showerror`Function
```
showerror(io, e)
```
Show a descriptive representation of an exception object `e`. This method is used to display the exception after a call to [`throw`](../base/index#Core.throw).
**Examples**
```
julia> struct MyException <: Exception
msg::String
end
julia> function Base.showerror(io::IO, err::MyException)
print(io, "MyException: ")
print(io, err.msg)
end
julia> err = MyException("test exception")
MyException("test exception")
julia> sprint(showerror, err)
"MyException: test exception"
julia> throw(MyException("test exception"))
ERROR: MyException: test exception
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/errorshow.jl#L3-L29)###
`Base.dump`Function
```
dump(x; maxdepth=8)
```
Show every part of the representation of a value. The depth of the output is truncated at `maxdepth`.
**Examples**
```
julia> struct MyStruct
x
y
end
julia> x = MyStruct(1, (2,3));
julia> dump(x)
MyStruct
x: Int64 1
y: Tuple{Int64, Int64}
1: Int64 2
2: Int64 3
julia> dump(x; maxdepth = 1)
MyStruct
x: Int64 1
y: Tuple{Int64, Int64}
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L2684-L2711)###
`Base.Meta.@dump`Macro
```
@dump expr
```
Show every part of the representation of the given expression. Equivalent to [`dump(:(expr))`](#Base.dump).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L147-L152)###
`Base.readline`Function
```
readline(io::IO=stdin; keep::Bool=false)
readline(filename::AbstractString; keep::Bool=false)
```
Read a single line of text from the given I/O stream or file (defaults to `stdin`). When reading from a file, the text is assumed to be encoded in UTF-8. Lines in the input end with `'\n'` or `"\r\n"` or the end of an input stream. When `keep` is false (as it is by default), these trailing newline characters are removed from the line before it is returned. When `keep` is true, they are returned as part of the line.
**Examples**
```
julia> open("my_file.txt", "w") do io
write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
end
57
julia> readline("my_file.txt")
"JuliaLang is a GitHub organization."
julia> readline("my_file.txt", keep=true)
"JuliaLang is a GitHub organization.\n"
julia> rm("my_file.txt")
```
```
julia> print("Enter your name: ")
Enter your name:
julia> your_name = readline()
Logan
"Logan"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L501-L535)###
`Base.readuntil`Function
```
readuntil(stream::IO, delim; keep::Bool = false)
readuntil(filename::AbstractString, delim; keep::Bool = false)
```
Read a string from an I/O stream or a file, up to the given delimiter. The delimiter can be a `UInt8`, `AbstractChar`, string, or vector. Keyword argument `keep` controls whether the delimiter is included in the result. The text is assumed to be encoded in UTF-8.
**Examples**
```
julia> open("my_file.txt", "w") do io
write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
end
57
julia> readuntil("my_file.txt", 'L')
"Julia"
julia> readuntil("my_file.txt", '.', keep = true)
"JuliaLang is a GitHub organization."
julia> rm("my_file.txt")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L474-L498)###
`Base.readlines`Function
```
readlines(io::IO=stdin; keep::Bool=false)
readlines(filename::AbstractString; keep::Bool=false)
```
Read all lines of an I/O stream or a file as a vector of strings. Behavior is equivalent to saving the result of reading [`readline`](#Base.readline) repeatedly with the same arguments and saving the resulting lines as a vector of strings. See also [`eachline`](#Base.eachline) to iterate over the lines without reading them all at once.
**Examples**
```
julia> open("my_file.txt", "w") do io
write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
end
57
julia> readlines("my_file.txt")
2-element Vector{String}:
"JuliaLang is a GitHub organization."
"It has many members."
julia> readlines("my_file.txt", keep=true)
2-element Vector{String}:
"JuliaLang is a GitHub organization.\n"
"It has many members.\n"
julia> rm("my_file.txt")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L554-L582)###
`Base.eachline`Function
```
eachline(io::IO=stdin; keep::Bool=false)
eachline(filename::AbstractString; keep::Bool=false)
```
Create an iterable `EachLine` object that will yield each line from an I/O stream or a file. Iteration calls [`readline`](#Base.readline) on the stream argument repeatedly with `keep` passed through, determining whether trailing end-of-line characters are retained. When called with a file name, the file is opened once at the beginning of iteration and closed at the end. If iteration is interrupted, the file will be closed when the `EachLine` object is garbage collected.
To iterate over each line of a `String`, `eachline(IOBuffer(str))` can be used.
[`Iterators.reverse`](../iterators/index#Base.Iterators.reverse) can be used on an `EachLine` object to read the lines in reverse order (for files, buffers, and other I/O streams supporting [`seek`](#Base.seek)), and [`first`](../collections/index#Base.first) or [`last`](../collections/index#Base.last) can be used to extract the initial or final lines, respectively.
**Examples**
```
julia> open("my_file.txt", "w") do io
write(io, "JuliaLang is a GitHub organization.\n It has many members.\n");
end;
julia> for line in eachline("my_file.txt")
print(line)
end
JuliaLang is a GitHub organization. It has many members.
julia> rm("my_file.txt");
```
Julia 1.8 is required to use `Iterators.reverse` or `last` with `eachline` iterators.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L1017-L1051)###
`Base.displaysize`Function
```
displaysize([io::IO]) -> (lines, columns)
```
Return the nominal size of the screen that may be used for rendering output to this `IO` object. If no input is provided, the environment variables `LINES` and `COLUMNS` are read. If those are not set, a default size of `(24, 80)` is returned.
**Examples**
```
julia> withenv("LINES" => 30, "COLUMNS" => 100) do
displaysize()
end
(30, 100)
```
To get your TTY size,
```
julia> displaysize(stdout)
(34, 147)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stream.jl#L537-L559)
[Multimedia I/O](#Multimedia-I/O)
----------------------------------
Just as text output is performed by [`print`](#Base.print) and user-defined types can indicate their textual representation by overloading [`show`](#Base.show-Tuple%7BIO,%20Any%7D), Julia provides a standardized mechanism for rich multimedia output (such as images, formatted text, or even audio and video), consisting of three parts:
* A function [`display(x)`](#Base.Multimedia.display) to request the richest available multimedia display of a Julia object `x` (with a plain-text fallback).
* Overloading [`show`](#Base.show-Tuple%7BIO,%20Any%7D) allows one to indicate arbitrary multimedia representations (keyed by standard MIME types) of user-defined types.
* Multimedia-capable display backends may be registered by subclassing a generic [`AbstractDisplay`](#Base.Multimedia.AbstractDisplay) type and pushing them onto a stack of display backends via [`pushdisplay`](#Base.Multimedia.pushdisplay).
The base Julia runtime provides only plain-text display, but richer displays may be enabled by loading external modules or by using graphical Julia environments (such as the IPython-based IJulia notebook).
###
`Base.Multimedia.AbstractDisplay`Type
```
AbstractDisplay
```
Abstract supertype for rich display output devices. [`TextDisplay`](#Base.Multimedia.TextDisplay) is a subtype of this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L207-L212)###
`Base.Multimedia.display`Function
```
display(x)
display(d::AbstractDisplay, x)
display(mime, x)
display(d::AbstractDisplay, mime, x)
```
Display `x` using the topmost applicable display in the display stack, typically using the richest supported multimedia output for `x`, with plain-text [`stdout`](#Base.stdout) output as a fallback. The `display(d, x)` variant attempts to display `x` on the given display `d` only, throwing a [`MethodError`](../base/index#Core.MethodError) if `d` cannot display objects of this type.
In general, you cannot assume that `display` output goes to `stdout` (unlike [`print(x)`](#Base.print) or [`show(x)`](#Base.show-Tuple%7BIO,%20Any%7D)). For example, `display(x)` may open up a separate window with an image. `display(x)` means "show `x` in the best way you can for the current output device(s)." If you want REPL-like text output that is guaranteed to go to `stdout`, use [`show(stdout, "text/plain", x)`](#Base.show-Tuple%7BIO,%20Any%7D) instead.
There are also two variants with a `mime` argument (a MIME type string, such as `"image/png"`), which attempt to display `x` using the requested MIME type *only*, throwing a `MethodError` if this type is not supported by either the display(s) or by `x`. With these variants, one can also supply the "raw" data in the requested MIME type by passing `x::AbstractString` (for MIME types with text-based storage, such as text/html or application/postscript) or `x::Vector{UInt8}` (for binary MIME types).
To customize how instances of a type are displayed, overload [`show`](#Base.show-Tuple%7BIO,%20Any%7D) rather than `display`, as explained in the manual section on [custom pretty-printing](../../manual/types/index#man-custom-pretty-printing).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L297-L323)###
`Base.Multimedia.redisplay`Function
```
redisplay(x)
redisplay(d::AbstractDisplay, x)
redisplay(mime, x)
redisplay(d::AbstractDisplay, mime, x)
```
By default, the `redisplay` functions simply call [`display`](#Base.Multimedia.display). However, some display backends may override `redisplay` to modify an existing display of `x` (if any). Using `redisplay` is also a hint to the backend that `x` may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L370-L382)###
`Base.Multimedia.displayable`Function
```
displayable(mime) -> Bool
displayable(d::AbstractDisplay, mime) -> Bool
```
Returns a boolean value indicating whether the given `mime` type (string) is displayable by any of the displays in the current display stack, or specifically by the display `d` in the second variant.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L219-L226)###
`Base.show`Method
```
show(io::IO, mime, x)
```
The [`display`](#Base.Multimedia.display) functions ultimately call `show` in order to write an object `x` as a given `mime` type to a given I/O stream `io` (usually a memory buffer), if possible. In order to provide a rich multimedia representation of a user-defined type `T`, it is only necessary to define a new `show` method for `T`, via: `show(io, ::MIME"mime", x::T) = ...`, where `mime` is a MIME-type string and the function body calls [`write`](#Base.write) (or similar) to write that representation of `x` to `io`. (Note that the `MIME""` notation only supports literal strings; to construct `MIME` types in a more flexible manner use `MIME{Symbol("")}`.)
For example, if you define a `MyImage` type and know how to write it to a PNG file, you could define a function `show(io, ::MIME"image/png", x::MyImage) = ...` to allow your images to be displayed on any PNG-capable `AbstractDisplay` (such as IJulia). As usual, be sure to `import Base.show` in order to add new methods to the built-in Julia function `show`.
Technically, the `MIME"mime"` macro defines a singleton type for the given `mime` string, which allows us to exploit Julia's dispatch mechanisms in determining how to display objects of any given type.
The default MIME type is `MIME"text/plain"`. There is a fallback definition for `text/plain` output that calls `show` with 2 arguments, so it is not always necessary to add a method for that case. If a type benefits from custom human-readable output though, `show(::IO, ::MIME"text/plain", ::T)` should be defined. For example, the `Day` type uses `1 day` as the output for the `text/plain` MIME type, and `Day(1)` as the output of 2-argument `show`.
Container types generally implement 3-argument `show` by calling `show(io, MIME"text/plain"(), x)` for elements `x`, with `:compact => true` set in an [`IOContext`](#Base.IOContext) passed as the first argument.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L79-L109)###
`Base.Multimedia.showable`Function
```
showable(mime, x)
```
Returns a boolean value indicating whether or not the object `x` can be written as the given `mime` type.
(By default, this is determined automatically by the existence of the corresponding [`show`](#Base.show-Tuple%7BIO,%20Any%7D) method for `typeof(x)`. Some types provide custom `showable` methods; for example, if the available MIME formats depend on the *value* of `x`.)
**Examples**
```
julia> showable(MIME("text/plain"), rand(5))
true
julia> showable("image/png", rand(5))
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L57-L75)###
`Base.repr`Method
```
repr(mime, x; context=nothing)
```
Returns an `AbstractString` or `Vector{UInt8}` containing the representation of `x` in the requested `mime` type, as written by [`show(io, mime, x)`](#Base.show-Tuple%7BIO,%20Any%7D) (throwing a [`MethodError`](../base/index#Core.MethodError) if no appropriate `show` is available). An `AbstractString` is returned for MIME types with textual representations (such as `"text/html"` or `"application/postscript"`), whereas binary data is returned as `Vector{UInt8}`. (The function `istextmime(mime)` returns whether or not Julia treats a given `mime` type as text.)
The optional keyword argument `context` can be set to `:key=>value` pair or an `IO` or [`IOContext`](#Base.IOContext) object whose attributes are used for the I/O stream passed to `show`.
As a special case, if `x` is an `AbstractString` (for textual MIME types) or a `Vector{UInt8}` (for binary MIME types), the `repr` function assumes that `x` is already in the requested `mime` format and simply returns `x`. This special case does not apply to the `"text/plain"` MIME type. This is useful so that raw data can be passed to `display(m::MIME, x)`.
In particular, `repr("text/plain", x)` is typically a "pretty-printed" version of `x` designed for human consumption. See also [`repr(x)`](#) to instead return a string corresponding to [`show(x)`](#Base.show-Tuple%7BIO,%20Any%7D) that may be closer to how the value of `x` would be entered in Julia.
**Examples**
```
julia> A = [1 2; 3 4];
julia> repr("text/plain", A)
"2×2 Matrix{Int64}:\n 1 2\n 3 4"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L113-L146)###
`Base.Multimedia.MIME`Type
```
MIME
```
A type representing a standard internet data format. "MIME" stands for "Multipurpose Internet Mail Extensions", since the standard was originally used to describe multimedia attachments to email messages.
A `MIME` object can be passed as the second argument to [`show`](#Base.show-Tuple%7BIO,%20Any%7D) to request output in that format.
**Examples**
```
julia> show(stdout, MIME("text/plain"), "hi")
"hi"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L16-L31)###
`Base.Multimedia.@MIME_str`Macro
```
@MIME_str
```
A convenience macro for writing [`MIME`](#Base.Multimedia.MIME) types, typically used when adding methods to [`show`](#Base.show-Tuple%7BIO,%20Any%7D). For example the syntax `show(io::IO, ::MIME"text/html", x::MyType) = ...` could be used to define how to write an HTML representation of `MyType`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L34-L41)As mentioned above, one can also define new display backends. For example, a module that can display PNG images in a window can register this capability with Julia, so that calling [`display(x)`](#Base.Multimedia.display) on types with PNG representations will automatically display the image using the module's window.
In order to define a new display backend, one should first create a subtype `D` of the abstract class [`AbstractDisplay`](#Base.Multimedia.AbstractDisplay). Then, for each MIME type (`mime` string) that can be displayed on `D`, one should define a function `display(d::D, ::MIME"mime", x) = ...` that displays `x` as that MIME type, usually by calling [`show(io, mime, x)`](#Base.show-Tuple%7BIO,%20Any%7D) or [`repr(io, mime, x)`](#Base.repr-Tuple%7BMIME,%20Any%7D). A [`MethodError`](../base/index#Core.MethodError) should be thrown if `x` cannot be displayed as that MIME type; this is automatic if one calls `show` or `repr`. Finally, one should define a function `display(d::D, x)` that queries [`showable(mime, x)`](#Base.Multimedia.showable) for the `mime` types supported by `D` and displays the "best" one; a `MethodError` should be thrown if no supported MIME types are found for `x`. Similarly, some subtypes may wish to override [`redisplay(d::D, ...)`](#Base.Multimedia.redisplay). (Again, one should `import Base.display` to add new methods to `display`.) The return values of these functions are up to the implementation (since in some cases it may be useful to return a display "handle" of some type). The display functions for `D` can then be called directly, but they can also be invoked automatically from [`display(x)`](#Base.Multimedia.display) simply by pushing a new display onto the display-backend stack with:
###
`Base.Multimedia.pushdisplay`Function
```
pushdisplay(d::AbstractDisplay)
```
Pushes a new display `d` on top of the global display-backend stack. Calling `display(x)` or `display(mime, x)` will display `x` on the topmost compatible backend in the stack (i.e., the topmost backend that does not throw a [`MethodError`](../base/index#Core.MethodError)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L262-L268)###
`Base.Multimedia.popdisplay`Function
```
popdisplay()
popdisplay(d::AbstractDisplay)
```
Pop the topmost backend off of the display-backend stack, or the topmost copy of `d` in the second variant.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L274-L280)###
`Base.Multimedia.TextDisplay`Type
```
TextDisplay(io::IO)
```
Returns a `TextDisplay <: AbstractDisplay`, which displays any object as the text/plain MIME type (by default), writing the text representation to the given I/O stream. (This is how objects are printed in the Julia REPL.)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L232-L238)###
`Base.Multimedia.istextmime`Function
```
istextmime(m::MIME)
```
Determine whether a MIME type is text data. MIME types are assumed to be binary data except for a set of types known to be text data (possibly Unicode).
**Examples**
```
julia> istextmime(MIME("text/plain"))
true
julia> istextmime(MIME("image/png"))
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multimedia.jl#L168-L182)
[Network I/O](#Network-I/O)
----------------------------
###
`Base.bytesavailable`Function
```
bytesavailable(io)
```
Return the number of bytes available for reading before a read from this stream or buffer will block.
**Examples**
```
julia> io = IOBuffer("JuliaLang is a GitHub organization");
julia> bytesavailable(io)
34
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L94-L106)###
`Base.ntoh`Function
```
ntoh(x)
```
Convert the endianness of a value from Network byte order (big-endian) to that used by the Host.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L621-L625)###
`Base.hton`Function
```
hton(x)
```
Convert the endianness of a value from that used by the Host to Network byte order (big-endian).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L628-L632)###
`Base.ltoh`Function
```
ltoh(x)
```
Convert the endianness of a value from Little-endian to that used by the Host.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L635-L639)###
`Base.htol`Function
```
htol(x)
```
Convert the endianness of a value from that used by the Host to Little-endian.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L642-L646)###
`Base.ENDIAN_BOM`Constant
```
ENDIAN_BOM
```
The 32-bit byte-order-mark indicates the native byte order of the host machine. Little-endian machines will contain the value `0x04030201`. Big-endian machines will contain the value `0x01020304`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L612-L618)
| programming_docs |
julia Arrays Arrays
======
[Constructors and Types](#Constructors-and-Types)
--------------------------------------------------
###
`Core.AbstractArray`Type
```
AbstractArray{T,N}
```
Supertype for `N`-dimensional arrays (or array-like types) with elements of type `T`. [`Array`](#Core.Array) and other types are subtypes of this. See the manual section on the [`AbstractArray` interface](../../manual/interfaces/index#man-interface-array).
See also: [`AbstractVector`](#Base.AbstractVector), [`AbstractMatrix`](#Base.AbstractMatrix), [`eltype`](../collections/index#Base.eltype), [`ndims`](#Base.ndims).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L5-L13)###
`Base.AbstractVector`Type
```
AbstractVector{T}
```
Supertype for one-dimensional arrays (or array-like types) with elements of type `T`. Alias for [`AbstractArray{T,1}`](#Core.AbstractArray).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L17-L22)###
`Base.AbstractMatrix`Type
```
AbstractMatrix{T}
```
Supertype for two-dimensional arrays (or array-like types) with elements of type `T`. Alias for [`AbstractArray{T,2}`](#Core.AbstractArray).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L25-L30)###
`Base.AbstractVecOrMat`Type
```
AbstractVecOrMat{T}
```
Union type of [`AbstractVector{T}`](#Base.AbstractVector) and [`AbstractMatrix{T}`](#Base.AbstractMatrix).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L33-L37)###
`Core.Array`Type
```
Array{T,N} <: AbstractArray{T,N}
```
`N`-dimensional dense array with elements of type `T`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L45-L49)###
`Core.Array`Method
```
Array{T}(undef, dims)
Array{T,N}(undef, dims)
```
Construct an uninitialized `N`-dimensional [`Array`](#Core.Array) containing elements of type `T`. `N` can either be supplied explicitly, as in `Array{T,N}(undef, dims)`, or be determined by the length or number of `dims`. `dims` may be a tuple or a series of integer arguments corresponding to the lengths in each dimension. If the rank `N` is supplied explicitly, then it must match the length or number of `dims`. Here [`undef`](#Core.undef) is the [`UndefInitializer`](#Core.UndefInitializer).
**Examples**
```
julia> A = Array{Float64, 2}(undef, 2, 3) # N given explicitly
2×3 Matrix{Float64}:
6.90198e-310 6.90198e-310 6.90198e-310
6.90198e-310 6.90198e-310 0.0
julia> B = Array{Float64}(undef, 4) # N determined by the input
4-element Vector{Float64}:
2.360075077e-314
NaN
2.2671131793e-314
2.299821756e-314
julia> similar(B, 2, 4, 1) # use typeof(B), and the given size
2×4×1 Array{Float64, 3}:
[:, :, 1] =
2.26703e-314 2.26708e-314 0.0 2.80997e-314
0.0 2.26703e-314 2.26708e-314 0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2222-L2254)###
`Core.Array`Method
```
Array{T}(nothing, dims)
Array{T,N}(nothing, dims)
```
Construct an `N`-dimensional [`Array`](#Core.Array) containing elements of type `T`, initialized with [`nothing`](../constants/index#Core.nothing) entries. Element type `T` must be able to hold these values, i.e. `Nothing <: T`.
**Examples**
```
julia> Array{Union{Nothing, String}}(nothing, 2)
2-element Vector{Union{Nothing, String}}:
nothing
nothing
julia> Array{Union{Nothing, Int}}(nothing, 2, 3)
2×3 Matrix{Union{Nothing, Int64}}:
nothing nothing nothing
nothing nothing nothing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2257-L2277)###
`Core.Array`Method
```
Array{T}(missing, dims)
Array{T,N}(missing, dims)
```
Construct an `N`-dimensional [`Array`](#Core.Array) containing elements of type `T`, initialized with [`missing`](../base/index#Base.missing) entries. Element type `T` must be able to hold these values, i.e. `Missing <: T`.
**Examples**
```
julia> Array{Union{Missing, String}}(missing, 2)
2-element Vector{Union{Missing, String}}:
missing
missing
julia> Array{Union{Missing, Int}}(missing, 2, 3)
2×3 Matrix{Union{Missing, Int64}}:
missing missing missing
missing missing missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2281-L2301)###
`Core.UndefInitializer`Type
```
UndefInitializer
```
Singleton type used in array initialization, indicating the array-constructor-caller would like an uninitialized array. See also [`undef`](#Core.undef), an alias for `UndefInitializer()`.
**Examples**
```
julia> Array{Float64, 1}(UndefInitializer(), 3)
3-element Array{Float64, 1}:
2.2752528595e-314
2.202942107e-314
2.275252907e-314
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2304-L2319)###
`Core.undef`Constant
```
undef
```
Alias for `UndefInitializer()`, which constructs an instance of the singleton type [`UndefInitializer`](#Core.UndefInitializer), used in array initialization to indicate the array-constructor-caller would like an uninitialized array.
See also: [`missing`](../base/index#Base.missing), [`similar`](#Base.similar).
**Examples**
```
julia> Array{Float64, 1}(undef, 3)
3-element Vector{Float64}:
2.2752528595e-314
2.202942107e-314
2.275252907e-314
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2322-L2339)###
`Base.Vector`Type
```
Vector{T} <: AbstractVector{T}
```
One-dimensional dense array with elements of type `T`, often used to represent a mathematical vector. Alias for [`Array{T,1}`](#Core.Array).
See also [`empty`](#Base.empty), [`similar`](#Base.similar) and [`zero`](../numbers/index#Base.zero) for creating vectors.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L52-L59)###
`Base.Vector`Method
```
Vector{T}(undef, n)
```
Construct an uninitialized [`Vector{T}`](#Base.Vector) of length `n`.
**Examples**
```
julia> Vector{Float64}(undef, 3)
3-element Array{Float64, 1}:
6.90966e-310
6.90966e-310
6.90966e-310
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2118-L2131)###
`Base.Vector`Method
```
Vector{T}(nothing, m)
```
Construct a [`Vector{T}`](#Base.Vector) of length `m`, initialized with [`nothing`](../constants/index#Core.nothing) entries. Element type `T` must be able to hold these values, i.e. `Nothing <: T`.
**Examples**
```
julia> Vector{Union{Nothing, String}}(nothing, 2)
2-element Vector{Union{Nothing, String}}:
nothing
nothing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2134-L2148)###
`Base.Vector`Method
```
Vector{T}(missing, m)
```
Construct a [`Vector{T}`](#Base.Vector) of length `m`, initialized with [`missing`](../base/index#Base.missing) entries. Element type `T` must be able to hold these values, i.e. `Missing <: T`.
**Examples**
```
julia> Vector{Union{Missing, String}}(missing, 2)
2-element Vector{Union{Missing, String}}:
missing
missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2151-L2165)###
`Base.Matrix`Type
```
Matrix{T} <: AbstractMatrix{T}
```
Two-dimensional dense array with elements of type `T`, often used to represent a mathematical matrix. Alias for [`Array{T,2}`](#Core.Array).
See also [`fill`](#Base.fill), [`zeros`](#Base.zeros), [`undef`](#Core.undef) and [`similar`](#Base.similar) for creating matrices.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L62-L70)###
`Base.Matrix`Method
```
Matrix{T}(undef, m, n)
```
Construct an uninitialized [`Matrix{T}`](#Base.Matrix) of size `m`×`n`.
**Examples**
```
julia> Matrix{Float64}(undef, 2, 3)
2×3 Array{Float64, 2}:
2.36365e-314 2.28473e-314 5.0e-324
2.26704e-314 2.26711e-314 NaN
julia> similar(ans, Int32, 2, 2)
2×2 Matrix{Int32}:
490537216 1277177453
1 1936748399
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2168-L2185)###
`Base.Matrix`Method
```
Matrix{T}(nothing, m, n)
```
Construct a [`Matrix{T}`](#Base.Matrix) of size `m`×`n`, initialized with [`nothing`](../constants/index#Core.nothing) entries. Element type `T` must be able to hold these values, i.e. `Nothing <: T`.
**Examples**
```
julia> Matrix{Union{Nothing, String}}(nothing, 2, 3)
2×3 Matrix{Union{Nothing, String}}:
nothing nothing nothing
nothing nothing nothing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2188-L2202)###
`Base.Matrix`Method
```
Matrix{T}(missing, m, n)
```
Construct a [`Matrix{T}`](#Base.Matrix) of size `m`×`n`, initialized with [`missing`](../base/index#Base.missing) entries. Element type `T` must be able to hold these values, i.e. `Missing <: T`.
**Examples**
```
julia> Matrix{Union{Missing, String}}(missing, 2, 3)
2×3 Matrix{Union{Missing, String}}:
missing missing missing
missing missing missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2205-L2219)###
`Base.VecOrMat`Type
```
VecOrMat{T}
```
Union type of [`Vector{T}`](#Base.Vector) and [`Matrix{T}`](#Base.Matrix) which allows functions to accept either a Matrix or a Vector.
**Examples**
```
julia> Vector{Float64} <: VecOrMat{Float64}
true
julia> Matrix{Float64} <: VecOrMat{Float64}
true
julia> Array{Float64, 3} <: VecOrMat{Float64}
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L73-L89)###
`Core.DenseArray`Type
```
DenseArray{T, N} <: AbstractArray{T,N}
```
`N`-dimensional dense array with elements of type `T`. The elements of a dense array are stored contiguously in memory.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L92-L97)###
`Base.DenseVector`Type
```
DenseVector{T}
```
One-dimensional [`DenseArray`](#Core.DenseArray) with elements of type `T`. Alias for `DenseArray{T,1}`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L100-L104)###
`Base.DenseMatrix`Type
```
DenseMatrix{T}
```
Two-dimensional [`DenseArray`](#Core.DenseArray) with elements of type `T`. Alias for `DenseArray{T,2}`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L107-L111)###
`Base.DenseVecOrMat`Type
```
DenseVecOrMat{T}
```
Union type of [`DenseVector{T}`](#Base.DenseVector) and [`DenseMatrix{T}`](#Base.DenseMatrix).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L114-L118)###
`Base.StridedArray`Type
```
StridedArray{T, N}
```
A hard-coded [`Union`](../base/index#Core.Union) of common array types that follow the [strided array interface](../../manual/interfaces/index#man-interface-strided-arrays), with elements of type `T` and `N` dimensions.
If `A` is a `StridedArray`, then its elements are stored in memory with offsets, which may vary between dimensions but are constant within a dimension. For example, `A` could have stride 2 in dimension 1, and stride 3 in dimension 2. Incrementing `A` along dimension `d` jumps in memory by [`strides(A, d)`] slots. Strided arrays are particularly important and useful because they can sometimes be passed directly as pointers to foreign language libraries like BLAS.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2776-L2788)###
`Base.StridedVector`Type
```
StridedVector{T}
```
One dimensional [`StridedArray`](#Base.StridedArray) with elements of type `T`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2791-L2795)###
`Base.StridedMatrix`Type
```
StridedMatrix{T}
```
Two dimensional [`StridedArray`](#Base.StridedArray) with elements of type `T`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2798-L2802)###
`Base.StridedVecOrMat`Type
```
StridedVecOrMat{T}
```
Union type of [`StridedVector`](#Base.StridedVector) and [`StridedMatrix`](#Base.StridedMatrix) with elements of type `T`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2805-L2809)###
`Base.getindex`Method
```
getindex(type[, elements...])
```
Construct a 1-d array of the specified type. This is usually called with the syntax `Type[]`. Element values can be specified using `Type[a,b,c,...]`.
**Examples**
```
julia> Int8[1, 2, 3]
3-element Vector{Int8}:
1
2
3
julia> getindex(Int8, 1, 2, 3)
3-element Vector{Int8}:
1
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L382-L402)###
`Base.zeros`Function
```
zeros([T=Float64,] dims::Tuple)
zeros([T=Float64,] dims...)
```
Create an `Array`, with element type `T`, of all zeros with size specified by `dims`. See also [`fill`](#Base.fill), [`ones`](#Base.ones), [`zero`](../numbers/index#Base.zero).
**Examples**
```
julia> zeros(1)
1-element Vector{Float64}:
0.0
julia> zeros(Int8, 2, 3)
2×3 Matrix{Int8}:
0 0 0
0 0 0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L539-L557)###
`Base.ones`Function
```
ones([T=Float64,] dims::Tuple)
ones([T=Float64,] dims...)
```
Create an `Array`, with element type `T`, of all ones with size specified by `dims`. See also [`fill`](#Base.fill), [`zeros`](#Base.zeros).
**Examples**
```
julia> ones(1,2)
1×2 Matrix{Float64}:
1.0 1.0
julia> ones(ComplexF64, 2, 3)
2×3 Matrix{ComplexF64}:
1.0+0.0im 1.0+0.0im 1.0+0.0im
1.0+0.0im 1.0+0.0im 1.0+0.0im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L560-L578)###
`Base.BitArray`Type
```
BitArray{N} <: AbstractArray{Bool, N}
```
Space-efficient `N`-dimensional boolean array, using just one bit for each boolean value.
`BitArray`s pack up to 64 values into every 8 bytes, resulting in an 8x space efficiency over `Array{Bool, N}` and allowing some operations to work on 64 values at once.
By default, Julia returns `BitArrays` from [broadcasting](../../manual/arrays/index#Broadcasting) operations that generate boolean elements (including dotted-comparisons like `.==`) as well as from the functions [`trues`](#Base.trues) and [`falses`](#Base.falses).
Due to its packed storage format, concurrent access to the elements of a `BitArray` where at least one of them is a write is not thread safe.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L7-L23)###
`Base.BitArray`Method
```
BitArray(undef, dims::Integer...)
BitArray{N}(undef, dims::NTuple{N,Int})
```
Construct an undef [`BitArray`](#Base.BitArray) with the given dimensions. Behaves identically to the [`Array`](#Core.Array) constructor. See [`undef`](#Core.undef).
**Examples**
```
julia> BitArray(undef, 2, 2)
2×2 BitMatrix:
0 0
0 0
julia> BitArray(undef, (3, 1))
3×1 BitMatrix:
0
0
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L48-L68)###
`Base.BitArray`Method
```
BitArray(itr)
```
Construct a [`BitArray`](#Base.BitArray) generated by the given iterable object. The shape is inferred from the `itr` object.
**Examples**
```
julia> BitArray([1 0; 0 1])
2×2 BitMatrix:
1 0
0 1
julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
2×3 BitMatrix:
0 1 0
1 0 0
julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
6-element BitVector:
0
1
0
1
0
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L549-L576)###
`Base.trues`Function
```
trues(dims)
```
Create a `BitArray` with all values set to `true`.
**Examples**
```
julia> trues(2,3)
2×3 BitMatrix:
1 1 1
1 1 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L408-L420)###
`Base.falses`Function
```
falses(dims)
```
Create a `BitArray` with all values set to `false`.
**Examples**
```
julia> falses(2,3)
2×3 BitMatrix:
0 0 0
0 0 0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitarray.jl#L390-L402)###
`Base.fill`Function
```
fill(value, dims::Tuple)
fill(value, dims...)
```
Create an array of size `dims` with every location set to `value`.
For example, `fill(1.0, (5,5))` returns a 5×5 array of floats, with `1.0` in every location of the array.
The dimension lengths `dims` may be specified as either a tuple or a sequence of arguments. An `N`-length tuple or `N` arguments following the `value` specify an `N`-dimensional array. Thus, a common idiom for creating a zero-dimensional array with its only location set to `x` is `fill(x)`.
Every location of the returned array is set to (and is thus [`===`](../base/index#Core.:===) to) the `value` that was passed; this means that if the `value` is itself modified, all elements of the `fill`ed array will reflect that modification because they're *still* that very `value`. This is of no concern with `fill(1.0, (5,5))` as the `value` `1.0` is immutable and cannot itself be modified, but can be unexpected with mutable values like — most commonly — arrays. For example, `fill([], 3)` places *the very same* empty array in all three locations of the returned vector:
```
julia> v = fill([], 3)
3-element Vector{Vector{Any}}:
[]
[]
[]
julia> v[1] === v[2] === v[3]
true
julia> value = v[1]
Any[]
julia> push!(value, 867_5309)
1-element Vector{Any}:
8675309
julia> v
3-element Vector{Vector{Any}}:
[8675309]
[8675309]
[8675309]
```
To create an array of many independent inner arrays, use a [comprehension](../../manual/arrays/index#man-comprehensions) instead. This creates a new and distinct array on each iteration of the loop:
```
julia> v2 = [[] for _ in 1:3]
3-element Vector{Vector{Any}}:
[]
[]
[]
julia> v2[1] === v2[2] === v2[3]
false
julia> push!(v2[1], 8675309)
1-element Vector{Any}:
8675309
julia> v2
3-element Vector{Vector{Any}}:
[8675309]
[]
[]
```
See also: [`fill!`](#Base.fill!), [`zeros`](#Base.zeros), [`ones`](#Base.ones), [`similar`](#Base.similar).
**Examples**
```
julia> fill(1.0, (2,3))
2×3 Matrix{Float64}:
1.0 1.0 1.0
1.0 1.0 1.0
julia> fill(42)
0-dimensional Array{Int64, 0}:
42
julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector
2-element Vector{Vector{Float64}}:
[0.0, 0.0]
[0.0, 0.0]
julia> A[1][1] = 42; # modifies the filled value to be [42.0, 0.0]
julia> A # both A[1] and A[2] are the very same vector
2-element Vector{Vector{Float64}}:
[42.0, 0.0]
[42.0, 0.0]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L436-L531)###
`Base.fill!`Function
```
fill!(A, x)
```
Fill array `A` with the value `x`. If `x` is an object reference, all elements will refer to the same object. `fill!(A, Foo())` will return `A` filled with the result of evaluating `Foo()` once.
**Examples**
```
julia> A = zeros(2,3)
2×3 Matrix{Float64}:
0.0 0.0 0.0
0.0 0.0 0.0
julia> fill!(A, 2.)
2×3 Matrix{Float64}:
2.0 2.0 2.0
2.0 2.0 2.0
julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(undef, 3), a); a[1] = 2; A
3-element Vector{Vector{Int64}}:
[2, 1, 1]
[2, 1, 1]
[2, 1, 1]
julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(undef, 3), f())
3-element Vector{Int64}:
1
1
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1065-L1096)###
`Base.empty`Function
```
empty(x::Tuple)
```
Returns an empty tuple, `()`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/tuple.jl#L548-L552)
```
empty(v::AbstractVector, [eltype])
```
Create an empty vector similar to `v`, optionally changing the `eltype`.
See also: [`empty!`](../collections/index#Base.empty!), [`isempty`](../collections/index#Base.isempty), [`isassigned`](#Base.isassigned).
**Examples**
```
julia> empty([1.0, 2.0, 3.0])
Float64[]
julia> empty([1.0, 2.0, 3.0], String)
String[]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L843-L859)
```
empty(a::AbstractDict, [index_type=keytype(a)], [value_type=valtype(a)])
```
Create an empty `AbstractDict` container which can accept indices of type `index_type` and values of type `value_type`. The second and third arguments are optional and default to the input's `keytype` and `valtype`, respectively. (If only one of the two types is specified, it is assumed to be the `value_type`, and the `index_type` we default to `keytype(a)`).
Custom `AbstractDict` subtypes may choose which specific dictionary type is best suited to return for the given index and value types, by specializing on the three-argument signature. The default is to return an empty `Dict`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L176-L187)###
`Base.similar`Function
```
similar(array, [element_type=eltype(array)], [dims=size(array)])
```
Create an uninitialized mutable array with the given element type and size, based upon the given source array. The second and third arguments are both optional, defaulting to the given array's `eltype` and `size`. The dimensions may be specified either as a single tuple argument or as a series of integer arguments.
Custom AbstractArray subtypes may choose which specific array type is best-suited to return for the given element type and dimensionality. If they do not specialize this method, the default is an `Array{element_type}(undef, dims...)`.
For example, `similar(1:10, 1, 4)` returns an uninitialized `Array{Int,2}` since ranges are neither mutable nor support 2 dimensions:
```
julia> similar(1:10, 1, 4)
1×4 Matrix{Int64}:
4419743872 4374413872 4419743888 0
```
Conversely, `similar(trues(10,10), 2)` returns an uninitialized `BitVector` with two elements since `BitArray`s are both mutable and can support 1-dimensional arrays:
```
julia> similar(trues(10,10), 2)
2-element BitVector:
0
0
```
Since `BitArray`s can only store elements of type [`Bool`](../numbers/index#Core.Bool), however, if you request a different element type it will create a regular `Array` instead:
```
julia> similar(falses(10), Float64, 2, 4)
2×4 Matrix{Float64}:
2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314
2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314
```
See also: [`undef`](#Core.undef), [`isassigned`](#Base.isassigned).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L750-L792)
```
similar(storagetype, axes)
```
Create an uninitialized mutable array analogous to that specified by `storagetype`, but with `axes` specified by the last argument.
**Examples**:
```
similar(Array{Int}, axes(A))
```
creates an array that "acts like" an `Array{Int}` (and might indeed be backed by one), but which is indexed identically to `A`. If `A` has conventional indexing, this will be identical to `Array{Int}(undef, size(A))`, but if `A` has unconventional indexing then the indices of the result will match `A`.
```
similar(BitArray, (axes(A, 2),))
```
would create a 1-dimensional logical array whose indices match those of the columns of `A`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L817-L838)
[Basic functions](#Basic-functions)
------------------------------------
###
`Base.ndims`Function
```
ndims(A::AbstractArray) -> Integer
```
Return the number of dimensions of `A`.
See also: [`size`](#Base.size), [`axes`](#Base.axes-Tuple%7BAny%7D).
**Examples**
```
julia> A = fill(1, (3,4,5));
julia> ndims(A)
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L224-L238)###
`Base.size`Function
```
size(A::AbstractArray, [dim])
```
Return a tuple containing the dimensions of `A`. Optionally you can specify a dimension to just get the length of that dimension.
Note that `size` may not be defined for arrays with non-standard indices, in which case [`axes`](#Base.axes-Tuple%7BAny%7D) may be useful. See the manual chapter on [arrays with custom indices](https://docs.julialang.org/en/v1.8/devdocs/offset-arrays/#man-custom-indices).
See also: [`length`](../collections/index#Base.length), [`ndims`](#Base.ndims), [`eachindex`](#Base.eachindex), [`sizeof`](#).
**Examples**
```
julia> A = fill(1, (2,3,4));
julia> size(A)
(2, 3, 4)
julia> size(A, 2)
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L20-L41)###
`Base.axes`Method
```
axes(A)
```
Return the tuple of valid indices for array `A`.
See also: [`size`](#Base.size), [`keys`](../collections/index#Base.keys), [`eachindex`](#Base.eachindex).
**Examples**
```
julia> A = fill(1, (5,6,7));
julia> axes(A)
(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L77-L92)###
`Base.axes`Method
```
axes(A, d)
```
Return the valid range of indices for array `A` along dimension `d`.
See also [`size`](#Base.size), and the manual chapter on [arrays with custom indices](https://docs.julialang.org/en/v1.8/devdocs/offset-arrays/#man-custom-indices).
**Examples**
```
julia> A = fill(1, (5,6,7));
julia> axes(A, 2)
Base.OneTo(6)
```
**Usage note**
Each of the indices has to be an `AbstractUnitRange{<:Integer}`, but at the same time can be a type that uses custom indices. So, for example, if you need a subset, use generalized indexing constructs like `begin`/`end` or [`firstindex`](../collections/index#Base.firstindex)/[`lastindex`](../collections/index#Base.lastindex):
```
ix = axes(v, 1)
ix[2:end] # will work for eg Vector, but may fail in general
ix[(begin+1):end] # works for generalized indexes
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L44-L71)###
`Base.length`Method
```
length(A::AbstractArray)
```
Return the number of elements in the array, defaults to `prod(size(A))`.
**Examples**
```
julia> length([1, 2, 3, 4])
4
julia> length([1 2; 3 4])
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L265-L278)###
`Base.keys`Method
```
keys(a::AbstractArray)
```
Return an efficient array describing all valid indices for `a` arranged in the shape of `a` itself.
They keys of 1-dimensional arrays (vectors) are integers, whereas all other N-dimensional arrays use [`CartesianIndex`](#Base.IteratorsMD.CartesianIndex) to describe their locations. Often the special array types [`LinearIndices`](#Base.LinearIndices) and [`CartesianIndices`](#Base.IteratorsMD.CartesianIndices) are used to efficiently represent these arrays of integers and `CartesianIndex`es, respectively.
Note that the `keys` of an array might not be the most efficient index type; for maximum performance use [`eachindex`](#Base.eachindex) instead.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L119-L131)###
`Base.eachindex`Function
```
eachindex(A...)
```
Create an iterable object for visiting each index of an `AbstractArray` `A` in an efficient manner. For array types that have opted into fast linear indexing (like `Array`), this is simply the range `1:length(A)`. For other array types, return a specialized Cartesian range to efficiently index into the array with indices specified for every dimension. For other iterables, including strings and dictionaries, return an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).
If you supply more than one `AbstractArray` argument, `eachindex` will create an iterable object that is fast for all arguments (a [`UnitRange`](../collections/index#Base.UnitRange) if all inputs have fast linear indexing, a [`CartesianIndices`](#Base.IteratorsMD.CartesianIndices) otherwise). If the arrays have different sizes and/or dimensionalities, a `DimensionMismatch` exception will be thrown.
**Examples**
```
julia> A = [1 2; 3 4];
julia> for i in eachindex(A) # linear indexing
println(i)
end
1
2
3
4
julia> for i in eachindex(view(A, 1:2, 1:1)) # Cartesian indexing
println(i)
end
CartesianIndex(1, 1)
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L295-L329)###
`Base.IndexStyle`Type
```
IndexStyle(A)
IndexStyle(typeof(A))
```
`IndexStyle` specifies the "native indexing style" for array `A`. When you define a new [`AbstractArray`](#Core.AbstractArray) type, you can choose to implement either linear indexing (with [`IndexLinear`](#Base.IndexLinear)) or cartesian indexing. If you decide to only implement linear indexing, then you must set this trait for your array type:
```
Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()
```
The default is [`IndexCartesian()`](#Base.IndexCartesian).
Julia's internal indexing machinery will automatically (and invisibly) recompute all indexing operations into the preferred style. This allows users to access elements of your array using any indexing style, even when explicit methods have not been provided.
If you define both styles of indexing for your `AbstractArray`, this trait can be used to select the most performant indexing style. Some methods check this trait on their inputs, and dispatch to different algorithms depending on the most efficient access pattern. In particular, [`eachindex`](#Base.eachindex) creates an iterator whose type depends on the setting of this trait.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L68-L93)###
`Base.IndexLinear`Type
```
IndexLinear()
```
Subtype of [`IndexStyle`](#Base.IndexStyle) used to describe arrays which are optimally indexed by one linear index.
A linear indexing style uses one integer index to describe the position in the array (even if it's a multidimensional array) and column-major ordering is used to efficiently access the elements. This means that requesting [`eachindex`](#Base.eachindex) from an array that is `IndexLinear` will return a simple one-dimensional range, even if it is multidimensional.
A custom array that reports its `IndexStyle` as `IndexLinear` only needs to implement indexing (and indexed assignment) with a single `Int` index; all other indexing expressions — including multidimensional accesses — will be recomputed to the linear index. For example, if `A` were a `2×3` custom matrix with linear indexing, and we referenced `A[1, 3]`, this would be recomputed to the equivalent linear index and call `A[5]` since `2*1 + 3 = 5`.
See also [`IndexCartesian`](#Base.IndexCartesian).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L16-L36)###
`Base.IndexCartesian`Type
```
IndexCartesian()
```
Subtype of [`IndexStyle`](#Base.IndexStyle) used to describe arrays which are optimally indexed by a Cartesian index. This is the default for new custom [`AbstractArray`](#Core.AbstractArray) subtypes.
A Cartesian indexing style uses multiple integer indices to describe the position in a multidimensional array, with exactly one index per dimension. This means that requesting [`eachindex`](#Base.eachindex) from an array that is `IndexCartesian` will return a range of [`CartesianIndices`](#Base.IteratorsMD.CartesianIndices).
A `N`-dimensional custom array that reports its `IndexStyle` as `IndexCartesian` needs to implement indexing (and indexed assignment) with exactly `N` `Int` indices; all other indexing expressions — including linear indexing — will be recomputed to the equivalent Cartesian location. For example, if `A` were a `2×3` custom matrix with cartesian indexing, and we referenced `A[5]`, this would be recomputed to the equivalent Cartesian index and call `A[1, 3]` since `5 = 2*1 + 3`.
It is significantly more expensive to compute Cartesian indices from a linear index than it is to go the other way. The former operation requires division — a very costly operation — whereas the latter only uses multiplication and addition and is essentially free. This asymmetry means it is far more costly to use linear indexing with an `IndexCartesian` array than it is to use Cartesian indexing with an `IndexLinear` array.
See also [`IndexLinear`](#Base.IndexLinear).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L39-L65)###
`Base.conj!`Function
```
conj!(A)
```
Transform an array to its complex conjugate in-place.
See also [`conj`](../math/index#Base.conj).
**Examples**
```
julia> A = [1+im 2-im; 2+2im 3+im]
2×2 Matrix{Complex{Int64}}:
1+1im 2-1im
2+2im 3+1im
julia> conj!(A);
julia> A
2×2 Matrix{Complex{Int64}}:
1-1im 2+1im
2-2im 3-1im
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L98-L119)###
`Base.stride`Function
```
stride(A, k::Integer)
```
Return the distance in memory (in number of elements) between adjacent elements in dimension `k`.
See also: [`strides`](#Base.strides).
**Examples**
```
julia> A = fill(1, (3,4,5));
julia> stride(A,2)
3
julia> stride(A,3)
12
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L528-L545)###
`Base.strides`Function
```
strides(A)
```
Return a tuple of the memory strides in each dimension.
See also: [`stride`](#Base.stride).
**Examples**
```
julia> A = fill(1, (3,4,5));
julia> strides(A)
(1, 3, 12)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L511-L525)
[Broadcast and vectorization](#Broadcast-and-vectorization)
------------------------------------------------------------
See also the [dot syntax for vectorizing functions](../../manual/functions/index#man-vectorized); for example, `f.(args...)` implicitly calls `broadcast(f, args...)`. Rather than relying on "vectorized" methods of functions like `sin` to operate on arrays, you should use `sin.(a)` to vectorize via `broadcast`.
###
`Base.Broadcast.broadcast`Function
```
broadcast(f, As...)
```
Broadcast the function `f` over the arrays, tuples, collections, [`Ref`](../c/index#Core.Ref)s and/or scalars `As`.
Broadcasting applies the function `f` over the elements of the container arguments and the scalars themselves in `As`. Singleton and missing dimensions are expanded to match the extents of the other arguments by virtually repeating the value. By default, only a limited number of types are considered scalars, including `Number`s, `String`s, `Symbol`s, `Type`s, `Function`s and some common singletons like [`missing`](../base/index#Base.missing) and [`nothing`](../constants/index#Core.nothing). All other arguments are iterated over or indexed into elementwise.
The resulting container type is established by the following rules:
* If all the arguments are scalars or zero-dimensional arrays, it returns an unwrapped scalar.
* If at least one argument is a tuple and all others are scalars or zero-dimensional arrays, it returns a tuple.
* All other combinations of arguments default to returning an `Array`, but custom container types can define their own implementation and promotion-like rules to customize the result when they appear as arguments.
A special syntax exists for broadcasting: `f.(args...)` is equivalent to `broadcast(f, args...)`, and nested `f.(g.(args...))` calls are fused into a single broadcast loop.
**Examples**
```
julia> A = [1, 2, 3, 4, 5]
5-element Vector{Int64}:
1
2
3
4
5
julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
5×2 Matrix{Int64}:
1 2
3 4
5 6
7 8
9 10
julia> broadcast(+, A, B)
5×2 Matrix{Int64}:
2 3
5 6
8 9
11 12
14 15
julia> parse.(Int, ["1", "2"])
2-element Vector{Int64}:
1
2
julia> abs.((1, -2))
(1, 2)
julia> broadcast(+, 1.0, (0, -2.0))
(1.0, -1.0)
julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
2-element Vector{Vector{Int64}}:
[1, 1]
[2, 2]
julia> string.(("one","two","three","four"), ": ", 1:4)
4-element Vector{String}:
"one: 1"
"two: 2"
"three: 3"
"four: 4"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L722-L797)###
`Base.Broadcast.broadcast!`Function
```
broadcast!(f, dest, As...)
```
Like [`broadcast`](#Base.Broadcast.broadcast), but store the result of `broadcast(f, As...)` in the `dest` array. Note that `dest` is only used to store the result, and does not supply arguments to `f` unless it is also listed in the `As`, as in `broadcast!(f, A, A, B)` to perform `A[:] = broadcast(f, A, B)`.
**Examples**
```
julia> A = [1.0; 0.0]; B = [0.0; 0.0];
julia> broadcast!(+, B, A, (0, -2.0));
julia> B
2-element Vector{Float64}:
1.0
-2.0
julia> A
2-element Vector{Float64}:
1.0
0.0
julia> broadcast!(+, A, A, (0, -2.0));
julia> A
2-element Vector{Float64}:
1.0
-2.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L804-L836)###
`Base.Broadcast.@__dot__`Macro
```
@. expr
```
Convert every function call or operator in `expr` into a "dot call" (e.g. convert `f(x)` to `f.(x)`), and convert every assignment in `expr` to a "dot assignment" (e.g. convert `+=` to `.+=`).
If you want to *avoid* adding dots for selected function calls in `expr`, splice those function calls in with `$`. For example, `@. sqrt(abs($sort(x)))` is equivalent to `sqrt.(abs.(sort(x)))` (no dot for `sort`).
(`@.` is equivalent to a call to `@__dot__`.)
**Examples**
```
julia> x = 1.0:3.0; y = similar(x);
julia> @. y = x + 3 * sin(x)
3-element Vector{Float64}:
3.5244129544236893
4.727892280477045
3.4233600241796016
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L1251-L1275)For specializing broadcast on custom types, see
###
`Base.Broadcast.BroadcastStyle`Type
`BroadcastStyle` is an abstract type and trait-function used to determine behavior of objects under broadcasting. `BroadcastStyle(typeof(x))` returns the style associated with `x`. To customize the broadcasting behavior of a type, one can declare a style by defining a type/method pair
```
struct MyContainerStyle <: BroadcastStyle end
Base.BroadcastStyle(::Type{<:MyContainer}) = MyContainerStyle()
```
One then writes method(s) (at least [`similar`](#Base.similar)) operating on `Broadcasted{MyContainerStyle}`. There are also several pre-defined subtypes of `BroadcastStyle` that you may be able to leverage; see the [Interfaces chapter](../../manual/interfaces/index#man-interfaces-broadcasting) for more information.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L21-L34)###
`Base.Broadcast.AbstractArrayStyle`Type
`Broadcast.AbstractArrayStyle{N} <: BroadcastStyle` is the abstract supertype for any style associated with an `AbstractArray` type. The `N` parameter is the dimensionality, which can be handy for AbstractArray types that only support specific dimensionalities:
```
struct SparseMatrixStyle <: Broadcast.AbstractArrayStyle{2} end
Base.BroadcastStyle(::Type{<:SparseMatrixCSC}) = SparseMatrixStyle()
```
For `AbstractArray` types that support arbitrary dimensionality, `N` can be set to `Any`:
```
struct MyArrayStyle <: Broadcast.AbstractArrayStyle{Any} end
Base.BroadcastStyle(::Type{<:MyArray}) = MyArrayStyle()
```
In cases where you want to be able to mix multiple `AbstractArrayStyle`s and keep track of dimensionality, your style needs to support a [`Val`](../base/index#Base.Val) constructor:
```
struct MyArrayStyleDim{N} <: Broadcast.AbstractArrayStyle{N} end
(::Type{<:MyArrayStyleDim})(::Val{N}) where N = MyArrayStyleDim{N}()
```
Note that if two or more `AbstractArrayStyle` subtypes conflict, broadcasting machinery will fall back to producing `Array`s. If this is undesirable, you may need to define binary [`BroadcastStyle`](#Base.Broadcast.BroadcastStyle) rules to control the output type.
See also [`Broadcast.DefaultArrayStyle`](#Base.Broadcast.DefaultArrayStyle).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L51-L76)###
`Base.Broadcast.ArrayStyle`Type
`Broadcast.ArrayStyle{MyArrayType}()` is a [`BroadcastStyle`](#Base.Broadcast.BroadcastStyle) indicating that an object behaves as an array for broadcasting. It presents a simple way to construct [`Broadcast.AbstractArrayStyle`](#Base.Broadcast.AbstractArrayStyle)s for specific `AbstractArray` container types. Broadcast styles created this way lose track of dimensionality; if keeping track is important for your type, you should create your own custom [`Broadcast.AbstractArrayStyle`](#Base.Broadcast.AbstractArrayStyle).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L79-L85)###
`Base.Broadcast.DefaultArrayStyle`Type
`Broadcast.DefaultArrayStyle{N}()` is a [`BroadcastStyle`](#Base.Broadcast.BroadcastStyle) indicating that an object behaves as an `N`-dimensional array for broadcasting. Specifically, `DefaultArrayStyle` is used for any `AbstractArray` type that hasn't defined a specialized style, and in the absence of overrides from other `broadcast` arguments the resulting output type is `Array`. When there are multiple inputs to `broadcast`, `DefaultArrayStyle` "loses" to any other [`Broadcast.ArrayStyle`](#Base.Broadcast.ArrayStyle).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L89-L96)###
`Base.Broadcast.broadcastable`Function
```
Broadcast.broadcastable(x)
```
Return either `x` or an object like `x` such that it supports [`axes`](#Base.axes-Tuple%7BAny%7D), indexing, and its type supports [`ndims`](#Base.ndims).
If `x` supports iteration, the returned value should have the same `axes` and indexing behaviors as [`collect(x)`](#).
If `x` is not an `AbstractArray` but it supports `axes`, indexing, and its type supports `ndims`, then `broadcastable(::typeof(x))` may be implemented to just return itself. Further, if `x` defines its own [`BroadcastStyle`](#Base.Broadcast.BroadcastStyle), then it must define its `broadcastable` method to return itself for the custom style to have any effect.
**Examples**
```
julia> Broadcast.broadcastable([1,2,3]) # like `identity` since arrays already support axes and indexing
3-element Vector{Int64}:
1
2
3
julia> Broadcast.broadcastable(Int) # Types don't support axes, indexing, or iteration but are commonly used as scalars
Base.RefValue{Type{Int64}}(Int64)
julia> Broadcast.broadcastable("hello") # Strings break convention of matching iteration and act like a scalar instead
Base.RefValue{String}("hello")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L672-L699)###
`Base.Broadcast.combine_axes`Function
```
combine_axes(As...) -> Tuple
```
Determine the result axes for broadcasting across all values in `As`.
```
julia> Broadcast.combine_axes([1], [1 2; 3 4; 5 6])
(Base.OneTo(3), Base.OneTo(2))
julia> Broadcast.combine_axes(1, 1, 1)
()
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L485-L497)###
`Base.Broadcast.combine_styles`Function
```
combine_styles(cs...) -> BroadcastStyle
```
Decides which `BroadcastStyle` to use for any number of value arguments. Uses [`BroadcastStyle`](#Base.Broadcast.BroadcastStyle) to get the style for each argument, and uses [`result_style`](#Base.Broadcast.result_style) to combine styles.
**Examples**
```
julia> Broadcast.combine_styles([1], [1 2; 3 4])
Base.Broadcast.DefaultArrayStyle{2}()
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L418-L431)###
`Base.Broadcast.result_style`Function
```
result_style(s1::BroadcastStyle[, s2::BroadcastStyle]) -> BroadcastStyle
```
Takes one or two `BroadcastStyle`s and combines them using [`BroadcastStyle`](#Base.Broadcast.BroadcastStyle) to determine a common `BroadcastStyle`.
**Examples**
```
julia> Broadcast.result_style(Broadcast.DefaultArrayStyle{0}(), Broadcast.DefaultArrayStyle{3}())
Base.Broadcast.DefaultArrayStyle{3}()
julia> Broadcast.result_style(Broadcast.Unknown(), Broadcast.DefaultArrayStyle{1}())
Base.Broadcast.DefaultArrayStyle{1}()
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L439-L454)
[Indexing and assignment](#Indexing-and-assignment)
----------------------------------------------------
###
`Base.getindex`Method
```
getindex(A, inds...)
```
Return a subset of array `A` as specified by `inds`, where each `ind` may be, for example, an `Int`, an [`AbstractRange`](../collections/index#Base.AbstractRange), or a [`Vector`](#Base.Vector). See the manual section on [array indexing](../../manual/arrays/index#man-array-indexing) for details.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> getindex(A, 1)
1
julia> getindex(A, [2, 1])
2-element Vector{Int64}:
3
1
julia> getindex(A, 2:4)
3-element Vector{Int64}:
3
2
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1209-L1237)###
`Base.setindex!`Method
```
setindex!(A, X, inds...)
A[inds...] = X
```
Store values from array `X` within some subset of `A` as specified by `inds`. The syntax `A[inds...] = X` is equivalent to `(setindex!(A, X, inds...); X)`.
**Examples**
```
julia> A = zeros(2,2);
julia> setindex!(A, [10, 20], [1, 2]);
julia> A[[3, 4]] = [30, 40];
julia> A
2×2 Matrix{Float64}:
10.0 30.0
20.0 40.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1320-L1340)###
`Base.copyto!`Method
```
copyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest
```
Copy the block of `src` in the range of `Rsrc` to the block of `dest` in the range of `Rdest`. The sizes of the two regions must match.
**Examples**
```
julia> A = zeros(5, 5);
julia> B = [1 2; 3 4];
julia> Ainds = CartesianIndices((2:3, 2:3));
julia> Binds = CartesianIndices(B);
julia> copyto!(A, Ainds, B, Binds)
5×5 Matrix{Float64}:
0.0 0.0 0.0 0.0 0.0
0.0 1.0 2.0 0.0 0.0
0.0 3.0 4.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1133-L1157)###
`Base.copy!`Function
```
copy!(dst, src) -> dst
```
In-place [`copy`](../base/index#Base.copy) of `src` into `dst`, discarding any pre-existing elements in `dst`. If `dst` and `src` are of the same type, `dst == src` should hold after the call. If `dst` and `src` are multidimensional arrays, they must have equal [`axes`](#Base.axes-Tuple%7BAny%7D).
See also [`copyto!`](../c/index#Base.copyto!).
This method requires at least Julia 1.1. In Julia 1.0 this method is available from the `Future` standard library as `Future.copy!`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L866-L880)###
`Base.isassigned`Function
```
isassigned(array, i) -> Bool
```
Test whether the given array has a value associated with index `i`. Return `false` if the index is out of bounds, or has an undefined reference.
**Examples**
```
julia> isassigned(rand(3, 3), 5)
true
julia> isassigned(rand(3, 3), 3 * 3 + 1)
false
julia> mutable struct Foo end
julia> v = similar(rand(3), Foo)
3-element Vector{Foo}:
#undef
#undef
#undef
julia> isassigned(v, 1)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L641-L666)###
`Base.Colon`Type
```
Colon()
```
Colons (:) are used to signify indexing entire objects or dimensions at once.
Very few operations are defined on Colons directly; instead they are converted by [`to_indices`](#Base.to_indices) to an internal vector type (`Base.Slice`) to represent the collection of indices they span before being used.
The singleton instance of `Colon` is also a function used to construct ranges; see [`:`](../math/index#Base.::).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L675-L686)###
`Base.IteratorsMD.CartesianIndex`Type
```
CartesianIndex(i, j, k...) -> I
CartesianIndex((i, j, k...)) -> I
```
Create a multidimensional index `I`, which can be used for indexing a multidimensional array `A`. In particular, `A[I]` is equivalent to `A[i,j,k...]`. One can freely mix integer and `CartesianIndex` indices; for example, `A[Ipre, i, Ipost]` (where `Ipre` and `Ipost` are `CartesianIndex` indices and `i` is an `Int`) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality.
A `CartesianIndex` is sometimes produced by [`eachindex`](#Base.eachindex), and always when iterating with an explicit [`CartesianIndices`](#Base.IteratorsMD.CartesianIndices).
**Examples**
```
julia> A = reshape(Vector(1:16), (2, 2, 2, 2))
2×2×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
1 3
2 4
[:, :, 2, 1] =
5 7
6 8
[:, :, 1, 2] =
9 11
10 12
[:, :, 2, 2] =
13 15
14 16
julia> A[CartesianIndex((1, 1, 1, 1))]
1
julia> A[CartesianIndex((1, 1, 1, 2))]
9
julia> A[CartesianIndex((1, 1, 2, 1))]
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L18-L63)###
`Base.IteratorsMD.CartesianIndices`Type
```
CartesianIndices(sz::Dims) -> R
CartesianIndices((istart:[istep:]istop, jstart:[jstep:]jstop, ...)) -> R
```
Define a region `R` spanning a multidimensional rectangular range of integer indices. These are most commonly encountered in the context of iteration, where `for I in R ... end` will return [`CartesianIndex`](#Base.IteratorsMD.CartesianIndex) indices `I` equivalent to the nested loops
```
for j = jstart:jstep:jstop
for i = istart:istep:istop
...
end
end
```
Consequently these can be useful for writing algorithms that work in arbitrary dimensions.
```
CartesianIndices(A::AbstractArray) -> R
```
As a convenience, constructing a `CartesianIndices` from an array makes a range of its indices.
The step range method `CartesianIndices((istart:istep:istop, jstart:[jstep:]jstop, ...))` requires at least Julia 1.6.
**Examples**
```
julia> foreach(println, CartesianIndices((2, 2, 2)))
CartesianIndex(1, 1, 1)
CartesianIndex(2, 1, 1)
CartesianIndex(1, 2, 1)
CartesianIndex(2, 2, 1)
CartesianIndex(1, 1, 2)
CartesianIndex(2, 1, 2)
CartesianIndex(1, 2, 2)
CartesianIndex(2, 2, 2)
julia> CartesianIndices(fill(1, (2,3)))
CartesianIndices((2, 3))
```
**Conversion between linear and cartesian indices**
Linear index to cartesian index conversion exploits the fact that a `CartesianIndices` is an `AbstractArray` and can be indexed linearly:
```
julia> cartesian = CartesianIndices((1:3, 1:2))
CartesianIndices((1:3, 1:2))
julia> cartesian[4]
CartesianIndex(1, 2)
julia> cartesian = CartesianIndices((1:2:5, 1:2))
CartesianIndices((1:2:5, 1:2))
julia> cartesian[2, 2]
CartesianIndex(3, 2)
```
**Broadcasting**
`CartesianIndices` support broadcasting arithmetic (+ and -) with a `CartesianIndex`.
Broadcasting of CartesianIndices requires at least Julia 1.1.
```
julia> CIs = CartesianIndices((2:3, 5:6))
CartesianIndices((2:3, 5:6))
julia> CI = CartesianIndex(3, 4)
CartesianIndex(3, 4)
julia> CIs .+ CI
CartesianIndices((5:6, 9:10))
```
For cartesian to linear index conversion, see [`LinearIndices`](#Base.LinearIndices).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L166-L247)###
`Base.Dims`Type
```
Dims{N}
```
An `NTuple` of `N` `Int`s used to represent the dimensions of an [`AbstractArray`](#Core.AbstractArray).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L3-L8)###
`Base.LinearIndices`Type
```
LinearIndices(A::AbstractArray)
```
Return a `LinearIndices` array with the same shape and [`axes`](#Base.axes-Tuple%7BAny%7D) as `A`, holding the linear index of each entry in `A`. Indexing this array with cartesian indices allows mapping them to linear indices.
For arrays with conventional indexing (indices start at 1), or any multidimensional array, linear indices range from 1 to `length(A)`. However, for `AbstractVector`s linear indices are `axes(A, 1)`, and therefore do not start at 1 for vectors with unconventional indexing.
Calling this function is the "safe" way to write algorithms that exploit linear indexing.
**Examples**
```
julia> A = fill(1, (5,6,7));
julia> b = LinearIndices(A);
julia> extrema(b)
(1, 210)
```
```
LinearIndices(inds::CartesianIndices) -> R
LinearIndices(sz::Dims) -> R
LinearIndices((istart:istop, jstart:jstop, ...)) -> R
```
Return a `LinearIndices` array with the specified shape or [`axes`](#Base.axes-Tuple%7BAny%7D).
**Example**
The main purpose of this constructor is intuitive conversion from cartesian to linear indexing:
```
julia> linear = LinearIndices((1:3, 1:2))
3×2 LinearIndices{2, Tuple{UnitRange{Int64}, UnitRange{Int64}}}:
1 4
2 5
3 6
julia> linear[1,2]
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L401-L447)###
`Base.to_indices`Function
```
to_indices(A, I::Tuple)
```
Convert the tuple `I` to a tuple of indices for use in indexing into array `A`.
The returned tuple must only contain either `Int`s or `AbstractArray`s of scalar indices that are supported by array `A`. It will error upon encountering a novel index type that it does not know how to process.
For simple index types, it defers to the unexported `Base.to_index(A, i)` to process each index `i`. While this internal function is not intended to be called directly, `Base.to_index` may be extended by custom array or index types to provide custom indexing behaviors.
More complicated index types may require more context about the dimension into which they index. To support those cases, `to_indices(A, I)` calls `to_indices(A, axes(A), I)`, which then recursively walks through both the given tuple of indices and the dimensional indices of `A` in tandem. As such, not all index types are guaranteed to propagate to `Base.to_index`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L304-L323)###
`Base.checkbounds`Function
```
checkbounds(Bool, A, I...)
```
Return `true` if the specified indices `I` are in bounds for the given array `A`. Subtypes of `AbstractArray` should specialize this method if they need to provide custom bounds checking behaviors; however, in many cases one can rely on `A`'s indices and [`checkindex`](#Base.checkindex).
See also [`checkindex`](#Base.checkindex).
**Examples**
```
julia> A = rand(3, 3);
julia> checkbounds(Bool, A, 2)
true
julia> checkbounds(Bool, A, 3, 4)
false
julia> checkbounds(Bool, A, 1:3)
true
julia> checkbounds(Bool, A, 1:3, 2:4)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L618-L644)
```
checkbounds(A, I...)
```
Throw an error if the specified indices `I` are not in bounds for the given array `A`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L661-L665)###
`Base.checkindex`Function
```
checkindex(Bool, inds::AbstractUnitRange, index)
```
Return `true` if the given `index` is within the bounds of `inds`. Custom types that would like to behave as indices for all arrays can extend this method in order to provide a specialized bounds checking implementation.
See also [`checkbounds`](#Base.checkbounds).
**Examples**
```
julia> checkindex(Bool, 1:20, 8)
true
julia> checkindex(Bool, 1:20, 21)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L706-L724)###
`Base.elsize`Function
```
elsize(type)
```
Compute the memory stride in bytes between consecutive elements of `eltype` stored inside the given `type`, if the array elements are stored densely with a uniform linear stride.
**Examples**
```
julia> Base.elsize(rand(Float32, 10))
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L209-L221)
[Views (SubArrays and other view types)](#Views-(SubArrays-and-other-view-types))
----------------------------------------------------------------------------------
A “view” is a data structure that acts like an array (it is a subtype of `AbstractArray`), but the underlying data is actually part of another array.
For example, if `x` is an array and `v = @view x[1:10]`, then `v` acts like a 10-element array, but its data is actually accessing the first 10 elements of `x`. Writing to a view, e.g. `v[3] = 2`, writes directly to the underlying array `x` (in this case modifying `x[3]`).
Slicing operations like `x[1:10]` create a copy by default in Julia. `@view x[1:10]` changes it to make a view. The `@views` macro can be used on a whole block of code (e.g. `@views function foo() .... end` or `@views begin ... end`) to change all the slicing operations in that block to use views. Sometimes making a copy of the data is faster and sometimes using a view is faster, as described in the [performance tips](../../manual/performance-tips/index#man-performance-views).
###
`Base.view`Function
```
view(A, inds...)
```
Like [`getindex`](../collections/index#Base.getindex), but returns a lightweight array that lazily references (or is effectively a *view* into) the parent array `A` at the given index or indices `inds` instead of eagerly extracting elements or constructing a copied subset. Calling [`getindex`](../collections/index#Base.getindex) or [`setindex!`](../collections/index#Base.setindex!) on the returned value (often a [`SubArray`](#Base.SubArray)) computes the indices to access or modify the parent array on the fly. The behavior is undefined if the shape of the parent array is changed after `view` is called because there is no bound check for the parent array; e.g., it may cause a segmentation fault.
Some immutable parent arrays (like ranges) may choose to simply recompute a new array in some circumstances instead of returning a `SubArray` if doing so is efficient and provides compatible semantics.
In Julia 1.6 or later, `view` can be called on an `AbstractString`, returning a `SubString`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> b = view(A, :, 1)
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
1
3
julia> fill!(b, 0)
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
0
0
julia> A # Note A has changed even though we modified b
2×2 Matrix{Int64}:
0 2
0 4
julia> view(2:5, 2:3) # returns a range as type is immutable
3:4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/subarray.jl#L128-L173)###
`Base.@view`Macro
```
@view A[inds...]
```
Transform the indexing expression `A[inds...]` into the equivalent [`view`](#Base.view) call.
This can only be applied directly to a single indexing expression and is particularly helpful for expressions that include the special `begin` or `end` indexing syntaxes like `A[begin, 2:end-1]` (as those are not supported by the normal [`view`](#Base.view) function).
Note that `@view` cannot be used as the target of a regular assignment (e.g., `@view(A[1, 2:end]) = ...`), nor would the un-decorated [indexed assignment](../../manual/arrays/index#man-indexed-assignment) (`A[1, 2:end] = ...`) or broadcasted indexed assignment (`A[1, 2:end] .= ...`) make a copy. It can be useful, however, for *updating* broadcasted assignments like `@view(A[1, 2:end]) .+= 1` because this is a simple syntax for `@view(A[1, 2:end]) .= @view(A[1, 2:end]) + 1`, and the indexing expression on the right-hand side would otherwise make a copy without the `@view`.
See also [`@views`](#Base.@views) to switch an entire block of code to use views for non-scalar indexing.
Using `begin` in an indexing expression to refer to the first index requires at least Julia 1.5.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> b = @view A[:, 1]
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
1
3
julia> fill!(b, 0)
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
0
0
julia> A
2×2 Matrix{Int64}:
0 2
0 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/views.jl#L77-L124)###
`Base.@views`Macro
```
@views expression
```
Convert every array-slicing operation in the given expression (which may be a `begin`/`end` block, loop, function, etc.) to return a view. Scalar indices, non-array types, and explicit [`getindex`](../collections/index#Base.getindex) calls (as opposed to `array[...]`) are unaffected.
The `@views` macro only affects `array[...]` expressions that appear explicitly in the given `expression`, not array slicing that occurs in functions called by that code.
Using `begin` in an indexing expression to refer to the first index requires at least Julia 1.5.
**Examples**
```
julia> A = zeros(3, 3);
julia> @views for row in 1:3
b = A[row, :]
b[:] .= row
end
julia> A
3×3 Matrix{Float64}:
1.0 1.0 1.0
2.0 2.0 2.0
3.0 3.0 3.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/views.jl#L208-L241)###
`Base.parent`Function
```
parent(A)
```
Return the underlying "parent array”. This parent array of objects of types `SubArray`, `ReshapedArray` or `LinearAlgebra.Transpose` is what was passed as an argument to `view`, `reshape`, `transpose`, etc. during object creation. If the input is not a wrapped object, return the input itself. If the input is wrapped multiple times, only the outermost wrapper will be removed.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> V = view(A, 1:2, :)
2×2 view(::Matrix{Int64}, 1:2, :) with eltype Int64:
1 2
3 4
julia> parent(V)
2×2 Matrix{Int64}:
1 2
3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1383-L1408)###
`Base.parentindices`Function
```
parentindices(A)
```
Return the indices in the [`parent`](#Base.parent) which correspond to the array view `A`.
**Examples**
```
julia> A = [1 2; 3 4];
julia> V = view(A, 1, :)
2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
1
2
julia> parentindices(V)
(1, Base.Slice(Base.OneTo(2)))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/subarray.jl#L81-L98)###
`Base.selectdim`Function
```
selectdim(A, d::Integer, i)
```
Return a view of all the data of `A` where the index for dimension `d` equals `i`.
Equivalent to `view(A,:,:,...,i,:,:,...)` where `i` is in position `d`.
See also: [`eachslice`](#Base.eachslice).
**Examples**
```
julia> A = [1 2 3 4; 5 6 7 8]
2×4 Matrix{Int64}:
1 2 3 4
5 6 7 8
julia> selectdim(A, 2, 3)
2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
3
7
julia> selectdim(A, 2, 3:4)
2×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64:
3 4
7 8
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L225-L251)###
`Base.reinterpret`Function
```
reinterpret(type, A)
```
Change the type-interpretation of a block of memory. For arrays, this constructs a view of the array with the same binary data as the given array, but with the specified element type. For example, `reinterpret(Float32, UInt32(7))` interprets the 4 bytes corresponding to `UInt32(7)` as a [`Float32`](../numbers/index#Core.Float32).
**Examples**
```
julia> reinterpret(Float32, UInt32(7))
1.0f-44
julia> reinterpret(Float32, UInt32[1 2 3 4 5])
1×5 reinterpret(Float32, ::Matrix{UInt32}):
1.0f-45 3.0f-45 4.0f-45 6.0f-45 7.0f-45
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L418-L437)
```
reinterpret(reshape, T, A::AbstractArray{S}) -> B
```
Change the type-interpretation of `A` while consuming or adding a "channel dimension."
If `sizeof(T) = n*sizeof(S)` for `n>1`, `A`'s first dimension must be of size `n` and `B` lacks `A`'s first dimension. Conversely, if `sizeof(S) = n*sizeof(T)` for `n>1`, `B` gets a new first dimension of size `n`. The dimensionality is unchanged if `sizeof(T) == sizeof(S)`.
This method requires at least Julia 1.6.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> reinterpret(reshape, Complex{Int}, A) # the result is a vector
2-element reinterpret(reshape, Complex{Int64}, ::Matrix{Int64}) with eltype Complex{Int64}:
1 + 3im
2 + 4im
julia> a = [(1,2,3), (4,5,6)]
2-element Vector{Tuple{Int64, Int64, Int64}}:
(1, 2, 3)
(4, 5, 6)
julia> reinterpret(reshape, Int, a) # the result is a matrix
3×2 reinterpret(reshape, Int64, ::Vector{Tuple{Int64, Int64, Int64}}) with eltype Int64:
1 4
2 5
3 6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reinterpretarray.jl#L98-L134)###
`Base.reshape`Function
```
reshape(A, dims...) -> AbstractArray
reshape(A, dims) -> AbstractArray
```
Return an array with the same data as `A`, but with different dimension sizes or number of dimensions. The two arrays share the same underlying data, so that the result is mutable if and only if `A` is mutable, and setting elements of one alters the values of the other.
The new dimensions may be specified either as a list of arguments or as a shape tuple. At most one dimension may be specified with a `:`, in which case its length is computed such that its product with all the specified dimensions is equal to the length of the original array `A`. The total number of elements must not change.
**Examples**
```
julia> A = Vector(1:16)
16-element Vector{Int64}:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
julia> reshape(A, (4, 4))
4×4 Matrix{Int64}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> reshape(A, 2, :)
2×8 Matrix{Int64}:
1 3 5 7 9 11 13 15
2 4 6 8 10 12 14 16
julia> reshape(1:6, 2, 3)
2×3 reshape(::UnitRange{Int64}, 2, 3) with eltype Int64:
1 3 5
2 4 6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reshapedarray.jl#L54-L107)###
`Base.dropdims`Function
```
dropdims(A; dims)
```
Return an array with the same data as `A`, but with the dimensions specified by `dims` removed. `size(A,d)` must equal 1 for every `d` in `dims`, and repeated dimensions or numbers outside `1:ndims(A)` are forbidden.
The result shares the same underlying data as `A`, such that the result is mutable if and only if `A` is mutable, and setting elements of one alters the values of the other.
See also: [`reshape`](#Base.reshape), [`vec`](#Base.vec).
**Examples**
```
julia> a = reshape(Vector(1:4),(2,2,1,1))
2×2×1×1 Array{Int64, 4}:
[:, :, 1, 1] =
1 3
2 4
julia> b = dropdims(a; dims=3)
2×2×1 Array{Int64, 3}:
[:, :, 1] =
1 3
2 4
julia> b[1,1,1] = 5; a
2×2×1×1 Array{Int64, 4}:
[:, :, 1, 1] =
5 3
2 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L48-L81)###
`Base.vec`Function
```
vec(a::AbstractArray) -> AbstractVector
```
Reshape the array `a` as a one-dimensional column vector. Return `a` if it is already an `AbstractVector`. The resulting array shares the same underlying data as `a`, so it will only be mutable if `a` is mutable, in which case modifying one will also modify the other.
**Examples**
```
julia> a = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> vec(a)
6-element Vector{Int64}:
1
4
2
5
3
6
julia> vec(1:3)
1:3
```
See also [`reshape`](#Base.reshape), [`dropdims`](#Base.dropdims).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L11-L40)###
`Base.SubArray`Type
```
SubArray{T,N,P,I,L} <: AbstractArray{T,N}
```
`N`-dimensional view into a parent array (of type `P`) with an element type `T`, restricted by a tuple of indices (of type `I`). `L` is true for types that support fast linear indexing, and `false` otherwise.
Construct `SubArray`s using the [`view`](#Base.view) function.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/subarray.jl#L7-L13)
[Concatenation and permutation](#Concatenation-and-permutation)
----------------------------------------------------------------
###
`Base.cat`Function
```
cat(A...; dims)
```
Concatenate the input arrays along the specified dimensions in the iterable `dims`. For dimensions not in `dims`, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions in `dims`, the size of the output array is the sum of the sizes of the input arrays along that dimension. If `dims` is a single number, the different arrays are tightly stacked along that dimension. If `dims` is an iterable containing several dimensions, this allows one to construct block diagonal matrices and their higher-dimensional analogues by simultaneously increasing several dimensions for every new input array and putting zero blocks elsewhere. For example, `cat(matrices...; dims=(1,2))` builds a block diagonal matrix, i.e. a block matrix with `matrices[1]`, `matrices[2]`, ... as diagonal blocks and matching zero blocks away from the diagonal.
See also [`hcat`](#Base.hcat), [`vcat`](#Base.vcat), [`hvcat`](#Base.hvcat), [`repeat`](#Base.repeat).
**Examples**
```
julia> cat([1 2; 3 4], [pi, pi], fill(10, 2,3,1); dims=2)
2×6×1 Array{Float64, 3}:
[:, :, 1] =
1.0 2.0 3.14159 10.0 10.0 10.0
3.0 4.0 3.14159 10.0 10.0 10.0
julia> cat(true, trues(2,2), trues(4)', dims=(1,2))
4×7 Matrix{Bool}:
1 0 0 0 0 0 0
0 1 1 0 0 0 0
0 1 1 0 0 0 0
0 0 0 1 1 1 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1883-L1915)###
`Base.vcat`Function
```
vcat(A...)
```
Concatenate along dimension 1. To efficiently concatenate a large vector of arrays, use `reduce(vcat, x)`.
**Examples**
```
julia> a = [1 2 3 4 5]
1×5 Matrix{Int64}:
1 2 3 4 5
julia> b = [6 7 8 9 10; 11 12 13 14 15]
2×5 Matrix{Int64}:
6 7 8 9 10
11 12 13 14 15
julia> vcat(a,b)
3×5 Matrix{Int64}:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
julia> c = ([1 2 3], [4 5 6])
([1 2 3], [4 5 6])
julia> vcat(c...)
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> vs = [[1, 2], [3, 4], [5, 6]]
3-element Vector{Vector{Int64}}:
[1, 2]
[3, 4]
[5, 6]
julia> reduce(vcat, vs)
6-element Vector{Int64}:
1
2
3
4
5
6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1768-L1814)###
`Base.hcat`Function
```
hcat(A...)
```
Concatenate along dimension 2. To efficiently concatenate a large vector of arrays, use `reduce(hcat, x)`.
**Examples**
```
julia> a = [1; 2; 3; 4; 5]
5-element Vector{Int64}:
1
2
3
4
5
julia> b = [6 7; 8 9; 10 11; 12 13; 14 15]
5×2 Matrix{Int64}:
6 7
8 9
10 11
12 13
14 15
julia> hcat(a,b)
5×3 Matrix{Int64}:
1 6 7
2 8 9
3 10 11
4 12 13
5 14 15
julia> c = ([1; 2; 3], [4; 5; 6])
([1, 2, 3], [4, 5, 6])
julia> hcat(c...)
3×2 Matrix{Int64}:
1 4
2 5
3 6
julia> x = Matrix(undef, 3, 0) # x = [] would have created an Array{Any, 1}, but need an Array{Any, 2}
3×0 Matrix{Any}
julia> hcat(x, [1; 2; 3])
3×1 Matrix{Any}:
1
2
3
julia> vs = [[1, 2], [3, 4], [5, 6]]
3-element Vector{Vector{Int64}}:
[1, 2]
[3, 4]
[5, 6]
julia> reduce(hcat, vs)
2×3 Matrix{Int64}:
1 3 5
2 4 6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1816-L1877)###
`Base.hvcat`Function
```
hvcat(rows::Tuple{Vararg{Int}}, values...)
```
Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row.
**Examples**
```
julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
(1, 2, 3, 4, 5, 6)
julia> [a b c; d e f]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> hvcat((3,3), a,b,c,d,e,f)
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> [a b; c d; e f]
3×2 Matrix{Int64}:
1 2
3 4
5 6
julia> hvcat((2,2,2), a,b,c,d,e,f)
3×2 Matrix{Int64}:
1 2
3 4
5 6
```
If the first argument is a single integer `n`, then all block rows are assumed to have `n` block columns.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L1951-L1988)###
`Base.hvncat`Function
```
hvncat(dim::Int, row_first, values...)
hvncat(dims::Tuple{Vararg{Int}}, row_first, values...)
hvncat(shape::Tuple{Vararg{Tuple}}, row_first, values...)
```
Horizontal, vertical, and n-dimensional concatenation of many `values` in one call.
This function is called for block matrix syntax. The first argument either specifies the shape of the concatenation, similar to `hvcat`, as a tuple of tuples, or the dimensions that specify the key number of elements along each axis, and is used to determine the output dimensions. The `dims` form is more performant, and is used by default when the concatenation operation has the same number of elements along each axis (e.g., [a b; c d;;; e f ; g h]). The `shape` form is used when the number of elements along each axis is unbalanced (e.g., [a b ; c]). Unbalanced syntax needs additional validation overhead. The `dim` form is an optimization for concatenation along just one dimension. `row_first` indicates how `values` are ordered. The meaning of the first and second elements of `shape` are also swapped based on `row_first`.
**Examples**
```
julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
(1, 2, 3, 4, 5, 6)
julia> [a b c;;; d e f]
1×3×2 Array{Int64, 3}:
[:, :, 1] =
1 2 3
[:, :, 2] =
4 5 6
julia> hvncat((2,1,3), false, a,b,c,d,e,f)
2×1×3 Array{Int64, 3}:
[:, :, 1] =
1
2
[:, :, 2] =
3
4
[:, :, 3] =
5
6
julia> [a b;;; c d;;; e f]
1×2×3 Array{Int64, 3}:
[:, :, 1] =
1 2
[:, :, 2] =
3 4
[:, :, 3] =
5 6
julia> hvncat(((3, 3), (3, 3), (6,)), true, a, b, c, d, e, f)
1×3×2 Array{Int64, 3}:
[:, :, 1] =
1 2 3
[:, :, 2] =
4 5 6
```
**Examples for construction of the arguments:**
```
[a b c ; d e f ;;;
g h i ; j k l ;;;
m n o ; p q r ;;;
s t u ; v w x]
=> dims = (2, 3, 4)
[a b ; c ;;; d ;;;;]
___ _ _
2 1 1 = elements in each row (2, 1, 1)
_______ _
3 1 = elements in each column (3, 1)
_____________
4 = elements in each 3d slice (4,)
_____________
4 = elements in each 4d slice (4,)
=> shape = ((2, 1, 1), (3, 1), (4,), (4,)) with `rowfirst` = true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L2102-L2187)###
`Base.vect`Function
```
vect(X...)
```
Create a [`Vector`](#Base.Vector) with element type computed from the `promote_typeof` of the argument, containing the argument list.
**Examples**
```
julia> a = Base.vect(UInt8(1), 2.5, 1//2)
3-element Vector{Float64}:
1.0
2.5
0.5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L128-L142)###
`Base.circshift`Function
```
circshift(A, shifts)
```
Circularly shift, i.e. rotate, the data in an array. The second argument is a tuple or vector giving the amount to shift in each dimension, or an integer to shift only in the first dimension.
See also: [`circshift!`](#Base.circshift!), [`circcopy!`](#Base.circcopy!), [`bitrotate`](../math/index#Base.bitrotate), [`<<`](#).
**Examples**
```
julia> b = reshape(Vector(1:16), (4,4))
4×4 Matrix{Int64}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> circshift(b, (0,2))
4×4 Matrix{Int64}:
9 13 1 5
10 14 2 6
11 15 3 7
12 16 4 8
julia> circshift(b, (-1,0))
4×4 Matrix{Int64}:
2 6 10 14
3 7 11 15
4 8 12 16
1 5 9 13
julia> a = BitArray([true, true, false, false, true])
5-element BitVector:
1
1
0
0
1
julia> circshift(a, 1)
5-element BitVector:
1
1
1
0
0
julia> circshift(a, -1)
5-element BitVector:
1
0
0
1
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L264-L320)###
`Base.circshift!`Function
```
circshift!(dest, src, shifts)
```
Circularly shift, i.e. rotate, the data in `src`, storing the result in `dest`. `shifts` specifies the amount to shift in each dimension.
The `dest` array must be distinct from the `src` array (they cannot alias each other).
See also [`circshift`](#Base.circshift).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1162-L1172)###
`Base.circcopy!`Function
```
circcopy!(dest, src)
```
Copy `src` to `dest`, indexing each dimension modulo its length. `src` and `dest` must have the same size, but can be offset in their indices; any offset results in a (circular) wraparound. If the arrays have overlapping indices, then on the domain of the overlap `dest` agrees with `src`.
See also: [`circshift`](#Base.circshift).
**Examples**
```
julia> src = reshape(Vector(1:16), (4,4))
4×4 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> dest = OffsetArray{Int}(undef, (0:3,2:5))
julia> circcopy!(dest, src)
OffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5:
8 12 16 4
5 9 13 1
6 10 14 2
7 11 15 3
julia> dest[1:3,2:4] == src[1:3,2:4]
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1218-L1250)###
`Base.findall`Method
```
findall(A)
```
Return a vector `I` of the `true` indices or keys of `A`. If there are no such elements of `A`, return an empty array. To search for other kinds of values, pass a predicate as the first argument.
Indices or keys are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
See also: [`findfirst`](#Base.findfirst-Tuple%7BAny%7D), [`searchsorted`](../sort/index#Base.Sort.searchsorted).
**Examples**
```
julia> A = [true, false, false, true]
4-element Vector{Bool}:
1
0
0
1
julia> findall(A)
2-element Vector{Int64}:
1
4
julia> A = [true false; false true]
2×2 Matrix{Bool}:
1 0
0 1
julia> findall(A)
2-element Vector{CartesianIndex{2}}:
CartesianIndex(1, 1)
CartesianIndex(2, 2)
julia> findall(falses(3))
Int64[]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2313-L2352)###
`Base.findall`Method
```
findall(f::Function, A)
```
Return a vector `I` of the indices or keys of `A` where `f(A[I])` returns `true`. If there are no such elements of `A`, return an empty array.
Indices or keys are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
**Examples**
```
julia> x = [1, 3, 4]
3-element Vector{Int64}:
1
3
4
julia> findall(isodd, x)
2-element Vector{Int64}:
1
2
julia> A = [1 2 0; 3 4 0]
2×3 Matrix{Int64}:
1 2 0
3 4 0
julia> findall(isodd, A)
2-element Vector{CartesianIndex{2}}:
CartesianIndex(1, 1)
CartesianIndex(2, 1)
julia> findall(!iszero, A)
4-element Vector{CartesianIndex{2}}:
CartesianIndex(1, 1)
CartesianIndex(2, 1)
CartesianIndex(1, 2)
CartesianIndex(2, 2)
julia> d = Dict(:A => 10, :B => -1, :C => 0)
Dict{Symbol, Int64} with 3 entries:
:A => 10
:B => -1
:C => 0
julia> findall(x -> x >= 0, d)
2-element Vector{Symbol}:
:A
:C
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2256-L2306)###
`Base.findfirst`Method
```
findfirst(A)
```
Return the index or key of the first `true` value in `A`. Return `nothing` if no such value is found. To search for other kinds of values, pass a predicate as the first argument.
Indices or keys are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
See also: [`findall`](#Base.findall-Tuple%7BAny%7D), [`findnext`](#Base.findnext-Tuple%7BAny,%20Integer%7D), [`findlast`](#Base.findlast-Tuple%7BAny%7D), [`searchsortedfirst`](../sort/index#Base.Sort.searchsortedfirst).
**Examples**
```
julia> A = [false, false, true, false]
4-element Vector{Bool}:
0
0
1
0
julia> findfirst(A)
3
julia> findfirst(falses(3)) # returns nothing, but not printed in the REPL
julia> A = [false false; true false]
2×2 Matrix{Bool}:
0 0
1 0
julia> findfirst(A)
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1954-L1988)###
`Base.findfirst`Method
```
findfirst(predicate::Function, A)
```
Return the index or key of the first element of `A` for which `predicate` returns `true`. Return `nothing` if there is no such element.
Indices or keys are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
**Examples**
```
julia> A = [1, 4, 2, 2]
4-element Vector{Int64}:
1
4
2
2
julia> findfirst(iseven, A)
2
julia> findfirst(x -> x>10, A) # returns nothing, but not printed in the REPL
julia> findfirst(isequal(4), A)
2
julia> A = [1 4; 2 2]
2×2 Matrix{Int64}:
1 4
2 2
julia> findfirst(iseven, A)
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2031-L2065)###
`Base.findlast`Method
```
findlast(A)
```
Return the index or key of the last `true` value in `A`. Return `nothing` if there is no `true` value in `A`.
Indices or keys are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
See also: [`findfirst`](#Base.findfirst-Tuple%7BAny%7D), [`findprev`](#Base.findprev-Tuple%7BAny,%20Integer%7D), [`findall`](#Base.findall-Tuple%7BAny%7D).
**Examples**
```
julia> A = [true, false, true, false]
4-element Vector{Bool}:
1
0
1
0
julia> findlast(A)
3
julia> A = falses(2,2);
julia> findlast(A) # returns nothing, but not printed in the REPL
julia> A = [true false; true false]
2×2 Matrix{Bool}:
1 0
1 0
julia> findlast(A)
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2127-L2162)###
`Base.findlast`Method
```
findlast(predicate::Function, A)
```
Return the index or key of the last element of `A` for which `predicate` returns `true`. Return `nothing` if there is no such element.
Indices or keys are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
**Examples**
```
julia> A = [1, 2, 3, 4]
4-element Vector{Int64}:
1
2
3
4
julia> findlast(isodd, A)
3
julia> findlast(x -> x > 5, A) # returns nothing, but not printed in the REPL
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> findlast(isodd, A)
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2213-L2244)###
`Base.findnext`Method
```
findnext(A, i)
```
Find the next index after or including `i` of a `true` element of `A`, or `nothing` if not found.
Indices are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
**Examples**
```
julia> A = [false, false, true, false]
4-element Vector{Bool}:
0
0
1
0
julia> findnext(A, 1)
3
julia> findnext(A, 4) # returns nothing, but not printed in the REPL
julia> A = [false false; true false]
2×2 Matrix{Bool}:
0 0
1 0
julia> findnext(A, CartesianIndex(1, 1))
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1920-L1951)###
`Base.findnext`Method
```
findnext(predicate::Function, A, i)
```
Find the next index after or including `i` of an element of `A` for which `predicate` returns `true`, or `nothing` if not found.
Indices are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
**Examples**
```
julia> A = [1, 4, 2, 2];
julia> findnext(isodd, A, 1)
1
julia> findnext(isodd, A, 2) # returns nothing, but not printed in the REPL
julia> A = [1 4; 2 2];
julia> findnext(isodd, A, CartesianIndex(1, 1))
CartesianIndex(1, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1994-L2017)###
`Base.findprev`Method
```
findprev(A, i)
```
Find the previous index before or including `i` of a `true` element of `A`, or `nothing` if not found.
Indices are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
See also: [`findnext`](#Base.findnext-Tuple%7BAny,%20Integer%7D), [`findfirst`](#Base.findfirst-Tuple%7BAny%7D), [`findall`](#Base.findall-Tuple%7BAny%7D).
**Examples**
```
julia> A = [false, false, true, true]
4-element Vector{Bool}:
0
0
1
1
julia> findprev(A, 3)
3
julia> findprev(A, 1) # returns nothing, but not printed in the REPL
julia> A = [false false; true true]
2×2 Matrix{Bool}:
0 0
1 1
julia> findprev(A, CartesianIndex(2, 1))
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2091-L2124)###
`Base.findprev`Method
```
findprev(predicate::Function, A, i)
```
Find the previous index before or including `i` of an element of `A` for which `predicate` returns `true`, or `nothing` if not found.
Indices are of the same type as those returned by [`keys(A)`](#Base.keys-Tuple%7BAbstractArray%7D) and [`pairs(A)`](../collections/index#Base.pairs).
**Examples**
```
julia> A = [4, 6, 1, 2]
4-element Vector{Int64}:
4
6
1
2
julia> findprev(isodd, A, 1) # returns nothing, but not printed in the REPL
julia> findprev(isodd, A, 3)
3
julia> A = [4 6; 1 2]
2×2 Matrix{Int64}:
4 6
1 2
julia> findprev(isodd, A, CartesianIndex(1, 2))
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2168-L2199)###
`Base.permutedims`Function
```
permutedims(A::AbstractArray, perm)
```
Permute the dimensions of array `A`. `perm` is a vector or a tuple of length `ndims(A)` specifying the permutation.
See also [`permutedims!`](#Base.permutedims!), [`PermutedDimsArray`](#Base.PermutedDimsArrays.PermutedDimsArray), [`transpose`](../../stdlib/linearalgebra/index#Base.transpose), [`invperm`](#Base.invperm).
**Examples**
```
julia> A = reshape(Vector(1:8), (2,2,2))
2×2×2 Array{Int64, 3}:
[:, :, 1] =
1 3
2 4
[:, :, 2] =
5 7
6 8
julia> permutedims(A, (3, 2, 1))
2×2×2 Array{Int64, 3}:
[:, :, 1] =
1 3
5 7
[:, :, 2] =
2 4
6 8
julia> B = randn(5, 7, 11, 13);
julia> perm = [4,1,3,2];
julia> size(permutedims(B, perm))
(13, 5, 11, 7)
julia> size(B)[perm] == ans
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/permuteddimsarray.jl#L83-L123)
```
permutedims(m::AbstractMatrix)
```
Permute the dimensions of the matrix `m`, by flipping the elements across the diagonal of the matrix. Differs from `LinearAlgebra`'s [`transpose`](../../stdlib/linearalgebra/index#Base.transpose) in that the operation is not recursive.
**Examples**
```
julia> a = [1 2; 3 4];
julia> b = [5 6; 7 8];
julia> c = [9 10; 11 12];
julia> d = [13 14; 15 16];
julia> X = [[a] [b]; [c] [d]]
2×2 Matrix{Matrix{Int64}}:
[1 2; 3 4] [5 6; 7 8]
[9 10; 11 12] [13 14; 15 16]
julia> permutedims(X)
2×2 Matrix{Matrix{Int64}}:
[1 2; 3 4] [9 10; 11 12]
[5 6; 7 8] [13 14; 15 16]
julia> transpose(X)
2×2 transpose(::Matrix{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
[1 3; 2 4] [9 11; 10 12]
[5 7; 6 8] [13 15; 14 16]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/permuteddimsarray.jl#L129-L161)
```
permutedims(v::AbstractVector)
```
Reshape vector `v` into a `1 × length(v)` row matrix. Differs from `LinearAlgebra`'s [`transpose`](../../stdlib/linearalgebra/index#Base.transpose) in that the operation is not recursive.
**Examples**
```
julia> permutedims([1, 2, 3, 4])
1×4 Matrix{Int64}:
1 2 3 4
julia> V = [[[1 2; 3 4]]; [[5 6; 7 8]]]
2-element Vector{Matrix{Int64}}:
[1 2; 3 4]
[5 6; 7 8]
julia> permutedims(V)
1×2 Matrix{Matrix{Int64}}:
[1 2; 3 4] [5 6; 7 8]
julia> transpose(V)
1×2 transpose(::Vector{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
[1 3; 2 4] [5 7; 6 8]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/permuteddimsarray.jl#L164-L190)###
`Base.permutedims!`Function
```
permutedims!(dest, src, perm)
```
Permute the dimensions of array `src` and store the result in the array `dest`. `perm` is a vector specifying a permutation of length `ndims(src)`. The preallocated array `dest` should have `size(dest) == size(src)[perm]` and is completely overwritten. No in-place permutation is supported and unexpected results will happen if `src` and `dest` have overlapping memory regions.
See also [`permutedims`](#Base.permutedims).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/permuteddimsarray.jl#L193-L203)###
`Base.PermutedDimsArrays.PermutedDimsArray`Type
```
PermutedDimsArray(A, perm) -> B
```
Given an AbstractArray `A`, create a view `B` such that the dimensions appear to be permuted. Similar to `permutedims`, except that no copying occurs (`B` shares storage with `A`).
See also [`permutedims`](#Base.permutedims), [`invperm`](#Base.invperm).
**Examples**
```
julia> A = rand(3,5,4);
julia> B = PermutedDimsArray(A, (3,1,2));
julia> size(B)
(4, 3, 5)
julia> B[3,1,2] == A[1,2,3]
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/permuteddimsarray.jl#L20-L41)###
`Base.promote_shape`Function
```
promote_shape(s1, s2)
```
Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.
**Examples**
```
julia> a = fill(1, (3,4,1,1,1));
julia> b = fill(1, (3,4));
julia> promote_shape(a,b)
(Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1))
julia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1))
(2, 3, 1, 4, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/indices.jl#L132-L150)
[Array functions](#Array-functions)
------------------------------------
###
`Base.accumulate`Function
```
accumulate(op, A; dims::Integer, [init])
```
Cumulative operation `op` along the dimension `dims` of `A` (providing `dims` is optional for vectors). An initial value `init` may optionally be provided by a keyword argument. See also [`accumulate!`](#Base.accumulate!) to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
For common operations there are specialized variants of `accumulate`, see [`cumsum`](#Base.cumsum), [`cumprod`](#Base.cumprod). For a lazy version, see [`Iterators.accumulate`](../iterators/index#Base.Iterators.accumulate).
`accumulate` on a non-array iterator requires at least Julia 1.5.
**Examples**
```
julia> accumulate(+, [1,2,3])
3-element Vector{Int64}:
1
3
6
julia> accumulate(min, (1, -2, 3, -4, 5), init=0)
(0, -2, -2, -4, -4)
julia> accumulate(/, (2, 4, Inf), init=100)
(50.0, 12.5, 0.0)
julia> accumulate(=>, i^2 for i in 1:3)
3-element Vector{Any}:
1
1 => 4
(1 => 4) => 9
julia> accumulate(+, fill(1, 3, 4))
3×4 Matrix{Int64}:
1 4 7 10
2 5 8 11
3 6 9 12
julia> accumulate(+, fill(1, 2, 5), dims=2, init=100.0)
2×5 Matrix{Float64}:
101.0 102.0 103.0 104.0 105.0
101.0 102.0 103.0 104.0 105.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L225-L271)###
`Base.accumulate!`Function
```
accumulate!(op, B, A; [dims], [init])
```
Cumulative operation `op` on `A` along the dimension `dims`, storing the result in `B`. Providing `dims` is optional for vectors. If the keyword argument `init` is given, its value is used to instantiate the accumulation.
See also [`accumulate`](#Base.accumulate), [`cumsum!`](#Base.cumsum!), [`cumprod!`](#Base.cumprod!).
**Examples**
```
julia> x = [1, 0, 2, 0, 3];
julia> y = rand(5);
julia> accumulate!(+, y, x);
julia> y
5-element Vector{Float64}:
1.0
1.0
3.0
3.0
6.0
julia> A = [1 2 3; 4 5 6];
julia> B = similar(A);
julia> accumulate!(-, B, A, dims=1)
2×3 Matrix{Int64}:
1 2 3
-3 -3 -3
julia> accumulate!(*, B, A, dims=2, init=10)
2×3 Matrix{Int64}:
10 20 60
40 200 1200
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L297-L336)###
`Base.cumprod`Function
```
cumprod(A; dims::Integer)
```
Cumulative product along the dimension `dim`. See also [`cumprod!`](#Base.cumprod!) to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
**Examples**
```
julia> a = Int8[1 2 3; 4 5 6];
julia> cumprod(a, dims=1)
2×3 Matrix{Int64}:
1 2 3
4 10 18
julia> cumprod(a, dims=2)
2×3 Matrix{Int64}:
1 2 6
4 20 120
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L165-L186)
```
cumprod(itr)
```
Cumulative product of an iterator.
See also [`cumprod!`](#Base.cumprod!), [`accumulate`](#Base.accumulate), [`cumsum`](#Base.cumsum).
`cumprod` on a non-array iterator requires at least Julia 1.5.
**Examples**
```
julia> cumprod(fill(1//2, 3))
3-element Vector{Rational{Int64}}:
1//2
1//4
1//8
julia> cumprod((1, 2, 1, 3, 1))
(1, 2, 2, 6, 6)
julia> cumprod("julia")
5-element Vector{String}:
"j"
"ju"
"jul"
"juli"
"julia"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L191-L220)###
`Base.cumprod!`Function
```
cumprod!(B, A; dims::Integer)
```
Cumulative product of `A` along the dimension `dims`, storing the result in `B`. See also [`cumprod`](#Base.cumprod).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L148-L153)
```
cumprod!(y::AbstractVector, x::AbstractVector)
```
Cumulative product of a vector `x`, storing the result in `y`. See also [`cumprod`](#Base.cumprod).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L157-L162)###
`Base.cumsum`Function
```
cumsum(A; dims::Integer)
```
Cumulative sum along the dimension `dims`. See also [`cumsum!`](#Base.cumsum!) to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
**Examples**
```
julia> a = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> cumsum(a, dims=1)
2×3 Matrix{Int64}:
1 2 3
5 7 9
julia> cumsum(a, dims=2)
2×3 Matrix{Int64}:
1 3 6
4 9 15
```
The return array's `eltype` is `Int` for signed integers of less than system word size and `UInt` for unsigned integers of less than system word size. To preserve `eltype` of arrays with small signed or unsigned integer `accumulate(+, A)` should be used.
```
julia> cumsum(Int8[100, 28])
2-element Vector{Int64}:
100
128
julia> accumulate(+,Int8[100, 28])
2-element Vector{Int8}:
100
-128
```
In the former case, the integers are widened to system word size and therefore the result is `Int64[100, 128]`. In the latter case, no such widening happens and integer overflow results in `Int8[100, -128]`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L64-L110)
```
cumsum(itr)
```
Cumulative sum of an iterator.
See also [`accumulate`](#Base.accumulate) to apply functions other than `+`.
`cumsum` on a non-array iterator requires at least Julia 1.5.
**Examples**
```
julia> cumsum(1:3)
3-element Vector{Int64}:
1
3
6
julia> cumsum((true, false, true, false, true))
(1, 1, 2, 2, 3)
julia> cumsum(fill(1, 2) for i in 1:3)
3-element Vector{Vector{Int64}}:
[1, 1]
[2, 2]
[3, 3]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L116-L143)###
`Base.cumsum!`Function
```
cumsum!(B, A; dims::Integer)
```
Cumulative sum of `A` along the dimension `dims`, storing the result in `B`. See also [`cumsum`](#Base.cumsum).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/accumulate.jl#L41-L45)###
`Base.diff`Function
```
diff(A::AbstractVector)
diff(A::AbstractArray; dims::Integer)
```
Finite difference operator on a vector or a multidimensional array `A`. In the latter case the dimension to operate on needs to be specified with the `dims` keyword argument.
`diff` for arrays with dimension higher than 2 requires at least Julia 1.1.
**Examples**
```
julia> a = [2 4; 6 16]
2×2 Matrix{Int64}:
2 4
6 16
julia> diff(a, dims=2)
2×1 Matrix{Int64}:
2
10
julia> diff(vec(a))
3-element Vector{Int64}:
4
-2
12
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L967-L996)###
`Base.repeat`Function
```
repeat(A::AbstractArray, counts::Integer...)
```
Construct an array by repeating array `A` a given number of times in each dimension, specified by `counts`.
See also: [`fill`](#Base.fill), [`Iterators.repeated`](../iterators/index#Base.Iterators.repeated), [`Iterators.cycle`](../iterators/index#Base.Iterators.cycle).
**Examples**
```
julia> repeat([1, 2, 3], 2)
6-element Vector{Int64}:
1
2
3
1
2
3
julia> repeat([1, 2, 3], 2, 3)
6×3 Matrix{Int64}:
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L327-L354)
```
repeat(A::AbstractArray; inner=ntuple(Returns(1), ndims(A)), outer=ntuple(Returns(1), ndims(A)))
```
Construct an array by repeating the entries of `A`. The i-th element of `inner` specifies the number of times that the individual entries of the i-th dimension of `A` should be repeated. The i-th element of `outer` specifies the number of times that a slice along the i-th dimension of `A` should be repeated. If `inner` or `outer` are omitted, no repetition is performed.
**Examples**
```
julia> repeat(1:2, inner=2)
4-element Vector{Int64}:
1
1
2
2
julia> repeat(1:2, outer=2)
4-element Vector{Int64}:
1
2
1
2
julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
4×6 Matrix{Int64}:
1 2 1 2 1 2
1 2 1 2 1 2
3 4 3 4 3 4
3 4 3 4 3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L359-L391)
```
repeat(s::AbstractString, r::Integer)
```
Repeat a string `r` times. This can be written as `s^r`.
See also [`^`](#Base.:%5E-Tuple%7BUnion%7BAbstractChar,%20AbstractString%7D,%20Integer%7D).
**Examples**
```
julia> repeat("ha", 3)
"hahaha"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L702-L714)
```
repeat(c::AbstractChar, r::Integer) -> String
```
Repeat a character `r` times. This can equivalently be accomplished by calling [`c^r`](#Base.:%5E-Tuple%7BUnion%7BAbstractChar,%20AbstractString%7D,%20Integer%7D).
**Examples**
```
julia> repeat('A', 3)
"AAA"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/string.jl#L325-L336)###
`Base.rot180`Function
```
rot180(A)
```
Rotate matrix `A` 180 degrees.
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rot180(a)
2×2 Matrix{Int64}:
4 3
2 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L158-L175)
```
rot180(A, k)
```
Rotate matrix `A` 180 degrees an integer `k` number of times. If `k` is even, this is equivalent to a `copy`.
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rot180(a,1)
2×2 Matrix{Int64}:
4 3
2 1
julia> rot180(a,2)
2×2 Matrix{Int64}:
1 2
3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L260-L283)###
`Base.rotl90`Function
```
rotl90(A)
```
Rotate matrix `A` left 90 degrees.
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rotl90(a)
2×2 Matrix{Int64}:
2 4
1 3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L103-L120)
```
rotl90(A, k)
```
Left-rotate matrix `A` 90 degrees counterclockwise an integer `k` number of times. If `k` is a multiple of four (including zero), this is equivalent to a `copy`.
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rotl90(a,1)
2×2 Matrix{Int64}:
2 4
1 3
julia> rotl90(a,2)
2×2 Matrix{Int64}:
4 3
2 1
julia> rotl90(a,3)
2×2 Matrix{Int64}:
3 1
4 2
julia> rotl90(a,4)
2×2 Matrix{Int64}:
1 2
3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L185-L218)###
`Base.rotr90`Function
```
rotr90(A)
```
Rotate matrix `A` right 90 degrees.
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rotr90(a)
2×2 Matrix{Int64}:
3 1
4 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L131-L148)
```
rotr90(A, k)
```
Right-rotate matrix `A` 90 degrees clockwise an integer `k` number of times. If `k` is a multiple of four (including zero), this is equivalent to a `copy`.
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> rotr90(a,1)
2×2 Matrix{Int64}:
3 1
4 2
julia> rotr90(a,2)
2×2 Matrix{Int64}:
4 3
2 1
julia> rotr90(a,3)
2×2 Matrix{Int64}:
2 4
1 3
julia> rotr90(a,4)
2×2 Matrix{Int64}:
1 2
3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L225-L258)###
`Base.mapslices`Function
```
mapslices(f, A; dims)
```
Transform the given dimensions of array `A` using function `f`. `f` is called on each slice of `A` of the form `A[...,:,...,:,...]`. `dims` is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, if `dims` is `[1,2]` and `A` is 4-dimensional, `f` is called on `A[:,:,i,j]` for all `i` and `j`.
See also [`eachcol`](#Base.eachcol), [`eachslice`](#Base.eachslice).
**Examples**
```
julia> a = reshape(Vector(1:16),(2,2,2,2))
2×2×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
1 3
2 4
[:, :, 2, 1] =
5 7
6 8
[:, :, 1, 2] =
9 11
10 12
[:, :, 2, 2] =
13 15
14 16
julia> mapslices(sum, a, dims = [1,2])
1×1×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
10
[:, :, 2, 1] =
26
[:, :, 1, 2] =
42
[:, :, 2, 2] =
58
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L2782-L2827)###
`Base.eachrow`Function
```
eachrow(A::AbstractVecOrMat)
```
Create a generator that iterates over the first dimension of vector or matrix `A`, returning the rows as `AbstractVector` views.
See also [`eachcol`](#Base.eachcol), [`eachslice`](#Base.eachslice), [`mapslices`](#Base.mapslices).
This function requires at least Julia 1.1.
**Example**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> first(eachrow(a))
2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
1
2
julia> collect(eachrow(a))
2-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
[1, 2]
[3, 4]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L520-L549)###
`Base.eachcol`Function
```
eachcol(A::AbstractVecOrMat)
```
Create a generator that iterates over the second dimension of matrix `A`, returning the columns as `AbstractVector` views.
See also [`eachrow`](#Base.eachrow) and [`eachslice`](#Base.eachslice).
This function requires at least Julia 1.1.
**Example**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> first(eachcol(a))
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
1
3
julia> collect(eachcol(a))
2-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
[1, 3]
[2, 4]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L553-L582)###
`Base.eachslice`Function
```
eachslice(A::AbstractArray; dims)
```
Create a generator that iterates over dimensions `dims` of `A`, returning views that select all the data from the other dimensions in `A`.
Only a single dimension in `dims` is currently supported. Equivalent to `(view(A,:,:,...,i,:,: ...)) for i in axes(A, dims))`, where `i` is in position `dims`.
See also [`eachrow`](#Base.eachrow), [`eachcol`](#Base.eachcol), [`mapslices`](#Base.mapslices), and [`selectdim`](#Base.selectdim).
This function requires at least Julia 1.1.
**Example**
```
julia> M = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> first(eachslice(M, dims=1))
3-element view(::Matrix{Int64}, 1, :) with eltype Int64:
1
2
3
julia> collect(eachslice(M, dims=2))
3-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarraymath.jl#L585-L620)
[Combinatorics](#Combinatorics)
--------------------------------
###
`Base.invperm`Function
```
invperm(v)
```
Return the inverse permutation of `v`. If `B = A[v]`, then `A == B[invperm(v)]`.
See also [`sortperm`](../sort/index#Base.sortperm), [`invpermute!`](#Base.invpermute!), [`isperm`](#Base.isperm), [`permutedims`](#Base.permutedims).
**Examples**
```
julia> p = (2, 3, 1);
julia> invperm(p)
(3, 1, 2)
julia> v = [2; 4; 3; 1];
julia> invperm(v)
4-element Vector{Int64}:
4
1
3
2
julia> A = ['a','b','c','d'];
julia> B = A[v]
4-element Vector{Char}:
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> B[invperm(v)]
4-element Vector{Char}:
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/combinatorics.jl#L237-L277)###
`Base.isperm`Function
```
isperm(v) -> Bool
```
Return `true` if `v` is a valid permutation.
**Examples**
```
julia> isperm([1; 2])
true
julia> isperm([1; 3])
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/combinatorics.jl#L55-L68)###
`Base.permute!`Method
```
permute!(v, p)
```
Permute vector `v` in-place, according to permutation `p`. No checking is done to verify that `p` is a permutation.
To return a new permutation, use `v[p]`. Note that this is generally faster than `permute!(v,p)` for large vectors.
See also [`invpermute!`](#Base.invpermute!).
**Examples**
```
julia> A = [1, 1, 3, 4];
julia> perm = [2, 4, 3, 1];
julia> permute!(A, perm);
julia> A
4-element Vector{Int64}:
1
4
3
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/combinatorics.jl#L161-L187)###
`Base.invpermute!`Function
```
invpermute!(v, p)
```
Like [`permute!`](#Base.permute!-Tuple%7BAny,%20AbstractVector%7D), but the inverse of the given permutation is applied.
**Examples**
```
julia> A = [1, 1, 3, 4];
julia> perm = [2, 4, 3, 1];
julia> invpermute!(A, perm);
julia> A
4-element Vector{Int64}:
4
1
3
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/combinatorics.jl#L214-L234)###
`Base.reverse`Method
```
reverse(A; dims=:)
```
Reverse `A` along dimension `dims`, which can be an integer (a single dimension), a tuple of integers (a tuple of dimensions) or `:` (reverse along all the dimensions, the default). See also [`reverse!`](#Base.reverse!) for in-place reversal.
**Examples**
```
julia> b = Int64[1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> reverse(b, dims=2)
2×2 Matrix{Int64}:
2 1
4 3
julia> reverse(b)
2×2 Matrix{Int64}:
4 3
2 1
```
Prior to Julia 1.6, only single-integer `dims` are supported in `reverse`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L30-L58)###
`Base.reverseind`Function
```
reverseind(v, i)
```
Given an index `i` in [`reverse(v)`](#Base.reverse-Tuple%7BAbstractVector%7D), return the corresponding index in `v` so that `v[reverseind(v,i)] == reverse(v)[i]`. (This can be nontrivial in cases where `v` contains non-ASCII characters.)
**Examples**
```
julia> s = "Julia🚀"
"Julia🚀"
julia> r = reverse(s)
"🚀ailuJ"
julia> for i in eachindex(s)
print(r[reverseind(r, i)])
end
Julia🚀
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L679-L699)###
`Base.reverse!`Function
```
reverse!(v [, start=1 [, stop=length(v) ]]) -> v
```
In-place version of [`reverse`](#Base.reverse-Tuple%7BAbstractVector%7D).
**Examples**
```
julia> A = Vector(1:5)
5-element Vector{Int64}:
1
2
3
4
5
julia> reverse!(A);
julia> A
5-element Vector{Int64}:
5
4
3
2
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1841-L1866)
```
reverse!(A; dims=:)
```
Like [`reverse`](#Base.reverse-Tuple%7BAbstractVector%7D), but operates in-place in `A`.
Multidimensional `reverse!` requires Julia 1.6.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/arraymath.jl#L62-L69)
| programming_docs |
julia Punctuation Punctuation
===========
Extended documentation for mathematical symbols & functions is [here](../math/index#math-ops).
| symbol | meaning |
| --- | --- |
| `@` | the at-sign marks a [macro](../../manual/metaprogramming/index#man-macros) invocation; optionally followed by an argument list |
| [`!`](../math/index#Base.:!) | an exclamation mark is a prefix operator for logical negation ("not") |
| `a!` | function names that end with an exclamation mark modify one or more of their arguments by convention |
| `#` | the number sign (or hash or pound) character begins single line comments |
| `#=` | when followed by an equals sign, it begins a multi-line comment (these are nestable) |
| `=#` | end a multi-line comment by immediately preceding the number sign with an equals sign |
| `$` | the dollar sign is used for [string](../../manual/strings/index#string-interpolation) and [expression](../../manual/metaprogramming/index#man-expression-interpolation) interpolation |
| [`%`](../math/index#Base.rem) | the percent symbol is the remainder operator |
| [`^`](#) | the caret is the exponentiation operator |
| [`&`](../math/index#Base.:&) | single ampersand is bitwise and |
| [`&&`](../math/index#&&) | double ampersands is short-circuiting boolean and |
| [`|`](#) | single pipe character is bitwise or |
| [`||`](#) | double pipe characters is short-circuiting boolean or |
| [`⊻`](../math/index#Base.xor) | the unicode xor character is bitwise exclusive or |
| [`~`](../math/index#Base.:~) | the tilde is an operator for bitwise not |
| `'` | a trailing apostrophe is the [`adjoint`](../../stdlib/linearalgebra/index#Base.adjoint) (that is, the complex transpose) operator Aᴴ |
| [`*`](#) | the asterisk is used for multiplication, including matrix multiplication and [string concatenation](../../manual/strings/index#man-concatenation) |
| [`/`](../math/index#Base.:/) | forward slash divides the argument on its left by the one on its right |
| [`\`](#) | backslash operator divides the argument on its right by the one on its left, commonly used to solve matrix equations |
| `()` | parentheses with no arguments constructs an empty [`Tuple`](../base/index#Core.Tuple) |
| `(a,...)` | parentheses with comma-separated arguments constructs a tuple containing its arguments |
| `(a=1,...)` | parentheses with comma-separated assignments constructs a [`NamedTuple`](../base/index#Core.NamedTuple) |
| `(x;y)` | parentheses can also be used to group one or more semicolon separated expressions |
| `a[]` | [array indexing](../../manual/arrays/index#man-array-indexing) (calling [`getindex`](../collections/index#Base.getindex) or [`setindex!`](../collections/index#Base.setindex!)) |
| `[,]` | [vector literal constructor](../../manual/arrays/index#man-array-literals) (calling [`vect`](../arrays/index#Base.vect)) |
| `[;]` | [vertical concatenation](../../manual/arrays/index#man-array-concatenation) (calling [`vcat`](../arrays/index#Base.vcat) or [`hvcat`](../arrays/index#Base.hvcat)) |
| `[ ]` | with space-separated expressions, [horizontal concatenation](../../manual/strings/index#man-concatenation) (calling [`hcat`](../arrays/index#Base.hcat) or [`hvcat`](../arrays/index#Base.hvcat)) |
| `T{ }` | curly braces following a type list that type's [parameters](../../manual/types/index#Parametric-Types) |
| `{}` | curly braces can also be used to group multiple [`where`](../base/index#where) expressions in function declarations |
| `;` | semicolons separate statements, begin a list of keyword arguments in function declarations or calls, or are used to separate array literals for vertical concatenation |
| `,` | commas separate function arguments or tuple or array components |
| `?` | the question mark delimits the ternary conditional operator (used like: `conditional ? if_true : if_false`) |
| `" "` | the single double-quote character delimits [`String`](#) literals |
| `""" """` | three double-quote characters delimits string literals that may contain `"` and ignore leading indentation |
| `' '` | the single-quote character delimits [`Char`](../strings/index#Core.Char) (that is, character) literals |
| `` `` | the backtick character delimits [external process](../../manual/running-external-programs/index#Running-External-Programs) ([`Cmd`](../base/index#Base.Cmd)) literals |
| `A...` | triple periods are a postfix operator that "splat" their arguments' contents into many arguments of a function call or declare a varargs function that "slurps" up many arguments into a single tuple |
| `a.b` | single periods access named fields in objects/modules (calling [`getproperty`](../base/index#Base.getproperty) or [`setproperty!`](../base/index#Base.setproperty!)) |
| `f.()` | periods may also prefix parentheses (like `f.(...)`) or infix operators (like `.+`) to perform the function element-wise (calling [`broadcast`](../arrays/index#Base.Broadcast.broadcast)) |
| `a:b` | colons ([`:`](../math/index#Base.::)) used as a binary infix operator construct a range from `a` to `b` (inclusive) with fixed step size `1` |
| `a:s:b` | colons ([`:`](../math/index#Base.::)) used as a ternary infix operator construct a range from `a` to `b` (inclusive) with step size `s` |
| `:` | when used by themselves, [`Colon`](../arrays/index#Base.Colon)s represent all indices within a dimension, frequently combined with [indexing](../../manual/arrays/index#man-array-indexing) |
| `::` | double-colons represent a type annotation or [`typeassert`](../base/index#Core.typeassert), depending on context, frequently used when declaring function arguments |
| `:( )` | quoted expression |
| `:a` | [`Symbol`](../base/index#Core.Symbol) a |
| [`<:`](#) | subtype operator |
| [`>:`](#) | supertype operator (reverse of subtype operator) |
| `=` | single equals sign is [assignment](../../manual/variables/index#man-variables) |
| [`==`](../math/index#Base.:==) | double equals sign is value equality comparison |
| [`===`](../base/index#Core.:===) | triple equals sign is programmatically identical equality comparison |
| [`=>`](../collections/index#Core.Pair) | right arrow using an equals sign defines a [`Pair`](../collections/index#Core.Pair) typically used to populate [dictionaries](../collections/index#Dictionaries) |
| `->` | right arrow using a hyphen defines an [anonymous function](../../manual/functions/index#man-anonymous-functions) on a single line |
| [`|>`](#) | pipe operator passes output from the left argument to input of the right argument, usually a [function](../../manual/functions/index#Function-composition-and-piping) |
| `∘` | function composition operator (typed with \circ{tab}) combines two functions as though they are a single larger [function](../../manual/functions/index#Function-composition-and-piping) |
julia Collections and Data Structures Collections and Data Structures
===============================
[Iteration](#lib-collections-iteration)
----------------------------------------
Sequential iteration is implemented by the [`iterate`](#Base.iterate) function. The general `for` loop:
```
for i in iter # or "for i = iter"
# body
end
```
is translated into:
```
next = iterate(iter)
while next !== nothing
(i, state) = next
# body
next = iterate(iter, state)
end
```
The `state` object may be anything, and should be chosen appropriately for each iterable type. See the [manual section on the iteration interface](../../manual/interfaces/index#man-interface-iteration) for more details about defining a custom iterable type.
###
`Base.iterate`Function
```
iterate(iter [, state]) -> Union{Nothing, Tuple{Any, Any}}
```
Advance the iterator to obtain the next element. If no elements remain, `nothing` should be returned. Otherwise, a 2-tuple of the next element and the new iteration state should be returned.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L897-L903)###
`Base.IteratorSize`Type
```
IteratorSize(itertype::Type) -> IteratorSize
```
Given the type of an iterator, return one of the following values:
* `SizeUnknown()` if the length (number of elements) cannot be determined in advance.
* `HasLength()` if there is a fixed, finite length.
* `HasShape{N}()` if there is a known length plus a notion of multidimensional shape (as for an array). In this case `N` should give the number of dimensions, and the [`axes`](#) function is valid for the iterator.
* `IsInfinite()` if the iterator yields values forever.
The default value (for iterators that do not define this function) is `HasLength()`. This means that most iterators are assumed to implement [`length`](#Base.length).
This trait is generally used to select between algorithms that pre-allocate space for their result, and algorithms that resize their result incrementally.
```
julia> Base.IteratorSize(1:5)
Base.HasShape{1}()
julia> Base.IteratorSize((2,3))
Base.HasLength()
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/generator.jl#L66-L91)###
`Base.IteratorEltype`Type
```
IteratorEltype(itertype::Type) -> IteratorEltype
```
Given the type of an iterator, return one of the following values:
* `EltypeUnknown()` if the type of elements yielded by the iterator is not known in advance.
* `HasEltype()` if the element type is known, and [`eltype`](#Base.eltype) would return a meaningful value.
`HasEltype()` is the default, since iterators are assumed to implement [`eltype`](#Base.eltype).
This trait is generally used to select between algorithms that pre-allocate a specific type of result, and algorithms that pick a result type based on the types of yielded values.
```
julia> Base.IteratorEltype(1:5)
Base.HasEltype()
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/generator.jl#L107-L125)Fully implemented by:
* [`AbstractRange`](#Base.AbstractRange)
* [`UnitRange`](#Base.UnitRange)
* `Tuple`
* `Number`
* [`AbstractArray`](../arrays/index#Core.AbstractArray)
* [`BitSet`](#Base.BitSet)
* [`IdDict`](#Base.IdDict)
* [`Dict`](#Base.Dict)
* [`WeakKeyDict`](#Base.WeakKeyDict)
* `EachLine`
* `AbstractString`
* [`Set`](#Base.Set)
* [`Pair`](#Core.Pair)
* [`NamedTuple`](../base/index#Core.NamedTuple)
[Constructors and Types](#Constructors-and-Types)
--------------------------------------------------
###
`Base.AbstractRange`Type
```
AbstractRange{T}
```
Supertype for ranges with elements of type `T`. [`UnitRange`](#Base.UnitRange) and other types are subtypes of this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L245-L250)###
`Base.OrdinalRange`Type
```
OrdinalRange{T, S} <: AbstractRange{T}
```
Supertype for ordinal ranges with elements of type `T` with spacing(s) of type `S`. The steps should be always-exact multiples of [`oneunit`](../numbers/index#Base.oneunit), and `T` should be a "discrete" type, which cannot have values smaller than `oneunit`. For example, `Integer` or `Date` types would qualify, whereas `Float64` would not (since this type can represent values smaller than `oneunit(Float64)`. [`UnitRange`](#Base.UnitRange), [`StepRange`](#Base.StepRange), and other types are subtypes of this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L260-L270)###
`Base.AbstractUnitRange`Type
```
AbstractUnitRange{T} <: OrdinalRange{T, T}
```
Supertype for ranges with a step size of [`oneunit(T)`](../numbers/index#Base.oneunit) with elements of type `T`. [`UnitRange`](#Base.UnitRange) and other types are subtypes of this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L273-L278)###
`Base.StepRange`Type
```
StepRange{T, S} <: OrdinalRange{T, S}
```
Ranges with elements of type `T` with spacing of type `S`. The step between each element is constant, and the range is defined in terms of a `start` and `stop` of type `T` and a `step` of type `S`. Neither `T` nor `S` should be floating point types. The syntax `a:b:c` with `b > 1` and `a`, `b`, and `c` all integers creates a `StepRange`.
**Examples**
```
julia> collect(StepRange(1, Int8(2), 10))
5-element Vector{Int64}:
1
3
5
7
9
julia> typeof(StepRange(1, Int8(2), 10))
StepRange{Int64, Int8}
julia> typeof(1:3:6)
StepRange{Int64, Int64}
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L281-L306)###
`Base.UnitRange`Type
```
UnitRange{T<:Real}
```
A range parameterized by a `start` and `stop` of type `T`, filled with elements spaced by `1` from `start` until `stop` is exceeded. The syntax `a:b` with `a` and `b` both `Integer`s creates a `UnitRange`.
**Examples**
```
julia> collect(UnitRange(2.3, 5.2))
3-element Vector{Float64}:
2.3
3.3
4.3
julia> typeof(1:10)
UnitRange{Int64}
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L371-L389)###
`Base.LinRange`Type
```
LinRange{T,L}
```
A range with `len` linearly spaced elements between its `start` and `stop`. The size of the spacing is controlled by `len`, which must be an `Integer`.
**Examples**
```
julia> LinRange(1.5, 5.5, 9)
9-element LinRange{Float64, Int64}:
1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0,5.5
```
Compared to using [`range`](../math/index#Base.range), directly constructing a `LinRange` should have less overhead but won't try to correct for floating point errors:
```
julia> collect(range(-0.1, 0.3, length=5))
5-element Vector{Float64}:
-0.1
0.0
0.1
0.2
0.3
julia> collect(LinRange(-0.1, 0.3, 5))
5-element Vector{Float64}:
-0.1
-1.3877787807814457e-17
0.09999999999999999
0.19999999999999998
0.3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L500-L533)
[General Collections](#General-Collections)
--------------------------------------------
###
`Base.isempty`Function
```
isempty(collection) -> Bool
```
Determine whether a collection is empty (has no elements).
**Examples**
```
julia> isempty([])
true
julia> isempty([1 2 3])
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L771-L784)
```
isempty(condition)
```
Return `true` if no tasks are waiting on the condition, `false` otherwise.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/condition.jl#L159-L163)###
`Base.empty!`Function
```
empty!(collection) -> collection
```
Remove all elements from a `collection`.
**Examples**
```
julia> A = Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> empty!(A);
julia> A
Dict{String, Int64}()
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L247-L264)###
`Base.length`Function
```
length(collection) -> Integer
```
Return the number of elements in the collection.
Use [`lastindex`](#Base.lastindex) to get the last valid index of an indexable collection.
See also: [`size`](../arrays/index#Base.size), [`ndims`](../arrays/index#Base.ndims), [`eachindex`](../arrays/index#Base.eachindex).
**Examples**
```
julia> length(1:5)
5
julia> length([1, 2, 3, 4])
4
julia> length([1 2; 3 4])
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L242-L262)###
`Base.checked_length`Function
```
Base.checked_length(r)
```
Calculates `length(r)`, but may check for overflow errors where applicable when the result doesn't fit into `Union{Integer(eltype(r)),Int}`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/checked.jl#L353-L358)Fully implemented by:
* [`AbstractRange`](#Base.AbstractRange)
* [`UnitRange`](#Base.UnitRange)
* `Tuple`
* `Number`
* [`AbstractArray`](../arrays/index#Core.AbstractArray)
* [`BitSet`](#Base.BitSet)
* [`IdDict`](#Base.IdDict)
* [`Dict`](#Base.Dict)
* [`WeakKeyDict`](#Base.WeakKeyDict)
* `AbstractString`
* [`Set`](#Base.Set)
* [`NamedTuple`](../base/index#Core.NamedTuple)
[Iterable Collections](#Iterable-Collections)
----------------------------------------------
###
`Base.in`Function
```
in(item, collection) -> Bool
∈(item, collection) -> Bool
```
Determine whether an item is in the given collection, in the sense that it is [`==`](../math/index#Base.:==) to one of the values generated by iterating over the collection. Returns a `Bool` value, except if `item` is [`missing`](../base/index#Base.missing) or `collection` contains `missing` but not `item`, in which case `missing` is returned ([three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic), matching the behavior of [`any`](#Base.any-Tuple%7BAny%7D) and [`==`](../math/index#Base.:==)).
Some collections follow a slightly different definition. For example, [`Set`](#Base.Set)s check whether the item [`isequal`](../base/index#Base.isequal) to one of the elements. [`Dict`](#Base.Dict)s look for `key=>value` pairs, and the key is compared using [`isequal`](../base/index#Base.isequal). To test for the presence of a key in a dictionary, use [`haskey`](#Base.haskey) or `k in keys(dict)`. For these collections, the result is always a `Bool` and never `missing`.
To determine whether an item is not in a given collection, see [`:∉`](#Base.:%E2%88%89). You may also negate the `in` by doing `!(a in b)` which is logically similar to "not in".
When broadcasting with `in.(items, collection)` or `items .∈ collection`, both `item` and `collection` are broadcasted over, which is often not what is intended. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each value in collection `items` is `in` the value at the corresponding position in `collection`. To get a vector indicating whether each value in `items` is in `collection`, wrap `collection` in a tuple or a `Ref` like this: `in.(items, Ref(collection))` or `items .∈ Ref(collection)`.
**Examples**
```
julia> a = 1:3:20
1:3:19
julia> 4 in a
true
julia> 5 in a
false
julia> missing in [1, 2]
missing
julia> 1 in [2, missing]
missing
julia> 1 in [1, missing]
true
julia> missing in Set([1, 2])
false
julia> !(21 in a)
true
julia> !(19 in a)
false
julia> [1, 2] .∈ [2, 3]
2-element BitVector:
0
0
julia> [1, 2] .∈ ([2, 3],)
2-element BitVector:
0
1
```
See also: [`insorted`](../sort/index#Base.Sort.insorted), [`contains`](../strings/index#Base.contains), [`occursin`](../strings/index#Base.occursin), [`issubset`](#Base.issubset).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1279-L1349)###
`Base.:∉`Function
```
∉(item, collection) -> Bool
∌(collection, item) -> Bool
```
Negation of `∈` and `∋`, i.e. checks that `item` is not in `collection`.
When broadcasting with `items .∉ collection`, both `item` and `collection` are broadcasted over, which is often not what is intended. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each value in collection `items` is not in the value at the corresponding position in `collection`. To get a vector indicating whether each value in `items` is not in `collection`, wrap `collection` in a tuple or a `Ref` like this: `items .∉ Ref(collection)`.
**Examples**
```
julia> 1 ∉ 2:4
true
julia> 1 ∉ 1:3
false
julia> [1, 2] .∉ [2, 3]
2-element BitVector:
1
1
julia> [1, 2] .∉ ([2, 3],)
2-element BitVector:
1
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1352-L1384)###
`Base.eltype`Function
```
eltype(type)
```
Determine the type of the elements generated by iterating a collection of the given `type`. For dictionary types, this will be a `Pair{KeyType,ValType}`. The definition `eltype(x) = eltype(typeof(x))` is provided for convenience so that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types.
See also: [`keytype`](#Base.keytype), [`typeof`](../base/index#Core.typeof).
**Examples**
```
julia> eltype(fill(1f0, (2,2)))
Float32
julia> eltype(fill(0x1, (2,2)))
UInt8
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L184-L203)###
`Base.indexin`Function
```
indexin(a, b)
```
Return an array containing the first index in `b` for each value in `a` that is a member of `b`. The output array contains `nothing` wherever `a` is not a member of `b`.
See also: [`sortperm`](../sort/index#Base.sortperm), [`findfirst`](#).
**Examples**
```
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
julia> b = ['a', 'b', 'c'];
julia> indexin(a, b)
6-element Vector{Union{Nothing, Int64}}:
1
2
3
2
nothing
1
julia> indexin(b, a)
3-element Vector{Union{Nothing, Int64}}:
1
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2376-L2406)###
`Base.unique`Function
```
unique(itr)
```
Return an array containing only the unique elements of collection `itr`, as determined by [`isequal`](../base/index#Base.isequal), in the order that the first of each set of equivalent elements originally appears. The element type of the input is preserved.
See also: [`unique!`](#Base.unique!), [`allunique`](#Base.allunique), [`allequal`](#Base.allequal).
**Examples**
```
julia> unique([1, 2, 6, 2])
3-element Vector{Int64}:
1
2
6
julia> unique(Real[1, 1.0, 2])
2-element Vector{Real}:
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L110-L133)
```
unique(f, itr)
```
Returns an array containing one value from `itr` for each unique value produced by `f` applied to elements of `itr`.
**Examples**
```
julia> unique(x -> x^2, [1, -1, 3, -3, 4])
3-element Vector{Int64}:
1
3
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L183-L197)
```
unique(A::AbstractArray; dims::Int)
```
Return unique regions of `A` along dimension `dims`.
**Examples**
```
julia> A = map(isodd, reshape(Vector(1:8), (2,2,2)))
2×2×2 Array{Bool, 3}:
[:, :, 1] =
1 1
0 0
[:, :, 2] =
1 1
0 0
julia> unique(A)
2-element Vector{Bool}:
1
0
julia> unique(A, dims=2)
2×1×2 Array{Bool, 3}:
[:, :, 1] =
1
0
[:, :, 2] =
1
0
julia> unique(A, dims=3)
2×2×1 Array{Bool, 3}:
[:, :, 1] =
1 1
0 0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1612-L1650)###
`Base.unique!`Function
```
unique!(f, A::AbstractVector)
```
Selects one value from `A` for each unique value produced by `f` applied to elements of `A`, then return the modified A.
This method is available as of Julia 1.1.
**Examples**
```
julia> unique!(x -> x^2, [1, -1, 3, -3, 4])
3-element Vector{Int64}:
1
3
4
julia> unique!(n -> n%3, [5, 1, 8, 9, 3, 4, 10, 7, 2, 6])
3-element Vector{Int64}:
5
1
9
julia> unique!(iseven, [2, 3, 5, 7, 9])
2-element Vector{Int64}:
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L245-L273)
```
unique!(A::AbstractVector)
```
Remove duplicate items as determined by [`isequal`](../base/index#Base.isequal), then return the modified `A`. `unique!` will return the elements of `A` in the order that they occur. If you do not care about the order of the returned data, then calling `(sort!(A); unique!(A))` will be much more efficient as long as the elements of `A` can be sorted.
**Examples**
```
julia> unique!([1, 1, 1])
1-element Vector{Int64}:
1
julia> A = [7, 3, 2, 3, 7, 5];
julia> unique!(A)
4-element Vector{Int64}:
7
3
2
5
julia> B = [7, 6, 42, 6, 7, 42];
julia> sort!(B); # unique! is able to process sorted data much more efficiently.
julia> unique!(B)
3-element Vector{Int64}:
6
7
42
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L337-L370)###
`Base.allunique`Function
```
allunique(itr) -> Bool
```
Return `true` if all values from `itr` are distinct when compared with [`isequal`](../base/index#Base.isequal).
See also: [`unique`](#Base.unique), [`issorted`](../sort/index#Base.issorted), [`allequal`](#Base.allequal).
**Examples**
```
julia> a = [1; 2; 3]
3-element Vector{Int64}:
1
2
3
julia> allunique(a)
true
julia> allunique([a, a])
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L381-L402)###
`Base.allequal`Function
```
allequal(itr) -> Bool
```
Return `true` if all values from `itr` are equal when compared with [`isequal`](../base/index#Base.isequal).
See also: [`unique`](#Base.unique), [`allunique`](#Base.allunique).
The `allequal` function requires at least Julia 1.8.
**Examples**
```
julia> allequal([])
true
julia> allequal([1])
true
julia> allequal([1, 1])
true
julia> allequal([1, 2])
false
julia> allequal(Dict(:a => 1, :b => 1))
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L430-L457)###
`Base.reduce`Method
```
reduce(op, itr; [init])
```
Reduce the given collection `itr` with the given binary operator `op`. If provided, the initial value `init` must be a neutral element for `op` that will be returned for empty collections. It is unspecified whether `init` is used for non-empty collections.
For empty collections, providing `init` will be necessary, except for some special cases (e.g. when `op` is one of `+`, `*`, `max`, `min`, `&`, `|`) when Julia can determine the neutral element of `op`.
Reductions for certain commonly-used operators may have special implementations, and should be used instead: `maximum(itr)`, `minimum(itr)`, `sum(itr)`, `prod(itr)`, `any(itr)`, `all(itr)`.
The associativity of the reduction is implementation dependent. This means that you can't use non-associative operations like `-` because it is undefined whether `reduce(-,[1,2,3])` should be evaluated as `(1-2)-3` or `1-(2-3)`. Use [`foldl`](#Base.foldl-Tuple%7BAny,%20Any%7D) or [`foldr`](#Base.foldr-Tuple%7BAny,%20Any%7D) instead for guaranteed left or right associativity.
Some operations accumulate error. Parallelism will be easier if the reduction can be executed in groups. Future versions of Julia might change the algorithm. Note that the elements are not reordered if you use an ordered collection.
**Examples**
```
julia> reduce(*, [2; 3; 4])
24
julia> reduce(*, [2; 3; 4]; init=-1)
-24
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L450-L482)###
`Base.foldl`Method
```
foldl(op, itr; [init])
```
Like [`reduce`](#Base.reduce-Tuple%7BAny,%20Any%7D), but with guaranteed left associativity. If provided, the keyword argument `init` will be used exactly once. In general, it will be necessary to provide `init` to work with empty collections.
See also [`mapfoldl`](#Base.mapfoldl-Tuple%7BAny,%20Any,%20Any%7D), [`foldr`](#Base.foldr-Tuple%7BAny,%20Any%7D), [`accumulate`](../arrays/index#Base.accumulate).
**Examples**
```
julia> foldl(=>, 1:4)
((1 => 2) => 3) => 4
julia> foldl(=>, 1:4; init=0)
(((0 => 1) => 2) => 3) => 4
julia> accumulate(=>, (1,2,3,4))
(1, 1 => 2, (1 => 2) => 3, ((1 => 2) => 3) => 4)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L172-L192)###
`Base.foldr`Method
```
foldr(op, itr; [init])
```
Like [`reduce`](#Base.reduce-Tuple%7BAny,%20Any%7D), but with guaranteed right associativity. If provided, the keyword argument `init` will be used exactly once. In general, it will be necessary to provide `init` to work with empty collections.
**Examples**
```
julia> foldr(=>, 1:4)
1 => (2 => (3 => 4))
julia> foldr(=>, 1:4; init=0)
1 => (2 => (3 => (4 => 0)))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L221-L236)###
`Base.maximum`Function
```
maximum(f, itr; [init])
```
Returns the largest result of calling function `f` on each element of `itr`.
The value returned for empty `itr` can be specified by `init`. It must be a neutral element for `max` (i.e. which is less than or equal to any other element) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
**Examples**
```
julia> maximum(length, ["Julion", "Julia", "Jule"])
6
julia> maximum(length, []; init=-1)
-1
julia> maximum(sin, Real[]; init=-1.0) # good, since output of sin is >= -1
-1.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L673-L697)
```
maximum(itr; [init])
```
Returns the largest element in a collection.
The value returned for empty `itr` can be specified by `init`. It must be a neutral element for `max` (i.e. which is less than or equal to any other element) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
**Examples**
```
julia> maximum(-20.5:10)
9.5
julia> maximum([1,2,3])
3
julia> maximum(())
ERROR: MethodError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
[...]
julia> maximum((); init=-Inf)
-Inf
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L727-L756)
```
maximum(A::AbstractArray; dims)
```
Compute the maximum value of an array over the given dimensions. See also the [`max(a,b)`](../math/index#Base.max) function to take the maximum of two or more arguments, which can be applied elementwise to arrays via `max.(a,b)`.
See also: [`maximum!`](#Base.maximum!), [`extrema`](#Base.extrema), [`findmax`](#Base.findmax), [`argmax`](#Base.argmax).
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> maximum(A, dims=1)
1×2 Matrix{Int64}:
3 4
julia> maximum(A, dims=2)
2×1 Matrix{Int64}:
2
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L621-L646)
```
maximum(f, A::AbstractArray; dims)
```
Compute the maximum value by calling the function `f` on each element of an array over the given dimensions.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> maximum(abs2, A, dims=1)
1×2 Matrix{Int64}:
9 16
julia> maximum(abs2, A, dims=2)
2×1 Matrix{Int64}:
4
16
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L649-L671)###
`Base.maximum!`Function
```
maximum!(r, A)
```
Compute the maximum value of `A` over the singleton dimensions of `r`, and write results to `r`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> maximum!([1; 1], A)
2-element Vector{Int64}:
2
4
julia> maximum!([1 1], A)
1×2 Matrix{Int64}:
3 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L674-L695)###
`Base.minimum`Function
```
minimum(f, itr; [init])
```
Returns the smallest result of calling function `f` on each element of `itr`.
The value returned for empty `itr` can be specified by `init`. It must be a neutral element for `min` (i.e. which is greater than or equal to any other element) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
**Examples**
```
julia> minimum(length, ["Julion", "Julia", "Jule"])
4
julia> minimum(length, []; init=typemax(Int64))
9223372036854775807
julia> minimum(sin, Real[]; init=1.0) # good, since output of sin is <= 1
1.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L700-L724)
```
minimum(itr; [init])
```
Returns the smallest element in a collection.
The value returned for empty `itr` can be specified by `init`. It must be a neutral element for `min` (i.e. which is greater than or equal to any other element) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
**Examples**
```
julia> minimum(-20.5:10)
-20.5
julia> minimum([1,2,3])
1
julia> minimum([])
ERROR: MethodError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
[...]
julia> minimum([]; init=Inf)
Inf
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L759-L788)
```
minimum(A::AbstractArray; dims)
```
Compute the minimum value of an array over the given dimensions. See also the [`min(a,b)`](../math/index#Base.min) function to take the minimum of two or more arguments, which can be applied elementwise to arrays via `min.(a,b)`.
See also: [`minimum!`](#Base.minimum!), [`extrema`](#Base.extrema), [`findmin`](#Base.findmin), [`argmin`](#Base.argmin).
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> minimum(A, dims=1)
1×2 Matrix{Int64}:
1 2
julia> minimum(A, dims=2)
2×1 Matrix{Int64}:
1
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L698-L723)
```
minimum(f, A::AbstractArray; dims)
```
Compute the minimum value by calling the function `f` on each element of an array over the given dimensions.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> minimum(abs2, A, dims=1)
1×2 Matrix{Int64}:
1 4
julia> minimum(abs2, A, dims=2)
2×1 Matrix{Int64}:
1
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L726-L748)###
`Base.minimum!`Function
```
minimum!(r, A)
```
Compute the minimum value of `A` over the singleton dimensions of `r`, and write results to `r`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> minimum!([1; 1], A)
2-element Vector{Int64}:
1
3
julia> minimum!([1 1], A)
1×2 Matrix{Int64}:
1 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L751-L772)###
`Base.extrema`Function
```
extrema(itr; [init]) -> (mn, mx)
```
Compute both the minimum `mn` and maximum `mx` element in a single pass, and return them as a 2-tuple.
The value returned for empty `itr` can be specified by `init`. It must be a 2-tuple whose first and second elements are neutral elements for `min` and `max` respectively (i.e. which are greater/less than or equal to any other element). As a consequence, when `itr` is empty the returned `(mn, mx)` tuple will satisfy `mn ≥ mx`. When `init` is specified it may be used even for non-empty `itr`.
Keyword argument `init` requires Julia 1.8 or later.
**Examples**
```
julia> extrema(2:10)
(2, 10)
julia> extrema([9,pi,4.5])
(3.141592653589793, 9.0)
julia> extrema([]; init = (Inf, -Inf))
(Inf, -Inf)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L791-L817)
```
extrema(f, itr; [init]) -> (mn, mx)
```
Compute both the minimum `mn` and maximum `mx` of `f` applied to each element in `itr` and return them as a 2-tuple. Only one pass is made over `itr`.
The value returned for empty `itr` can be specified by `init`. It must be a 2-tuple whose first and second elements are neutral elements for `min` and `max` respectively (i.e. which are greater/less than or equal to any other element). It is used for non-empty collections. Note: it implies that, for empty `itr`, the returned value `(mn, mx)` satisfies `mn ≥ mx` even though for non-empty `itr` it satisfies `mn ≤ mx`. This is a "paradoxical" but yet expected result.
This method requires Julia 1.2 or later.
Keyword argument `init` requires Julia 1.8 or later.
**Examples**
```
julia> extrema(sin, 0:π)
(0.0, 0.9092974268256817)
julia> extrema(sin, Real[]; init = (1.0, -1.0)) # good, since -1 ≤ sin(::Real) ≤ 1
(1.0, -1.0)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L820-L847)
```
extrema(A::AbstractArray; dims) -> Array{Tuple}
```
Compute the minimum and maximum elements of an array over the given dimensions.
See also: [`minimum`](#Base.minimum), [`maximum`](#Base.maximum), [`extrema!`](#Base.extrema!).
**Examples**
```
julia> A = reshape(Vector(1:2:16), (2,2,2))
2×2×2 Array{Int64, 3}:
[:, :, 1] =
1 5
3 7
[:, :, 2] =
9 13
11 15
julia> extrema(A, dims = (1,2))
1×1×2 Array{Tuple{Int64, Int64}, 3}:
[:, :, 1] =
(1, 7)
[:, :, 2] =
(9, 15)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L775-L802)
```
extrema(f, A::AbstractArray; dims) -> Array{Tuple}
```
Compute the minimum and maximum of `f` applied to each element in the given dimensions of `A`.
This method requires Julia 1.2 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L805-L813)###
`Base.extrema!`Function
```
extrema!(r, A)
```
Compute the minimum and maximum value of `A` over the singleton dimensions of `r`, and write results to `r`.
This method requires Julia 1.8 or later.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> extrema!([(1, 1); (1, 1)], A)
2-element Vector{Tuple{Int64, Int64}}:
(1, 2)
(3, 4)
julia> extrema!([(1, 1);; (1, 1)], A)
1×2 Matrix{Tuple{Int64, Int64}}:
(1, 3) (2, 4)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L816-L840)###
`Base.argmax`Function
```
argmax(r::AbstractRange)
```
Ranges can have multiple maximal elements. In that case `argmax` will return a maximal index, but not necessarily the first one.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L847-L853)
```
argmax(f, domain)
```
Return a value `x` in the domain of `f` for which `f(x)` is maximised. If there are multiple maximal values for `f(x)` then the first one will be found.
`domain` must be a non-empty iterable.
Values are compared with `isless`.
This method requires Julia 1.7 or later.
See also [`argmin`](#Base.argmin), [`findmax`](#Base.findmax).
**Examples**
```
julia> argmax(abs, -10:5)
-10
julia> argmax(cos, 0:π/2:2π)
0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L980-L1003)
```
argmax(itr)
```
Return the index or key of the maximal element in a collection. If there are multiple maximal elements, then the first one will be returned.
The collection must not be empty.
Values are compared with `isless`.
See also: [`argmin`](#Base.argmin), [`findmax`](#Base.findmax).
**Examples**
```
julia> argmax([8, 0.1, -9, pi])
1
julia> argmax([1, 7, 7, 6])
2
julia> argmax([1, 7, 7, NaN])
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1006-L1029)
```
argmax(A; dims) -> indices
```
For an array input, return the indices of the maximum elements over the given dimensions. `NaN` is treated as greater than all other values except `missing`.
**Examples**
```
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> argmax(A, dims=1)
1×2 Matrix{CartesianIndex{2}}:
CartesianIndex(2, 1) CartesianIndex(2, 2)
julia> argmax(A, dims=2)
2×1 Matrix{CartesianIndex{2}}:
CartesianIndex(1, 2)
CartesianIndex(2, 2)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L1201-L1223)###
`Base.argmin`Function
```
argmin(r::AbstractRange)
```
Ranges can have multiple minimal elements. In that case `argmin` will return a minimal index, but not necessarily the first one.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L830-L836)
```
argmin(f, domain)
```
Return a value `x` in the domain of `f` for which `f(x)` is minimised. If there are multiple minimal values for `f(x)` then the first one will be found.
`domain` must be a non-empty iterable.
`NaN` is treated as less than all other values except `missing`.
This method requires Julia 1.7 or later.
See also [`argmax`](#Base.argmax), [`findmin`](#Base.findmin).
**Examples**
```
julia> argmin(sign, -10:5)
-10
julia> argmin(x -> -x^3 + x^2 - 10, -5:5)
5
julia> argmin(acos, 0:0.1:1)
1.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1032-L1058)
```
argmin(itr)
```
Return the index or key of the minimal element in a collection. If there are multiple minimal elements, then the first one will be returned.
The collection must not be empty.
`NaN` is treated as less than all other values except `missing`.
See also: [`argmax`](#Base.argmax), [`findmin`](#Base.findmin).
**Examples**
```
julia> argmin([8, 0.1, -9, pi])
3
julia> argmin([7, 1, 1, 6])
2
julia> argmin([7, 1, 1, NaN])
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1061-L1084)
```
argmin(A; dims) -> indices
```
For an array input, return the indices of the minimum elements over the given dimensions. `NaN` is treated as less than all other values except `missing`.
**Examples**
```
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> argmin(A, dims=1)
1×2 Matrix{CartesianIndex{2}}:
CartesianIndex(1, 1) CartesianIndex(1, 2)
julia> argmin(A, dims=2)
2×1 Matrix{CartesianIndex{2}}:
CartesianIndex(1, 1)
CartesianIndex(2, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L1176-L1198)###
`Base.findmax`Function
```
findmax(f, domain) -> (f(x), index)
```
Returns a pair of a value in the codomain (outputs of `f`) and the index of the corresponding value in the `domain` (inputs to `f`) such that `f(x)` is maximised. If there are multiple maximal points, then the first one will be returned.
`domain` must be a non-empty iterable.
Values are compared with `isless`.
This method requires Julia 1.7 or later.
**Examples**
```
julia> findmax(identity, 5:9)
(9, 5)
julia> findmax(-, 1:10)
(-1, 1)
julia> findmax(first, [(1, :a), (3, :b), (3, :c)])
(3, 2)
julia> findmax(cos, 0:π/2:2π)
(1.0, 1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L863-L892)
```
findmax(itr) -> (x, index)
```
Return the maximal element of the collection `itr` and its index or key. If there are multiple maximal elements, then the first one will be returned. Values are compared with `isless`.
See also: [`findmin`](#Base.findmin), [`argmax`](#Base.argmax), [`maximum`](#Base.maximum).
**Examples**
```
julia> findmax([8, 0.1, -9, pi])
(8.0, 1)
julia> findmax([1, 7, 7, 6])
(7, 2)
julia> findmax([1, 7, 7, NaN])
(NaN, 4)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L896-L917)
```
findmax(A; dims) -> (maxval, index)
```
For an array input, returns the value and index of the maximum over the given dimensions. `NaN` is treated as greater than all other values except `missing`.
**Examples**
```
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> findmax(A, dims=1)
([3.0 4.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(2, 2)])
julia> findmax(A, dims=2)
([2.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 2); CartesianIndex(2, 2);;])
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L1139-L1158)###
`Base.findmin`Function
```
findmin(f, domain) -> (f(x), index)
```
Returns a pair of a value in the codomain (outputs of `f`) and the index of the corresponding value in the `domain` (inputs to `f`) such that `f(x)` is minimised. If there are multiple minimal points, then the first one will be returned.
`domain` must be a non-empty iterable.
`NaN` is treated as less than all other values except `missing`.
This method requires Julia 1.7 or later.
**Examples**
```
julia> findmin(identity, 5:9)
(5, 1)
julia> findmin(-, 1:10)
(-10, 10)
julia> findmin(first, [(2, :a), (2, :b), (3, :c)])
(2, 1)
julia> findmin(cos, 0:π/2:2π)
(-1.0, 3)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L921-L951)
```
findmin(itr) -> (x, index)
```
Return the minimal element of the collection `itr` and its index or key. If there are multiple minimal elements, then the first one will be returned. `NaN` is treated as less than all other values except `missing`.
See also: [`findmax`](#Base.findmax), [`argmin`](#Base.argmin), [`minimum`](#Base.minimum).
**Examples**
```
julia> findmin([8, 0.1, -9, pi])
(-9.0, 3)
julia> findmin([1, 7, 7, 6])
(1, 1)
julia> findmin([1, 7, 7, NaN])
(NaN, 4)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L955-L976)
```
findmin(A; dims) -> (minval, index)
```
For an array input, returns the value and index of the minimum over the given dimensions. `NaN` is treated as less than all other values except `missing`.
**Examples**
```
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> findmin(A, dims=1)
([1.0 2.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(1, 2)])
julia> findmin(A, dims=2)
([1.0; 3.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L1092-L1111)###
`Base.findmax!`Function
```
findmax!(rval, rind, A) -> (maxval, index)
```
Find the maximum of `A` and the corresponding linear index along singleton dimensions of `rval` and `rind`, and store the results in `rval` and `rind`. `NaN` is treated as greater than all other values except `missing`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L1127-L1133)###
`Base.findmin!`Function
```
findmin!(rval, rind, A) -> (minval, index)
```
Find the minimum of `A` and the corresponding linear index along singleton dimensions of `rval` and `rind`, and store the results in `rval` and `rind`. `NaN` is treated as less than all other values except `missing`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L1080-L1086)###
`Base.sum`Function
```
sum(f, itr; [init])
```
Sum the results of calling function `f` on each element of `itr`.
The return type is `Int` for signed integers of less than system word size, and `UInt` for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for empty `itr` can be specified by `init`. It must be the additive identity (i.e. zero) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
**Examples**
```
julia> sum(abs2, [2; 3; 4])
29
```
Note the important difference between `sum(A)` and `reduce(+, A)` for arrays with small integer eltype:
```
julia> sum(Int8[100, 28])
128
julia> reduce(+, Int8[100, 28])
-128
```
In the former case, the integers are widened to system word size and therefore the result is 128. In the latter case, no such widening happens and integer overflow results in -128.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L491-L527)
```
sum(itr; [init])
```
Returns the sum of all elements in a collection.
The return type is `Int` for signed integers of less than system word size, and `UInt` for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for empty `itr` can be specified by `init`. It must be the additive identity (i.e. zero) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
See also: [`reduce`](#Base.reduce-Tuple%7BAny,%20Any%7D), [`mapreduce`](#Base.mapreduce-Tuple%7BAny,%20Any,%20Any%7D), [`count`](#Base.count), [`union`](#Base.union).
**Examples**
```
julia> sum(1:20)
210
julia> sum(1:20; init = 0.0)
210.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L530-L556)
```
sum(A::AbstractArray; dims)
```
Sum elements of an array over the given dimensions.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sum(A, dims=1)
1×2 Matrix{Int64}:
4 6
julia> sum(A, dims=2)
2×1 Matrix{Int64}:
3
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L475-L496)
```
sum(f, A::AbstractArray; dims)
```
Sum the results of calling function `f` on each element of an array over the given dimensions.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sum(abs2, A, dims=1)
1×2 Matrix{Int64}:
10 20
julia> sum(abs2, A, dims=2)
2×1 Matrix{Int64}:
5
25
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L499-L521)###
`Base.sum!`Function
```
sum!(r, A)
```
Sum elements of `A` over the singleton dimensions of `r`, and write results to `r`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sum!([1; 1], A)
2-element Vector{Int64}:
3
7
julia> sum!([1 1], A)
1×2 Matrix{Int64}:
4 6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L524-L545)###
`Base.prod`Function
```
prod(f, itr; [init])
```
Returns the product of `f` applied to each element of `itr`.
The return type is `Int` for signed integers of less than system word size, and `UInt` for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for empty `itr` can be specified by `init`. It must be the multiplicative identity (i.e. one) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
**Examples**
```
julia> prod(abs2, [2; 3; 4])
576
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L562-L583)
```
prod(itr; [init])
```
Returns the product of all elements of a collection.
The return type is `Int` for signed integers of less than system word size, and `UInt` for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for empty `itr` can be specified by `init`. It must be the multiplicative identity (i.e. one) as it is unspecified whether `init` is used for non-empty collections.
Keyword argument `init` requires Julia 1.6 or later.
See also: [`reduce`](#Base.reduce-Tuple%7BAny,%20Any%7D), [`cumprod`](../arrays/index#Base.cumprod), [`any`](#Base.any-Tuple%7BAny%7D).
**Examples**
```
julia> prod(1:5)
120
julia> prod(1:5; init = 1.0)
120.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L586-L612)
```
prod(A::AbstractArray; dims)
```
Multiply elements of an array over the given dimensions.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> prod(A, dims=1)
1×2 Matrix{Int64}:
3 8
julia> prod(A, dims=2)
2×1 Matrix{Int64}:
2
12
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L548-L569)
```
prod(f, A::AbstractArray; dims)
```
Multiply the results of calling the function `f` on each element of an array over the given dimensions.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> prod(abs2, A, dims=1)
1×2 Matrix{Int64}:
9 64
julia> prod(abs2, A, dims=2)
2×1 Matrix{Int64}:
4
144
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L572-L594)###
`Base.prod!`Function
```
prod!(r, A)
```
Multiply elements of `A` over the singleton dimensions of `r`, and write results to `r`.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> prod!([1; 1], A)
2-element Vector{Int64}:
2
12
julia> prod!([1 1], A)
1×2 Matrix{Int64}:
3 8
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L597-L618)###
`Base.any`Method
```
any(itr) -> Bool
```
Test whether any elements of a boolean collection are `true`, returning `true` as soon as the first `true` value in `itr` is encountered (short-circuiting). To short-circuit on `false`, use [`all`](#Base.all-Tuple%7BAny%7D).
If the input contains [`missing`](../base/index#Base.missing) values, return `missing` if all non-missing values are `false` (or equivalently, if the input contains no `true` value), following [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic).
See also: [`all`](#Base.all-Tuple%7BAny%7D), [`count`](#Base.count), [`sum`](#Base.sum), [`|`](#), , [`||`](#).
**Examples**
```
julia> a = [true,false,false,true]
4-element Vector{Bool}:
1
0
0
1
julia> any(a)
true
julia> any((println(i); v) for (i, v) in enumerate(a))
1
true
julia> any([missing, true])
true
julia> any([false, missing])
missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1089-L1124)###
`Base.any`Method
```
any(p, itr) -> Bool
```
Determine whether predicate `p` returns `true` for any elements of `itr`, returning `true` as soon as the first item in `itr` for which `p` returns `true` is encountered (short-circuiting). To short-circuit on `false`, use [`all`](#Base.all-Tuple%7BAny%7D).
If the input contains [`missing`](../base/index#Base.missing) values, return `missing` if all non-missing values are `false` (or equivalently, if the input contains no `true` value), following [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic).
**Examples**
```
julia> any(i->(4<=i<=6), [3,5,7])
true
julia> any(i -> (println(i); i > 3), 1:10)
1
2
3
4
true
julia> any(i -> i > 0, [1, missing])
true
julia> any(i -> i > 0, [-1, missing])
missing
julia> any(i -> i > 0, [-1, 0])
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1166-L1198)###
`Base.any!`Function
```
any!(r, A)
```
Test whether any values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`.
**Examples**
```
julia> A = [true false; true false]
2×2 Matrix{Bool}:
1 0
1 0
julia> any!([1; 1], A)
2-element Vector{Int64}:
1
1
julia> any!([1 1], A)
1×2 Matrix{Int64}:
1 0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L963-L985)###
`Base.all`Method
```
all(itr) -> Bool
```
Test whether all elements of a boolean collection are `true`, returning `false` as soon as the first `false` value in `itr` is encountered (short-circuiting). To short-circuit on `true`, use [`any`](#Base.any-Tuple%7BAny%7D).
If the input contains [`missing`](../base/index#Base.missing) values, return `missing` if all non-missing values are `true` (or equivalently, if the input contains no `false` value), following [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic).
See also: [`all!`](#Base.all!), [`any`](#Base.any-Tuple%7BAny%7D), [`count`](#Base.count), [`&`](../math/index#Base.:&), , [`&&`](../math/index#&&), [`allunique`](#Base.allunique).
**Examples**
```
julia> a = [true,false,false,true]
4-element Vector{Bool}:
1
0
0
1
julia> all(a)
false
julia> all((println(i); v) for (i, v) in enumerate(a))
1
2
false
julia> all([missing, false])
false
julia> all([true, missing])
missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1127-L1163)###
`Base.all`Method
```
all(p, itr) -> Bool
```
Determine whether predicate `p` returns `true` for all elements of `itr`, returning `false` as soon as the first item in `itr` for which `p` returns `false` is encountered (short-circuiting). To short-circuit on `true`, use [`any`](#Base.any-Tuple%7BAny%7D).
If the input contains [`missing`](../base/index#Base.missing) values, return `missing` if all non-missing values are `true` (or equivalently, if the input contains no `false` value), following [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic).
**Examples**
```
julia> all(i->(4<=i<=6), [4,5,6])
true
julia> all(i -> (println(i); i < 3), 1:10)
1
2
3
false
julia> all(i -> i > 0, [1, missing])
missing
julia> all(i -> i > 0, [-1, missing])
false
julia> all(i -> i > 0, [1, 2])
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1214-L1245)###
`Base.all!`Function
```
all!(r, A)
```
Test whether all values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`.
**Examples**
```
julia> A = [true false; true false]
2×2 Matrix{Bool}:
1 0
1 0
julia> all!([1; 1], A)
2-element Vector{Int64}:
0
0
julia> all!([1 1], A)
1×2 Matrix{Int64}:
1 0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L891-L912)###
`Base.count`Function
```
count([f=identity,] itr; init=0) -> Integer
```
Count the number of elements in `itr` for which the function `f` returns `true`. If `f` is omitted, count the number of `true` elements in `itr` (which should be a collection of boolean values). `init` optionally specifies the value to start counting from and therefore also determines the output type.
`init` keyword was added in Julia 1.6.
See also: [`any`](#Base.any-Tuple%7BAny%7D), [`sum`](#Base.sum).
**Examples**
```
julia> count(i->(4<=i<=6), [2,3,4,5,6])
3
julia> count([true, false, true, true])
3
julia> count(>(3), 1:7, init=0x03)
0x07
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L1268-L1292)
```
count(
pattern::Union{AbstractChar,AbstractString,AbstractPattern},
string::AbstractString;
overlap::Bool = false,
)
```
Return the number of matches for `pattern` in `string`. This is equivalent to calling `length(findall(pattern, string))` but more efficient.
If `overlap=true`, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from disjoint character ranges.
This method requires at least Julia 1.3.
Using a character as the pattern requires at least Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/regex.jl#L506-L524)
```
count([f=identity,] A::AbstractArray; dims=:)
```
Count the number of elements in `A` for which `f` returns `true` over the given dimensions.
`dims` keyword was added in Julia 1.5.
`init` keyword was added in Julia 1.6.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> count(<=(2), A, dims=1)
1×2 Matrix{Int64}:
1 1
julia> count(<=(2), A, dims=2)
2×1 Matrix{Int64}:
2
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reducedim.jl#L410-L438)###
`Base.foreach`Function
```
foreach(f, c...) -> Nothing
```
Call function `f` on each element of iterable `c`. For multiple iterable arguments, `f` is called elementwise, and iteration stops when any iterator is finished.
`foreach` should be used instead of [`map`](#Base.map) when the results of `f` are not needed, for example in `foreach(println, array)`.
**Examples**
```
julia> tri = 1:3:7; res = Int[];
julia> foreach(x -> push!(res, x^2), tri)
julia> res
3-element Vector{Int64}:
1
16
49
julia> foreach((x, y) -> println(x, " with ", y), tri, 'a':'z')
1 with a
4 with b
7 with c
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L2745-L2772)###
`Base.map`Function
```
map(f, c...) -> collection
```
Transform collection `c` by applying `f` to each element. For multiple collection arguments, apply `f` elementwise, and stop when when any of them is exhausted.
See also [`map!`](#Base.map!), [`foreach`](#Base.foreach), [`mapreduce`](#Base.mapreduce-Tuple%7BAny,%20Any,%20Any%7D), [`mapslices`](../arrays/index#Base.mapslices), [`zip`](../iterators/index#Base.Iterators.zip), [`Iterators.map`](../iterators/index#Base.Iterators.map).
**Examples**
```
julia> map(x -> x * 2, [1, 2, 3])
3-element Vector{Int64}:
2
4
6
julia> map(+, [1, 2, 3], [10, 20, 30, 400, 5000])
3-element Vector{Int64}:
11
22
33
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L2938-L2960)
```
map(f, A::AbstractArray...) -> N-array
```
When acting on multi-dimensional arrays of the same [`ndims`](../arrays/index#Base.ndims), they must all have the same [`axes`](#), and the answer will too.
See also [`broadcast`](../arrays/index#Base.Broadcast.broadcast), which allows mismatched sizes.
**Examples**
```
julia> map(//, [1 2; 3 4], [4 3; 2 1])
2×2 Matrix{Rational{Int64}}:
1//4 2//3
3//2 4//1
julia> map(+, [1 2; 3 4], zeros(2,1))
ERROR: DimensionMismatch
julia> map(+, [1 2; 3 4], [1,10,100,1000], zeros(3,1)) # iterates until 3rd is exhausted
3-element Vector{Float64}:
2.0
13.0
102.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L3030-L3054)###
`Base.map!`Function
```
map!(function, destination, collection...)
```
Like [`map`](#Base.map), but stores the result in `destination` rather than a new collection. `destination` must be at least as large as the smallest collection.
See also: [`map`](#Base.map), [`foreach`](#Base.foreach), [`zip`](../iterators/index#Base.Iterators.zip), [`copyto!`](../c/index#Base.copyto!).
**Examples**
```
julia> a = zeros(3);
julia> map!(x -> x * 2, a, [1, 2, 3]);
julia> a
3-element Vector{Float64}:
2.0
4.0
6.0
julia> map!(+, zeros(Int, 5), 100:999, 1:3)
5-element Vector{Int64}:
101
103
105
0
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L2995-L3023)
```
map!(f, values(dict::AbstractDict))
```
Modifies `dict` by transforming each value from `val` to `f(val)`. Note that the type of `dict` cannot be changed: if `f(val)` is not an instance of the value type of `dict` then it will be converted to the value type if possible and otherwise raise an error.
`map!(f, values(dict::AbstractDict))` requires Julia 1.2 or later.
**Examples**
```
julia> d = Dict(:a => 1, :b => 2)
Dict{Symbol, Int64} with 2 entries:
:a => 1
:b => 2
julia> map!(v -> v-1, values(d))
ValueIterator for a Dict{Symbol, Int64} with 2 entries. Values:
0
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L587-L609)###
`Base.mapreduce`Method
```
mapreduce(f, op, itrs...; [init])
```
Apply function `f` to each element(s) in `itrs`, and then reduce the result using the binary function `op`. If provided, `init` must be a neutral element for `op` that will be returned for empty collections. It is unspecified whether `init` is used for non-empty collections. In general, it will be necessary to provide `init` to work with empty collections.
[`mapreduce`](#Base.mapreduce-Tuple%7BAny,%20Any,%20Any%7D) is functionally equivalent to calling `reduce(op, map(f, itr); init=init)`, but will in general execute faster since no intermediate collection needs to be created. See documentation for [`reduce`](#Base.reduce-Tuple%7BAny,%20Any%7D) and [`map`](#Base.map).
`mapreduce` with multiple iterators requires Julia 1.2 or later.
**Examples**
```
julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9
14
```
The associativity of the reduction is implementation-dependent. Additionally, some implementations may reuse the return value of `f` for elements that appear multiple times in `itr`. Use [`mapfoldl`](#Base.mapfoldl-Tuple%7BAny,%20Any,%20Any%7D) or [`mapfoldr`](#Base.mapfoldr-Tuple%7BAny,%20Any,%20Any%7D) instead for guaranteed left or right associativity and invocation of `f` for every value.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L275-L301)###
`Base.mapfoldl`Method
```
mapfoldl(f, op, itr; [init])
```
Like [`mapreduce`](#Base.mapreduce-Tuple%7BAny,%20Any,%20Any%7D), but with guaranteed left associativity, as in [`foldl`](#Base.foldl-Tuple%7BAny,%20Any%7D). If provided, the keyword argument `init` will be used exactly once. In general, it will be necessary to provide `init` to work with empty collections.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L163-L169)###
`Base.mapfoldr`Method
```
mapfoldr(f, op, itr; [init])
```
Like [`mapreduce`](#Base.mapreduce-Tuple%7BAny,%20Any,%20Any%7D), but with guaranteed right associativity, as in [`foldr`](#Base.foldr-Tuple%7BAny,%20Any%7D). If provided, the keyword argument `init` will be used exactly once. In general, it will be necessary to provide `init` to work with empty collections.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reduce.jl#L211-L217)###
`Base.first`Function
```
first(coll)
```
Get the first element of an iterable collection. Return the start point of an [`AbstractRange`](#Base.AbstractRange) even if it is empty.
See also: [`only`](../iterators/index#Base.Iterators.only), [`firstindex`](#Base.firstindex), [`last`](#Base.last).
**Examples**
```
julia> first(2:2:10)
2
julia> first([1; 2; 3; 4])
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L406-L422)
```
first(itr, n::Integer)
```
Get the first `n` elements of the iterable collection `itr`, or fewer elements if `itr` is not long enough.
See also: [`startswith`](../strings/index#Base.startswith), [`Iterators.take`](../iterators/index#Base.Iterators.take).
This method requires at least Julia 1.6.
**Examples**
```
julia> first(["foo", "bar", "qux"], 2)
2-element Vector{String}:
"foo"
"bar"
julia> first(1:6, 10)
1:6
julia> first(Bool[], 1)
Bool[]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L429-L453)
```
first(s::AbstractString, n::Integer)
```
Get a string consisting of the first `n` characters of `s`.
**Examples**
```
julia> first("∀ϵ≠0: ϵ²>0", 0)
""
julia> first("∀ϵ≠0: ϵ²>0", 1)
"∀"
julia> first("∀ϵ≠0: ϵ²>0", 3)
"∀ϵ≠"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L641-L657)###
`Base.last`Function
```
last(coll)
```
Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling [`lastindex`](#Base.lastindex) to get the last index. Return the end point of an [`AbstractRange`](#Base.AbstractRange) even if it is empty.
See also [`first`](#Base.first), [`endswith`](../strings/index#Base.endswith).
**Examples**
```
julia> last(1:2:10)
9
julia> last([1; 2; 3; 4])
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L461-L478)
```
last(itr, n::Integer)
```
Get the last `n` elements of the iterable collection `itr`, or fewer elements if `itr` is not long enough.
This method requires at least Julia 1.6.
**Examples**
```
julia> last(["foo", "bar", "qux"], 2)
2-element Vector{String}:
"bar"
"qux"
julia> last(1:6, 10)
1:6
julia> last(Float64[], 1)
Float64[]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L481-L503)
```
last(s::AbstractString, n::Integer)
```
Get a string consisting of the last `n` characters of `s`.
**Examples**
```
julia> last("∀ϵ≠0: ϵ²>0", 0)
""
julia> last("∀ϵ≠0: ϵ²>0", 1)
"0"
julia> last("∀ϵ≠0: ϵ²>0", 3)
"²>0"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/basic.jl#L660-L676)###
`Base.front`Function
```
front(x::Tuple)::Tuple
```
Return a `Tuple` consisting of all but the last component of `x`.
See also: [`first`](#Base.first), [`tail`](#Base.tail).
**Examples**
```
julia> Base.front((1,2,3))
(1, 2)
julia> Base.front(())
ERROR: ArgumentError: Cannot call front on an empty tuple.
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/tuple.jl#L190-L205)###
`Base.tail`Function
```
tail(x::Tuple)::Tuple
```
Return a `Tuple` consisting of all but the first component of `x`.
See also: [`front`](#Base.front), [`rest`](#Base.rest), [`first`](#Base.first), [`Iterators.peel`](../iterators/index#Base.Iterators.peel).
**Examples**
```
julia> Base.tail((1,2,3))
(2, 3)
julia> Base.tail(())
ERROR: ArgumentError: Cannot call tail on an empty tuple.
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L235-L250)###
`Base.step`Function
```
step(r)
```
Get the step size of an [`AbstractRange`](#Base.AbstractRange) object.
**Examples**
```
julia> step(1:10)
1
julia> step(1:2:10)
2
julia> step(2.5:0.3:10.9)
0.3
julia> step(range(2.5, stop=10.9, length=85))
0.1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/range.jl#L658-L677)###
`Base.collect`Method
```
collect(collection)
```
Return an `Array` of all items in a collection or iterator. For dictionaries, returns `Pair{KeyType, ValType}`. If the argument is array-like or is an iterator with the [`HasShape`](#Base.IteratorSize) trait, the result will have the same shape and number of dimensions as the argument.
Used by comprehensions to turn a generator into an `Array`.
**Examples**
```
julia> collect(1:2:13)
7-element Vector{Int64}:
1
3
5
7
9
11
13
julia> [x^2 for x in 1:8 if isodd(x)]
4-element Vector{Int64}:
1
9
25
49
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L682-L711)###
`Base.collect`Method
```
collect(element_type, collection)
```
Return an `Array` with the given element type of all items in a collection or iterable. The result has the same shape and number of dimensions as `collection`.
**Examples**
```
julia> collect(Float64, 1:2:5)
3-element Vector{Float64}:
1.0
3.0
5.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L632-L646)###
`Base.filter`Function
```
filter(f, a)
```
Return a copy of collection `a`, removing elements for which `f` is `false`. The function `f` is passed one argument.
Support for `a` as a tuple requires at least Julia 1.4.
See also: [`filter!`](#Base.filter!), [`Iterators.filter`](../iterators/index#Base.Iterators.filter).
**Examples**
```
julia> a = 1:10
1:10
julia> filter(isodd, a)
5-element Vector{Int64}:
1
3
5
7
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2509-L2533)
```
filter(f, d::AbstractDict)
```
Return a copy of `d`, removing elements for which `f` is `false`. The function `f` is passed `key=>value` pairs.
**Examples**
```
julia> d = Dict(1=>"a", 2=>"b")
Dict{Int64, String} with 2 entries:
2 => "b"
1 => "a"
julia> filter(p->isodd(p.first), d)
Dict{Int64, String} with 1 entry:
1 => "a"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L450-L467)
```
filter(f, itr::SkipMissing{<:AbstractArray})
```
Return a vector similar to the array wrapped by the given `SkipMissing` iterator but with all missing elements and those for which `f` returns `false` removed.
This method requires Julia 1.2 or later.
**Examples**
```
julia> x = [1 2; missing 4]
2×2 Matrix{Union{Missing, Int64}}:
1 2
missing 4
julia> filter(isodd, skipmissing(x))
1-element Vector{Int64}:
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/missing.jl#L372-L392)###
`Base.filter!`Function
```
filter!(f, a)
```
Update collection `a`, removing elements for which `f` is `false`. The function `f` is passed one argument.
**Examples**
```
julia> filter!(isodd, Vector(1:10))
5-element Vector{Int64}:
1
3
5
7
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2563-L2579)
```
filter!(f, d::AbstractDict)
```
Update `d`, removing elements for which `f` is `false`. The function `f` is passed `key=>value` pairs.
**Example**
```
julia> d = Dict(1=>"a", 2=>"b", 3=>"c")
Dict{Int64, String} with 3 entries:
2 => "b"
3 => "c"
1 => "a"
julia> filter!(p->isodd(p.first), d)
Dict{Int64, String} with 2 entries:
3 => "c"
1 => "a"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L408-L427)###
`Base.replace`Method
```
replace(A, old_new::Pair...; [count::Integer])
```
Return a copy of collection `A` where, for each pair `old=>new` in `old_new`, all occurrences of `old` are replaced by `new`. Equality is determined using [`isequal`](../base/index#Base.isequal). If `count` is specified, then replace at most `count` occurrences in total.
The element type of the result is chosen using promotion (see [`promote_type`](../base/index#Base.promote_type)) based on the element type of `A` and on the types of the `new` values in pairs. If `count` is omitted and the element type of `A` is a `Union`, the element type of the result will not include singleton types which are replaced with values of a different type: for example, `Union{T,Missing}` will become `T` if `missing` is replaced.
See also [`replace!`](#Base.replace!), [`splice!`](#Base.splice!), [`delete!`](#Base.delete!), [`insert!`](#Base.insert!).
Version 1.7 is required to replace elements of a `Tuple`.
**Examples**
```
julia> replace([1, 2, 1, 3], 1=>0, 2=>4, count=2)
4-element Vector{Int64}:
0
4
1
3
julia> replace([1, missing], missing=>0)
2-element Vector{Int64}:
1
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L576-L610)###
`Base.replace`Method
```
replace(new::Function, A; [count::Integer])
```
Return a copy of `A` where each value `x` in `A` is replaced by `new(x)`. If `count` is specified, then replace at most `count` values in total (replacements being defined as `new(x) !== x`).
Version 1.7 is required to replace elements of a `Tuple`.
**Examples**
```
julia> replace(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
4-element Vector{Int64}:
2
2
6
4
julia> replace(Dict(1=>2, 3=>4)) do kv
first(kv) < 3 ? first(kv)=>3 : kv
end
Dict{Int64, Int64} with 2 entries:
3 => 4
1 => 3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L637-L663)###
`Base.replace!`Function
```
replace!(A, old_new::Pair...; [count::Integer])
```
For each pair `old=>new` in `old_new`, replace all occurrences of `old` in collection `A` by `new`. Equality is determined using [`isequal`](../base/index#Base.isequal). If `count` is specified, then replace at most `count` occurrences in total. See also [`replace`](#Base.replace-Tuple%7BAny,%20Vararg%7BPair%7D%7D).
**Examples**
```
julia> replace!([1, 2, 1, 3], 1=>0, 2=>4, count=2)
4-element Vector{Int64}:
0
4
1
3
julia> replace!(Set([1, 2, 3]), 1=>0)
Set{Int64} with 3 elements:
0
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L506-L530)
```
replace!(new::Function, A; [count::Integer])
```
Replace each element `x` in collection `A` by `new(x)`. If `count` is specified, then replace at most `count` values in total (replacements being defined as `new(x) !== x`).
**Examples**
```
julia> replace!(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
4-element Vector{Int64}:
2
2
6
4
julia> replace!(Dict(1=>2, 3=>4)) do kv
first(kv) < 3 ? first(kv)=>3 : kv
end
Dict{Int64, Int64} with 2 entries:
3 => 4
1 => 3
julia> replace!(x->2x, Set([3, 6]))
Set{Int64} with 2 elements:
6
12
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L544-L572)###
`Base.rest`Function
```
Base.rest(collection[, itr_state])
```
Generic function for taking the tail of `collection`, starting from a specific iteration state `itr_state`. Return a `Tuple`, if `collection` itself is a `Tuple`, a subtype of `AbstractVector`, if `collection` is an `AbstractArray`, a subtype of `AbstractString` if `collection` is an `AbstractString`, and an arbitrary iterator, falling back to `Iterators.rest(collection[, itr_state])`, otherwise.
Can be overloaded for user-defined collection types to customize the behavior of [slurping in assignments](../../manual/functions/index#destructuring-assignment), like `a, b... = collection`.
`Base.rest` requires at least Julia 1.6.
See also: [`first`](#Base.first), [`Iterators.rest`](../iterators/index#Base.Iterators.rest).
**Examples**
```
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> first, state = iterate(a)
(1, 2)
julia> first, Base.rest(a, state)
(1, [3, 2, 4])
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/tuple.jl#L101-L131)
[Indexable Collections](#Indexable-Collections)
------------------------------------------------
###
`Base.getindex`Function
```
getindex(collection, key...)
```
Retrieve the value(s) stored at the given key or index within a collection. The syntax `a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`.
See also [`get`](#Base.get), [`keys`](#Base.keys), [`eachindex`](../arrays/index#Base.eachindex).
**Examples**
```
julia> A = Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> getindex(A, "a")
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L902-L920)###
`Base.setindex!`Function
```
setindex!(collection, value, key...)
```
Store the given value at the given key or index within a collection. The syntax `a[i,j,...] = x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L958-L963)###
`Base.firstindex`Function
```
firstindex(collection) -> Integer
firstindex(collection, d) -> Integer
```
Return the first index of `collection`. If `d` is given, return the first index of `collection` along dimension `d`.
The syntaxes `A[begin]` and `A[1, begin]` lower to `A[firstindex(A)]` and `A[1, firstindex(A, 2)]`, respectively.
See also: [`first`](#Base.first), [`axes`](#), [`lastindex`](#Base.lastindex), [`nextind`](../strings/index#Base.nextind).
**Examples**
```
julia> firstindex([1,2,4])
1
julia> firstindex(rand(3,4,5), 2)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L381-L400)###
`Base.lastindex`Function
```
lastindex(collection) -> Integer
lastindex(collection, d) -> Integer
```
Return the last index of `collection`. If `d` is given, return the last index of `collection` along dimension `d`.
The syntaxes `A[end]` and `A[end, end]` lower to `A[lastindex(A)]` and `A[lastindex(A, 1), lastindex(A, 2)]`, respectively.
See also: [`axes`](#), [`firstindex`](#Base.firstindex), [`eachindex`](../arrays/index#Base.eachindex), [`prevind`](../strings/index#Base.prevind).
**Examples**
```
julia> lastindex([1,2,4])
3
julia> lastindex(rand(3,4,5), 2)
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L358-L377)Fully implemented by:
* [`Array`](../arrays/index#Core.Array)
* [`BitArray`](../arrays/index#Base.BitArray)
* [`AbstractArray`](../arrays/index#Core.AbstractArray)
* `SubArray`
Partially implemented by:
* [`AbstractRange`](#Base.AbstractRange)
* [`UnitRange`](#Base.UnitRange)
* `Tuple`
* `AbstractString`
* [`Dict`](#Base.Dict)
* [`IdDict`](#Base.IdDict)
* [`WeakKeyDict`](#Base.WeakKeyDict)
* [`NamedTuple`](../base/index#Core.NamedTuple)
[Dictionaries](#Dictionaries)
------------------------------
[`Dict`](#Base.Dict) is the standard dictionary. Its implementation uses [`hash`](../base/index#Base.hash) as the hashing function for the key, and [`isequal`](../base/index#Base.isequal) to determine equality. Define these two functions for custom types to override how they are stored in a hash table.
[`IdDict`](#Base.IdDict) is a special hash table where the keys are always object identities.
[`WeakKeyDict`](#Base.WeakKeyDict) is a hash table implementation where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table. Like `Dict` it uses `hash` for hashing and `isequal` for equality, unlike `Dict` it does not convert keys on insertion.
[`Dict`](#Base.Dict)s can be created by passing pair objects constructed with `=>` to a [`Dict`](#Base.Dict) constructor: `Dict("A"=>1, "B"=>2)`. This call will attempt to infer type information from the keys and values (i.e. this example creates a `Dict{String, Int64}`). To explicitly specify types use the syntax `Dict{KeyType,ValueType}(...)`. For example, `Dict{String,Int32}("A"=>1, "B"=>2)`.
Dictionaries may also be created with generators. For example, `Dict(i => f(i) for i = 1:10)`.
Given a dictionary `D`, the syntax `D[x]` returns the value of key `x` (if it exists) or throws an error, and `D[x] = y` stores the key-value pair `x => y` in `D` (replacing any existing value for the key `x`). Multiple arguments to `D[...]` are converted to tuples; for example, the syntax `D[x,y]` is equivalent to `D[(x,y)]`, i.e. it refers to the value keyed by the tuple `(x,y)`.
###
`Base.AbstractDict`Type
```
AbstractDict{K, V}
```
Supertype for dictionary-like types with keys of type `K` and values of type `V`. [`Dict`](#Base.Dict), [`IdDict`](#Base.IdDict) and other types are subtypes of this. An `AbstractDict{K, V}` should be an iterator of `Pair{K, V}`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L17-L23)###
`Base.Dict`Type
```
Dict([itr])
```
`Dict{K,V}()` constructs a hash table with keys of type `K` and values of type `V`. Keys are compared with [`isequal`](../base/index#Base.isequal) and hashed with [`hash`](../base/index#Base.hash).
Given a single iterable argument, constructs a [`Dict`](#Base.Dict) whose key-value pairs are taken from 2-tuples `(key,value)` generated by the argument.
**Examples**
```
julia> Dict([("A", 1), ("B", 2)])
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
```
Alternatively, a sequence of pair arguments may be passed.
```
julia> Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L52-L77)###
`Base.IdDict`Type
```
IdDict([itr])
```
`IdDict{K,V}()` constructs a hash table using [`objectid`](../base/index#Base.objectid) as hash and `===` as equality with keys of type `K` and values of type `V`.
See [`Dict`](#Base.Dict) for further help. In the example below, The `Dict` keys are all `isequal` and therefore get hashed the same, so they get overwritten. The `IdDict` hashes by object-id, and thus preserves the 3 different keys.
**Examples**
```
julia> Dict(true => "yes", 1 => "no", 1.0 => "maybe")
Dict{Real, String} with 1 entry:
1.0 => "maybe"
julia> IdDict(true => "yes", 1 => "no", 1.0 => "maybe")
IdDict{Any, String} with 3 entries:
true => "yes"
1.0 => "maybe"
1 => "no"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iddict.jl#L3-L25)###
`Base.WeakKeyDict`Type
```
WeakKeyDict([itr])
```
`WeakKeyDict()` constructs a hash table where the keys are weak references to objects which may be garbage collected even when referenced in a hash table.
See [`Dict`](#Base.Dict) for further help. Note, unlike [`Dict`](#Base.Dict), `WeakKeyDict` does not convert keys on insertion, as this would imply the key object was unreferenced anywhere before insertion.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/weakkeydict.jl#L5-L15)###
`Base.ImmutableDict`Type
```
ImmutableDict
```
`ImmutableDict` is a dictionary implemented as an immutable linked list, which is optimal for small dictionaries that are constructed over many individual insertions. Note that it is not possible to remove a value, although it can be partially overridden and hidden by inserting a new value with the same key.
```
ImmutableDict(KV::Pair)
```
Create a new entry in the `ImmutableDict` for a `key => value` pair
* use `(key => value) in dict` to see if this particular combination is in the properties set
* use `get(dict, key, default)` to retrieve the most recent value for a particular key
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L772-L787)###
`Base.haskey`Function
```
haskey(collection, key) -> Bool
```
Determine whether a collection has a mapping for a given `key`.
**Examples**
```
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> haskey(D, 'a')
true
julia> haskey(D, 'c')
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L550-L568)###
`Base.get`Function
```
get(collection, key, default)
```
Return the value stored for the given key, or the given default value if no mapping for the key is present.
For tuples and numbers, this function requires at least Julia 1.7.
**Examples**
```
julia> d = Dict("a"=>1, "b"=>2);
julia> get(d, "a", 3)
1
julia> get(d, "c", 3)
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L501-L520)
```
get(f::Function, collection, key)
```
Return the value stored for the given key, or if no mapping for the key is present, return `f()`. Use [`get!`](#Base.get!) to also store the default value in the dictionary.
This is intended to be called using `do` block syntax
```
get(dict, key) do
# default value calculated here
time()
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L528-L542)###
`Base.get!`Function
```
get!(collection, key, default)
```
Return the value stored for the given key, or if no mapping for the key is present, store `key => default`, and return `default`.
**Examples**
```
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
julia> get!(d, "a", 5)
1
julia> get!(d, "d", 4)
4
julia> d
Dict{String, Int64} with 4 entries:
"c" => 3
"b" => 2
"a" => 1
"d" => 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L412-L435)
```
get!(f::Function, collection, key)
```
Return the value stored for the given key, or if no mapping for the key is present, store `key => f()`, and return `f()`.
This is intended to be called using `do` block syntax.
**Examples**
```
julia> squares = Dict{Int, Int}();
julia> function get_square!(d, i)
get!(d, i) do
i^2
end
end
get_square! (generic function with 1 method)
julia> get_square!(squares, 2)
4
julia> squares
Dict{Int64, Int64} with 1 entry:
2 => 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L438-L464)###
`Base.getkey`Function
```
getkey(collection, key, default)
```
Return the key matching argument `key` if one exists in `collection`, otherwise return `default`.
**Examples**
```
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> getkey(D, 'a', 1)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> getkey(D, 'd', 'a')
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L572-L590)###
`Base.delete!`Function
```
delete!(collection, key)
```
Delete the mapping for the given key in a collection, if any, and return the collection.
**Examples**
```
julia> d = Dict("a"=>1, "b"=>2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> delete!(d, "b")
Dict{String, Int64} with 1 entry:
"a" => 1
julia> delete!(d, "b") # d is left unchanged
Dict{String, Int64} with 1 entry:
"a" => 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L655-L675)###
`Base.pop!`Method
```
pop!(collection, key[, default])
```
Delete and return the mapping for `key` if it exists in `collection`, otherwise return `default`, or throw an error if `default` is not specified.
**Examples**
```
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
julia> pop!(d, "a")
1
julia> pop!(d, "d")
ERROR: KeyError: key "d" not found
Stacktrace:
[...]
julia> pop!(d, "e", 4)
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L607-L628)###
`Base.keys`Function
```
keys(iterator)
```
For an iterator or collection that has keys and values (e.g. arrays and dictionaries), return an iterator over the keys.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L73-L78)###
`Base.values`Function
```
values(iterator)
```
For an iterator or collection that has keys and values, return an iterator over the values. This function simply returns its argument by default, since the elements of a general iterator are normally considered its "values".
**Examples**
```
julia> d = Dict("a"=>1, "b"=>2);
julia> values(d)
ValueIterator for a Dict{String, Int64} with 2 entries. Values:
2
1
julia> values([2])
1-element Vector{Int64}:
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L791-L812)
```
values(a::AbstractDict)
```
Return an iterator over all values in a collection. `collect(values(a))` returns an array of values. When the values are stored internally in a hash table, as is the case for `Dict`, the order in which they are returned may vary. But `keys(a)` and `values(a)` both iterate `a` and return the elements in the same order.
**Examples**
```
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> collect(values(D))
2-element Vector{Int64}:
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L107-L130)###
`Base.pairs`Function
```
pairs(IndexLinear(), A)
pairs(IndexCartesian(), A)
pairs(IndexStyle(A), A)
```
An iterator that accesses each element of the array `A`, returning `i => x`, where `i` is the index for the element and `x = A[i]`. Identical to `pairs(A)`, except that the style of index can be selected. Also similar to `enumerate(A)`, except `i` will be a valid index for `A`, while `enumerate` always counts from 1 regardless of the indices of `A`.
Specifying [`IndexLinear()`](../arrays/index#Base.IndexLinear) ensures that `i` will be an integer; specifying [`IndexCartesian()`](../arrays/index#Base.IndexCartesian) ensures that `i` will be a [`CartesianIndex`](../arrays/index#Base.IteratorsMD.CartesianIndex); specifying `IndexStyle(A)` chooses whichever has been defined as the native indexing style for array `A`.
Mutation of the bounds of the underlying array will invalidate this iterator.
**Examples**
```
julia> A = ["a" "d"; "b" "e"; "c" "f"];
julia> for (index, value) in pairs(IndexStyle(A), A)
println("$index $value")
end
1 a
2 b
3 c
4 d
5 e
6 f
julia> S = view(A, 1:2, :);
julia> for (index, value) in pairs(IndexStyle(S), S)
println("$index $value")
end
CartesianIndex(1, 1) a
CartesianIndex(2, 1) b
CartesianIndex(1, 2) d
CartesianIndex(2, 2) e
```
See also [`IndexStyle`](../arrays/index#Base.IndexStyle), [`axes`](#).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L189-L234)
```
pairs(collection)
```
Return an iterator over `key => value` pairs for any collection that maps a set of keys to a set of values. This includes arrays, where the keys are the array indices.
**Examples**
```
julia> a = Dict(zip(["a", "b", "c"], [1, 2, 3]))
Dict{String, Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1
julia> pairs(a)
Dict{String, Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1
julia> foreach(println, pairs(["a", "b", "c"]))
1 => "a"
2 => "b"
3 => "c"
julia> (;a=1, b=2, c=3) |> pairs |> collect
3-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 2
:c => 3
julia> (;a=1, b=2, c=3) |> collect
3-element Vector{Int64}:
1
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L133-L171)###
`Base.merge`Function
```
merge(d::AbstractDict, others::AbstractDict...)
```
Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed. See also [`mergewith`](#Base.mergewith) for custom handling of values with the same key.
**Examples**
```
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String, Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String, Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> merge(a, b)
Dict{String, Float64} with 3 entries:
"bar" => 4711.0
"baz" => 17.0
"foo" => 0.0
julia> merge(b, a)
Dict{String, Float64} with 3 entries:
"bar" => 42.0
"baz" => 17.0
"foo" => 0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L316-L349)
```
merge(a::NamedTuple, bs::NamedTuple...)
```
Construct a new named tuple by merging two or more existing ones, in a left-associative manner. Merging proceeds left-to-right, between pairs of named tuples, and so the order of fields present in both the leftmost and rightmost named tuples take the same position as they are found in the leftmost named tuple. However, values are taken from matching fields in the rightmost named tuple that contains that field. Fields present in only the rightmost named tuple of a pair are appended at the end. A fallback is implemented for when only a single named tuple is supplied, with signature `merge(a::NamedTuple)`.
Merging 3 or more `NamedTuple` requires at least Julia 1.1.
**Examples**
```
julia> merge((a=1, b=2, c=3), (b=4, d=5))
(a = 1, b = 4, c = 3, d = 5)
```
```
julia> merge((a=1, b=2), (b=3, c=(d=1,)), (c=(d=2,),))
(a = 1, b = 3, c = (d = 2,))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/namedtuple.jl#L239-L263)
```
merge(a::NamedTuple, iterable)
```
Interpret an iterable of key-value pairs as a named tuple, and perform a merge.
```
julia> merge((a=1, b=2, c=3), [:b=>4, :d=>5])
(a = 1, b = 4, c = 3, d = 5)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/namedtuple.jl#L289-L298)###
`Base.mergewith`Function
```
mergewith(combine, d::AbstractDict, others::AbstractDict...)
mergewith(combine)
merge(combine, d::AbstractDict, others::AbstractDict...)
```
Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. Values with the same key will be combined using the combiner function. The curried form `mergewith(combine)` returns the function `(args...) -> mergewith(combine, args...)`.
Method `merge(combine::Union{Function,Type}, args...)` as an alias of `mergewith(combine, args...)` is still available for backward compatibility.
`mergewith` requires Julia 1.5 or later.
**Examples**
```
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String, Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String, Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> mergewith(+, a, b)
Dict{String, Float64} with 3 entries:
"bar" => 4753.0
"baz" => 17.0
"foo" => 0.0
julia> ans == mergewith(+)(a, b)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L353-L391)###
`Base.merge!`Function
```
merge!(d::AbstractDict, others::AbstractDict...)
```
Update collection with pairs from the other collections. See also [`merge`](#Base.merge).
**Examples**
```
julia> d1 = Dict(1 => 2, 3 => 4);
julia> d2 = Dict(1 => 4, 4 => 5);
julia> merge!(d1, d2);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 4
1 => 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L197-L217)###
`Base.mergewith!`Function
```
mergewith!(combine, d::AbstractDict, others::AbstractDict...) -> d
mergewith!(combine)
merge!(combine, d::AbstractDict, others::AbstractDict...) -> d
```
Update collection with pairs from the other collections. Values with the same key will be combined using the combiner function. The curried form `mergewith!(combine)` returns the function `(args...) -> mergewith!(combine, args...)`.
Method `merge!(combine::Union{Function,Type}, args...)` as an alias of `mergewith!(combine, args...)` is still available for backward compatibility.
`mergewith!` requires Julia 1.5 or later.
**Examples**
```
julia> d1 = Dict(1 => 2, 3 => 4);
julia> d2 = Dict(1 => 4, 4 => 5);
julia> mergewith!(+, d1, d2);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 4
1 => 6
julia> mergewith!(-, d1, d1);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 0
3 => 0
1 => 0
julia> foldl(mergewith!(+), [d1, d2]; init=Dict{Int64, Int64}())
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 0
1 => 4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L227-L272)###
`Base.sizehint!`Function
```
sizehint!(s, n)
```
Suggest that collection `s` reserve capacity for at least `n` elements. This can improve performance.
**Notes on the performance model**
For types that support `sizehint!`,
1. `push!` and `append!` methods generally may (but are not required to) preallocate extra storage. For types implemented in `Base`, they typically do, using a heuristic optimized for a general use case.
2. `sizehint!` may control this preallocation. Again, it typically does this for types in `Base`.
3. `empty!` is nearly costless (and O(1)) for types that support this kind of preallocation.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1246-L1263)###
`Base.keytype`Function
```
keytype(T::Type{<:AbstractArray})
keytype(A::AbstractArray)
```
Return the key type of an array. This is equal to the `eltype` of the result of `keys(...)`, and is provided mainly for compatibility with the dictionary interface.
**Examples**
```
julia> keytype([1, 2, 3]) == Int
true
julia> keytype([1 2; 3 4])
CartesianIndex{2}
```
For arrays, this function requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L135-L154)
```
keytype(type)
```
Get the key type of a dictionary type. Behaves similarly to [`eltype`](#Base.eltype).
**Examples**
```
julia> keytype(Dict(Int32(1) => "foo"))
Int32
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L288-L298)###
`Base.valtype`Function
```
valtype(T::Type{<:AbstractArray})
valtype(A::AbstractArray)
```
Return the value type of an array. This is identical to `eltype` and is provided mainly for compatibility with the dictionary interface.
**Examples**
```
julia> valtype(["one", "two", "three"])
String
```
For arrays, this function requires at least Julia 1.2.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L162-L177)
```
valtype(type)
```
Get the value type of a dictionary type. Behaves similarly to [`eltype`](#Base.eltype).
**Examples**
```
julia> valtype(Dict(Int32(1) => "foo"))
String
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L302-L312)Fully implemented by:
* [`IdDict`](#Base.IdDict)
* [`Dict`](#Base.Dict)
* [`WeakKeyDict`](#Base.WeakKeyDict)
Partially implemented by:
* [`BitSet`](#Base.BitSet)
* [`Set`](#Base.Set)
* [`EnvDict`](../base/index#Base.EnvDict)
* [`Array`](../arrays/index#Core.Array)
* [`BitArray`](../arrays/index#Base.BitArray)
* [`ImmutableDict`](#Base.ImmutableDict)
* [`Iterators.Pairs`](#Base.Pairs)
[Set-Like Collections](#Set-Like-Collections)
----------------------------------------------
###
`Base.AbstractSet`Type
```
AbstractSet{T}
```
Supertype for set-like types whose elements are of type `T`. [`Set`](#Base.Set), [`BitSet`](#Base.BitSet) and other types are subtypes of this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L9-L14)###
`Base.Set`Type
```
Set([itr])
```
Construct a [`Set`](#Base.Set) of the values generated by the given iterable object, or an empty set. Should be used instead of [`BitSet`](#Base.BitSet) for sparse integer sets, or for sets of arbitrary objects.
See also: [`push!`](#Base.push!), [`empty!`](#Base.empty!), [`union!`](#Base.union!), [`in`](#Base.in).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/set.jl#L22-L30)###
`Base.BitSet`Type
```
BitSet([itr])
```
Construct a sorted set of `Int`s generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. If the set will be sparse (for example, holding a few very large integers), use [`Set`](#Base.Set) instead.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/bitset.jl#L21-L28)###
`Base.union`Function
```
union(s, itrs...)
∪(s, itrs...)
```
Construct an object containing all distinct elements from all of the arguments.
The first argument controls what kind of container is returned. If this is an array, it maintains the order in which elements first appear.
Unicode `∪` can be typed by writing `\cup` then pressing tab in the Julia REPL, and in many editors. This is an infix operator, allowing `s ∪ itr`.
See also [`unique`](#Base.unique), [`intersect`](#Base.intersect), [`isdisjoint`](#Base.isdisjoint), [`vcat`](../arrays/index#Base.vcat), [`Iterators.flatten`](../iterators/index#Base.Iterators.flatten).
**Examples**
```
julia> union([1, 2], [3])
3-element Vector{Int64}:
1
2
3
julia> union([4 2 3 4 4], 1:3, 3.0)
4-element Vector{Float64}:
4.0
2.0
3.0
1.0
julia> (0, 0.0) ∪ (-0.0, NaN)
3-element Vector{Real}:
0
-0.0
NaN
julia> union(Set([1, 2]), 2:3)
Set{Int64} with 3 elements:
2
3
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L13-L54)###
`Base.union!`Function
```
union!(s::Union{AbstractSet,AbstractVector}, itrs...)
```
Construct the [`union`](#Base.union) of passed in sets and overwrite `s` with the result. Maintain order with arrays.
**Examples**
```
julia> a = Set([3, 4, 5]);
julia> union!(a, 1:2:7);
julia> a
Set{Int64} with 5 elements:
5
4
7
3
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L62-L82)###
`Base.intersect`Function
```
intersect(s, itrs...)
∩(s, itrs...)
```
Construct the set containing those elements which appear in all of the arguments.
The first argument controls what kind of container is returned. If this is an array, it maintains the order in which elements first appear.
Unicode `∩` can be typed by writing `\cap` then pressing tab in the Julia REPL, and in many editors. This is an infix operator, allowing `s ∩ itr`.
See also [`setdiff`](#Base.setdiff), [`isdisjoint`](#Base.isdisjoint), [`issubset`](#Base.issubset), [`issetequal`](#Base.issetequal).
As of Julia 1.8 intersect returns a result with the eltype of the type-promoted eltypes of the two inputs
**Examples**
```
julia> intersect([1, 2, 3], [3, 4, 5])
1-element Vector{Int64}:
3
julia> intersect([1, 4, 4, 5, 6], [6, 4, 6, 7, 8])
2-element Vector{Int64}:
4
6
julia> intersect(1:16, 7:99)
7:16
julia> (0, 0.0) ∩ (-0.0, 0)
1-element Vector{Real}:
0
julia> intersect(Set([1, 2]), BitSet([2, 3]), 1.0:10.0)
Set{Float64} with 1 element:
2.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L110-L150)###
`Base.setdiff`Function
```
setdiff(s, itrs...)
```
Construct the set of elements in `s` but not in any of the iterables in `itrs`. Maintain order with arrays.
See also [`setdiff!`](#Base.setdiff!), [`union`](#Base.union) and [`intersect`](#Base.intersect).
**Examples**
```
julia> setdiff([1,2,3], [3,4,5])
2-element Vector{Int64}:
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L196-L211)###
`Base.setdiff!`Function
```
setdiff!(s, itrs...)
```
Remove from set `s` (in-place) each element of each iterable from `itrs`. Maintain order with arrays.
**Examples**
```
julia> a = Set([1, 3, 4, 5]);
julia> setdiff!(a, 1:2:6);
julia> a
Set{Int64} with 1 element:
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L215-L231)###
`Base.symdiff`Function
```
symdiff(s, itrs...)
```
Construct the symmetric difference of elements in the passed in sets. When `s` is not an `AbstractSet`, the order is maintained. Note that in this case the multiplicity of elements matters.
See also [`symdiff!`](#Base.symdiff!), [`setdiff`](#Base.setdiff), [`union`](#Base.union) and [`intersect`](#Base.intersect).
**Examples**
```
julia> symdiff([1,2,3], [3,4,5], [4,5,6])
3-element Vector{Int64}:
1
2
6
julia> symdiff([1,2,1], [2, 1, 2])
2-element Vector{Int64}:
1
2
julia> symdiff(unique([1,2,1]), unique([2, 1, 2]))
Int64[]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L246-L271)###
`Base.symdiff!`Function
```
symdiff!(s::Union{AbstractSet,AbstractVector}, itrs...)
```
Construct the symmetric difference of the passed in sets, and overwrite `s` with the result. When `s` is an array, the order is maintained. Note that in this case the multiplicity of elements matters.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L275-L281)###
`Base.intersect!`Function
```
intersect!(s::Union{AbstractSet,AbstractVector}, itrs...)
```
Intersect all passed in sets and overwrite `s` with the result. Maintain order with arrays.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L180-L185)###
`Base.issubset`Function
```
issubset(a, b) -> Bool
⊆(a, b) -> Bool
⊇(b, a) -> Bool
```
Determine whether every element of `a` is also in `b`, using [`in`](#Base.in).
See also [`⊊`](#Base.:%E2%8A%8A), [`⊈`](#Base.:%E2%8A%88), [`∩`](#Base.intersect), [`∪`](#Base.union), [`contains`](../strings/index#Base.contains).
**Examples**
```
julia> issubset([1, 2], [1, 2, 3])
true
julia> [1, 2, 3] ⊆ [1, 2]
false
julia> [1, 2, 3] ⊇ [1, 2]
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L300-L320)###
`Base.:⊈`Function
```
⊈(a, b) -> Bool
⊉(b, a) -> Bool
```
Negation of `⊆` and `⊇`, i.e. checks that `a` is not a subset of `b`.
See also [`issubset`](#Base.issubset) (`⊆`), [`⊊`](#Base.:%E2%8A%8A).
**Examples**
```
julia> (1, 2) ⊈ (2, 3)
true
julia> (1, 2) ⊈ (1, 2, 3)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L390-L406)###
`Base.:⊊`Function
```
⊊(a, b) -> Bool
⊋(b, a) -> Bool
```
Determines if `a` is a subset of, but not equal to, `b`.
See also [`issubset`](#Base.issubset) (`⊆`), [`⊈`](#Base.:%E2%8A%88).
**Examples**
```
julia> (1, 2) ⊊ (1, 2, 3)
true
julia> (1, 2) ⊊ (1, 2)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L363-L379)###
`Base.issetequal`Function
```
issetequal(a, b) -> Bool
```
Determine whether `a` and `b` have the same elements. Equivalent to `a ⊆ b && b ⊆ a` but more efficient when possible.
See also: [`isdisjoint`](#Base.isdisjoint), [`union`](#Base.union).
**Examples**
```
julia> issetequal([1, 2], [1, 2, 3])
false
julia> issetequal([1, 2], [2, 1])
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L414-L430)###
`Base.isdisjoint`Function
```
isdisjoint(a, b) -> Bool
```
Determine whether the collections `a` and `b` are disjoint. Equivalent to `isempty(a ∩ b)` but more efficient when possible.
See also: [`intersect`](#Base.intersect), [`isempty`](#Base.isempty), [`issetequal`](#Base.issetequal).
This function requires at least Julia 1.5.
**Examples**
```
julia> isdisjoint([1, 2], [2, 3, 4])
false
julia> isdisjoint([3, 1], [2, 4])
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractset.jl#L449-L468)Fully implemented by:
* [`BitSet`](#Base.BitSet)
* [`Set`](#Base.Set)
Partially implemented by:
* [`Array`](../arrays/index#Core.Array)
[Dequeues](#Dequeues)
----------------------
###
`Base.push!`Function
```
push!(collection, items...) -> collection
```
Insert one or more `items` in `collection`. If `collection` is an ordered container, the items are inserted at the end (in the given order).
**Examples**
```
julia> push!([1, 2, 3], 4, 5, 6)
6-element Vector{Int64}:
1
2
3
4
5
6
```
If `collection` is ordered, use [`append!`](#Base.append!) to add all the elements of another collection to it. The result of the preceding example is equivalent to `append!([1, 2, 3], [4, 5, 6])`. For `AbstractSet` objects, [`union!`](#Base.union!) can be used instead.
See [`sizehint!`](#Base.sizehint!) for notes about the performance model.
See also [`pushfirst!`](#Base.pushfirst!).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1027-L1052)###
`Base.pop!`Function
```
pop!(collection) -> item
```
Remove an item in `collection` and return it. If `collection` is an ordered container, the last item is returned; for unordered containers, an arbitrary element is returned.
See also: [`popfirst!`](#Base.popfirst!), [`popat!`](#Base.popat!), [`delete!`](#Base.delete!), [`deleteat!`](#Base.deleteat!), [`splice!`](#Base.splice!), and [`push!`](#Base.push!).
**Examples**
```
julia> A=[1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> pop!(A)
3
julia> A
2-element Vector{Int64}:
1
2
julia> S = Set([1, 2])
Set{Int64} with 2 elements:
2
1
julia> pop!(S)
2
julia> S
Set{Int64} with 1 element:
1
julia> pop!(Dict(1=>2))
1 => 2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1271-L1311)
```
pop!(collection, key[, default])
```
Delete and return the mapping for `key` if it exists in `collection`, otherwise return `default`, or throw an error if `default` is not specified.
**Examples**
```
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
julia> pop!(d, "a")
1
julia> pop!(d, "d")
ERROR: KeyError: key "d" not found
Stacktrace:
[...]
julia> pop!(d, "e", 4)
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/dict.jl#L607-L628)###
`Base.popat!`Function
```
popat!(a::Vector, i::Integer, [default])
```
Remove the item at the given `i` and return it. Subsequent items are shifted to fill the resulting gap. When `i` is not a valid index for `a`, return `default`, or throw an error if `default` is not specified.
See also: [`pop!`](#Base.pop!), [`popfirst!`](#Base.popfirst!), [`deleteat!`](#Base.deleteat!), [`splice!`](#Base.splice!).
This function is available as of Julia 1.5.
**Examples**
```
julia> a = [4, 3, 2, 1]; popat!(a, 2)
3
julia> a
3-element Vector{Int64}:
4
2
1
julia> popat!(a, 4, missing)
missing
julia> popat!(a, 4)
ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [4]
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1321-L1352)###
`Base.pushfirst!`Function
```
pushfirst!(collection, items...) -> collection
```
Insert one or more `items` at the beginning of `collection`.
This function is called `unshift` in many other programming languages.
**Examples**
```
julia> pushfirst!([1, 2, 3, 4], 5, 6)
6-element Vector{Int64}:
5
6
1
2
3
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1369-L1387)###
`Base.popfirst!`Function
```
popfirst!(collection) -> item
```
Remove the first `item` from `collection`.
This function is called `shift` in many other programming languages.
See also: [`pop!`](#Base.pop!), [`popat!`](#Base.popat!), [`delete!`](#Base.delete!).
**Examples**
```
julia> A = [1, 2, 3, 4, 5, 6]
6-element Vector{Int64}:
1
2
3
4
5
6
julia> popfirst!(A)
1
julia> A
5-element Vector{Int64}:
2
3
4
5
6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1395-L1426)###
`Base.insert!`Function
```
insert!(a::Vector, index::Integer, item)
```
Insert an `item` into `a` at the given `index`. `index` is the index of `item` in the resulting `a`.
See also: [`push!`](#Base.push!), [`replace`](#Base.replace-Tuple%7BAny,%20Vararg%7BPair%7D%7D), [`popat!`](#Base.popat!), [`splice!`](#Base.splice!).
**Examples**
```
julia> insert!(Any[1:6;], 3, "here")
7-element Vector{Any}:
1
2
"here"
3
4
5
6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1436-L1456)###
`Base.deleteat!`Function
```
deleteat!(a::Vector, i::Integer)
```
Remove the item at the given `i` and return the modified `a`. Subsequent items are shifted to fill the resulting gap.
See also: [`delete!`](#Base.delete!), [`popat!`](#Base.popat!), [`splice!`](#Base.splice!).
**Examples**
```
julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
5-element Vector{Int64}:
6
4
3
2
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1466-L1484)
```
deleteat!(a::Vector, inds)
```
Remove the items at the indices given by `inds`, and return the modified `a`. Subsequent items are shifted to fill the resulting gap.
`inds` can be either an iterator or a collection of sorted and unique integer indices, or a boolean vector of the same length as `a` with `true` indicating entries to delete.
**Examples**
```
julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)
3-element Vector{Int64}:
5
3
1
julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])
3-element Vector{Int64}:
5
3
1
julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
ERROR: ArgumentError: indices must be unique and sorted
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1503-L1531)###
`Base.keepat!`Function
```
keepat!(a::Vector, inds)
keepat!(a::BitVector, inds)
```
Remove the items at all the indices which are not given by `inds`, and return the modified `a`. Items which are kept are shifted to fill the resulting gaps.
`inds` must be an iterator of sorted and unique integer indices. See also [`deleteat!`](#Base.deleteat!).
This function is available as of Julia 1.7.
**Examples**
```
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
3-element Vector{Int64}:
6
4
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2596-L2618)
```
keepat!(a::Vector, m::AbstractVector{Bool})
keepat!(a::BitVector, m::AbstractVector{Bool})
```
The in-place version of logical indexing `a = a[m]`. That is, `keepat!(a, m)` on vectors of equal length `a` and `m` will remove all elements from `a` for which `m` at the corresponding index is `false`.
**Examples**
```
julia> a = [:a, :b, :c];
julia> keepat!(a, [true, false, true])
2-element Vector{Symbol}:
:a
:c
julia> a
2-element Vector{Symbol}:
:a
:c
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L2621-L2643)###
`Base.splice!`Function
```
splice!(a::Vector, index::Integer, [replacement]) -> item
```
Remove the item at the given index, and return the removed item. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.
See also: [`replace`](#Base.replace-Tuple%7BAny,%20Vararg%7BPair%7D%7D), [`delete!`](#Base.delete!), [`deleteat!`](#Base.deleteat!), [`pop!`](#Base.pop!), [`popat!`](#Base.popat!).
**Examples**
```
julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
2
julia> A
5-element Vector{Int64}:
6
5
4
3
1
julia> splice!(A, 5, -1)
1
julia> A
5-element Vector{Int64}:
6
5
4
3
-1
julia> splice!(A, 1, [-1, -2, -3])
6
julia> A
7-element Vector{Int64}:
-1
-2
-3
5
4
3
-1
```
To insert `replacement` before an index `n` without removing any items, use `splice!(collection, n:n-1, replacement)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1604-L1654)
```
splice!(a::Vector, indices, [replacement]) -> items
```
Remove items at specified indices, and return a collection containing the removed items. Subsequent items are shifted left to fill the resulting gaps. If specified, replacement values from an ordered collection will be spliced in place of the removed items; in this case, `indices` must be a `AbstractUnitRange`.
To insert `replacement` before an index `n` without removing any items, use `splice!(collection, n:n-1, replacement)`.
Prior to Julia 1.5, `indices` must always be a `UnitRange`.
Prior to Julia 1.8, `indices` must be a `UnitRange` if splicing in replacement values.
**Examples**
```
julia> A = [-1, -2, -3, 5, 4, 3, -1]; splice!(A, 4:3, 2)
Int64[]
julia> A
8-element Vector{Int64}:
-1
-2
-3
2
5
4
3
-1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1673-L1707)###
`Base.resize!`Function
```
resize!(a::Vector, n::Integer) -> Vector
```
Resize `a` to contain `n` elements. If `n` is smaller than the current collection length, the first `n` elements will be retained. If `n` is larger, the new elements are not guaranteed to be initialized.
**Examples**
```
julia> resize!([6, 5, 4, 3, 2, 1], 3)
3-element Vector{Int64}:
6
5
4
julia> a = resize!([6, 5, 4, 3, 2, 1], 8);
julia> length(a)
8
julia> a[1:6]
6-element Vector{Int64}:
6
5
4
3
2
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1203-L1232)###
`Base.append!`Function
```
append!(collection, collections...) -> collection.
```
For an ordered container `collection`, add the elements of each `collections` to the end of it.
Specifying multiple collections to be appended requires at least Julia 1.6.
**Examples**
```
julia> append!([1], [2, 3])
3-element Vector{Int64}:
1
2
3
julia> append!([1, 2, 3], [4, 5], [6])
6-element Vector{Int64}:
1
2
3
4
5
6
```
Use [`push!`](#Base.push!) to add individual items to `collection` which are not already themselves in another collection. The result of the preceding example is equivalent to `push!([1, 2, 3], 4, 5, 6)`.
See [`sizehint!`](#Base.sizehint!) for notes about the performance model.
See also [`vcat`](../arrays/index#Base.vcat) for vectors, [`union!`](#Base.union!) for sets, and [`prepend!`](#Base.prepend!) and [`pushfirst!`](#Base.pushfirst!) for the opposite order.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1069-L1104)###
`Base.prepend!`Function
```
prepend!(a::Vector, collections...) -> collection
```
Insert the elements of each `collections` to the beginning of `a`.
When `collections` specifies multiple collections, order is maintained: elements of `collections[1]` will appear leftmost in `a`, and so on.
Specifying multiple collections to be prepended requires at least Julia 1.6.
**Examples**
```
julia> prepend!([3], [1, 2])
3-element Vector{Int64}:
1
2
3
julia> prepend!([6], [1, 2], [3, 4, 5])
6-element Vector{Int64}:
1
2
3
4
5
6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L1135-L1163)Fully implemented by:
* `Vector` (a.k.a. 1-dimensional [`Array`](../arrays/index#Core.Array))
* `BitVector` (a.k.a. 1-dimensional [`BitArray`](../arrays/index#Base.BitArray))
[Utility Collections](#Utility-Collections)
--------------------------------------------
###
`Core.Pair`Type
```
Pair(x, y)
x => y
```
Construct a `Pair` object with type `Pair{typeof(x), typeof(y)}`. The elements are stored in the fields `first` and `second`. They can also be accessed via iteration (but a `Pair` is treated as a single "scalar" for broadcasting operations).
See also [`Dict`](#Base.Dict).
**Examples**
```
julia> p = "foo" => 7
"foo" => 7
julia> typeof(p)
Pair{String, Int64}
julia> p.first
"foo"
julia> for x in p
println(x)
end
foo
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pair.jl#L5-L32)###
`Base.Pairs`Type
```
Iterators.Pairs(values, keys) <: AbstractDict{eltype(keys), eltype(values)}
```
Transforms an indexable container into a Dictionary-view of the same data. Modifying the key-space of the underlying data may invalidate this object.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L26-L31)
| programming_docs |
julia C Interface C Interface
===========
###
`Base.@ccall`Macro
```
@ccall library.function_name(argvalue1::argtype1, ...)::returntype
@ccall function_name(argvalue1::argtype1, ...)::returntype
@ccall $function_pointer(argvalue1::argtype1, ...)::returntype
```
Call a function in a C-exported shared library, specified by `library.function_name`, where `library` is a string constant or literal. The library may be omitted, in which case the `function_name` is resolved in the current process. Alternatively, `@ccall` may also be used to call a function pointer `$function_pointer`, such as one returned by `dlsym`.
Each `argvalue` to `@ccall` is converted to the corresponding `argtype`, by automatic insertion of calls to `unsafe_convert(argtype, cconvert(argtype, argvalue))`. (See also the documentation for [`unsafe_convert`](#Base.unsafe_convert) and [`cconvert`](#Base.cconvert) for further details.) In most cases, this simply results in a call to `convert(argtype, argvalue)`.
**Examples**
```
@ccall strlen(s::Cstring)::Csize_t
```
This calls the C standard library function:
```
size_t strlen(char *)
```
with a Julia variable named `s`. See also `ccall`.
Varargs are supported with the following convention:
```
@ccall printf("%s = %d"::Cstring ; "foo"::Cstring, foo::Cint)::Cint
```
The semicolon is used to separate required arguments (of which there must be at least one) from variadic arguments.
Example using an external library:
```
# C signature of g_uri_escape_string:
# char *g_uri_escape_string(const char *unescaped, const char *reserved_chars_allowed, gboolean allow_utf8);
const glib = "libglib-2.0"
@ccall glib.g_uri_escape_string(my_uri::Cstring, ":/"::Cstring, true::Cint)::Cstring
```
The string literal could also be used directly before the function name, if desired `"libglib-2.0".g_uri_escape_string(...`
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L685-L732)###
`ccall`Keyword
```
ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)
ccall(function_name, returntype, (argtype1, ...), argvalue1, ...)
ccall(function_pointer, returntype, (argtype1, ...), argvalue1, ...)
```
Call a function in a C-exported shared library, specified by the tuple `(function_name, library)`, where each component is either a string or symbol. Instead of specifying a library, one can also use a `function_name` symbol or string, which is resolved in the current process. Alternatively, `ccall` may also be used to call a function pointer `function_pointer`, such as one returned by `dlsym`.
Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression.
Each `argvalue` to the `ccall` will be converted to the corresponding `argtype`, by automatic insertion of calls to `unsafe_convert(argtype, cconvert(argtype, argvalue))`. (See also the documentation for [`unsafe_convert`](#Base.unsafe_convert) and [`cconvert`](#Base.cconvert) for further details.) In most cases, this simply results in a call to `convert(argtype, argvalue)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1064-L1082)###
`Core.Intrinsics.cglobal`Function
```
cglobal((symbol, library) [, type=Cvoid])
```
Obtain a pointer to a global variable in a C-exported shared library, specified exactly as in [`ccall`](#ccall). Returns a `Ptr{Type}`, defaulting to `Ptr{Cvoid}` if no `Type` argument is supplied. The values can be read or written by [`unsafe_load`](#Base.unsafe_load) or [`unsafe_store!`](#Base.unsafe_store!), respectively.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L7-L16)###
`Base.@cfunction`Macro
```
@cfunction(callable, ReturnType, (ArgumentTypes...,)) -> Ptr{Cvoid}
@cfunction($callable, ReturnType, (ArgumentTypes...,)) -> CFunction
```
Generate a C-callable function pointer from the Julia function `callable` for the given type signature. To pass the return value to a `ccall`, use the argument type `Ptr{Cvoid}` in the signature.
Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression (although it can include a splat expression). And that these arguments will be evaluated in global scope during compile-time (not deferred until runtime). Adding a '$' in front of the function argument changes this to instead create a runtime closure over the local variable `callable` (this is not supported on all architectures).
See [manual section on ccall and cfunction usage](../../manual/calling-c-and-fortran-code/index#Calling-C-and-Fortran-Code).
**Examples**
```
julia> function foo(x::Int, y::Int)
return x + y
end
julia> @cfunction(foo, Int, (Int, Int))
Ptr{Cvoid} @0x000000001b82fcd0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L38-L63)###
`Base.CFunction`Type
```
CFunction struct
```
Garbage-collection handle for the return value from `@cfunction` when the first argument is annotated with '$'. Like all `cfunction` handles, it should be passed to `ccall` as a `Ptr{Cvoid}`, and will be converted automatically at the call site to the appropriate type.
See [`@cfunction`](#Base.@cfunction).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L19-L28)###
`Base.unsafe_convert`Function
```
unsafe_convert(T, x)
```
Convert `x` to a C argument of type `T` where the input `x` must be the return value of `cconvert(T, ...)`.
In cases where [`convert`](../base/index#Base.convert) would need to take a Julia object and turn it into a `Ptr`, this function should be used to define and perform that conversion.
Be careful to ensure that a Julia reference to `x` exists as long as the result of this function will be used. Accordingly, the argument `x` to this function should never be an expression, only a variable name or field reference. For example, `x=a.b.c` is acceptable, but `x=[a,b,c]` is not.
The `unsafe` prefix on this function indicates that using the result of this function after the `x` argument to this function is no longer accessible to the program may cause undefined behavior, including program corruption or segfaults, at any later time.
See also [`cconvert`](#Base.cconvert)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L34-L54)###
`Base.cconvert`Function
```
cconvert(T,x)
```
Convert `x` to a value to be passed to C code as type `T`, typically by calling `convert(T, x)`.
In cases where `x` cannot be safely converted to `T`, unlike [`convert`](../base/index#Base.convert), `cconvert` may return an object of a type different from `T`, which however is suitable for [`unsafe_convert`](#Base.unsafe_convert) to handle. The result of this function should be kept valid (for the GC) until the result of [`unsafe_convert`](#Base.unsafe_convert) is not needed anymore. This can be used to allocate memory that will be accessed by the `ccall`. If multiple objects need to be allocated, a tuple of the objects can be used as return value.
Neither `convert` nor `cconvert` should take a Julia object and turn it into a `Ptr`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L396-L409)###
`Base.unsafe_load`Function
```
unsafe_load(p::Ptr{T}, i::Integer=1)
```
Load a value of type `T` from the address of the `i`th element (1-indexed) starting at `p`. This is equivalent to the C expression `p[i-1]`.
The `unsafe` prefix on this function indicates that no validation is performed on the pointer `p` to ensure that it is valid. Incorrect usage may segfault your program or return garbage answers, in the same manner as C.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L95-L104)###
`Base.unsafe_store!`Function
```
unsafe_store!(p::Ptr{T}, x, i::Integer=1)
```
Store a value of type `T` to the address of the `i`th element (1-indexed) starting at `p`. This is equivalent to the C expression `p[i-1] = x`.
The `unsafe` prefix on this function indicates that no validation is performed on the pointer `p` to ensure that it is valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L107-L116)###
`Base.unsafe_copyto!`Method
```
unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)
```
Copy `N` elements from a source pointer to a destination, with no checking. The size of an element is determined by the type of the pointers.
The `unsafe` prefix on this function indicates that no validation is performed on the pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L228-L237)###
`Base.unsafe_copyto!`Method
```
unsafe_copyto!(dest::Array, do, src::Array, so, N)
```
Copy `N` elements from a source array to a destination, starting at offset `so` in the source and `do` in the destination (1-indexed).
The `unsafe` prefix on this function indicates that no validation is performed to ensure that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in the same manner as C.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L270-L279)###
`Base.copyto!`Function
```
copyto!(dest::AbstractMatrix, src::UniformScaling)
```
Copies a [`UniformScaling`](../../stdlib/linearalgebra/index#LinearAlgebra.UniformScaling) onto a matrix.
In Julia 1.0 this method only supported a square destination matrix. Julia 1.1. added support for a rectangular matrix.
```
copyto!(dest, do, src, so, N)
```
Copy `N` elements from collection `src` starting at offset `so`, to array `dest` starting at offset `do`. Return `dest`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L310-L315)
```
copyto!(dest::AbstractArray, src) -> dest
```
Copy all elements from collection `src` to array `dest`, whose length must be greater than or equal to the length `n` of `src`. The first `n` elements of `dest` are overwritten, the other elements are left untouched.
See also [`copy!`](../arrays/index#Base.copy!), [`copy`](../base/index#Base.copy).
**Examples**
```
julia> x = [1., 0., 3., 0., 5.];
julia> y = zeros(7);
julia> copyto!(y, x);
julia> y
7-element Vector{Float64}:
1.0
0.0
3.0
0.0
5.0
0.0
0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractarray.jl#L983-L1010)
```
copyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest
```
Copy the block of `src` in the range of `Rsrc` to the block of `dest` in the range of `Rdest`. The sizes of the two regions must match.
**Examples**
```
julia> A = zeros(5, 5);
julia> B = [1 2; 3 4];
julia> Ainds = CartesianIndices((2:3, 2:3));
julia> Binds = CartesianIndices(B);
julia> copyto!(A, Ainds, B, Binds)
5×5 Matrix{Float64}:
0.0 0.0 0.0 0.0 0.0
0.0 1.0 2.0 0.0 0.0
0.0 3.0 4.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/multidimensional.jl#L1133-L1157)###
`Base.pointer`Function
```
pointer(array [, index])
```
Get the native address of an array or string, optionally at a given location `index`.
This function is "unsafe". Be careful to ensure that a Julia reference to `array` exists as long as this pointer will be used. The [`GC.@preserve`](../base/index#Base.GC.@preserve) macro should be used to protect the `array` argument from garbage collection within a given block of code.
Calling [`Ref(array[, index])`](#Core.Ref) is generally preferable to this function as it guarantees validity.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L172-L183)###
`Base.unsafe_wrap`Method
```
unsafe_wrap(Array, pointer::Ptr{T}, dims; own = false)
```
Wrap a Julia `Array` object around the data at the address given by `pointer`, without making a copy. The pointer element type `T` determines the array element type. `dims` is either an integer (for a 1d array) or a tuple of the array dimensions. `own` optionally specifies whether Julia should take ownership of the memory, calling `free` on the pointer when the array is no longer referenced.
This function is labeled "unsafe" because it will crash if `pointer` is not a valid memory address to data of the requested length.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L70-L81)###
`Base.pointer_from_objref`Function
```
pointer_from_objref(x)
```
Get the memory address of a Julia object as a `Ptr`. The existence of the resulting `Ptr` will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the `Ptr` will be used.
This function may not be called on immutable objects, since they do not have stable memory addresses.
See also [`unsafe_pointer_to_objref`](#Base.unsafe_pointer_to_objref).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L132-L143)###
`Base.unsafe_pointer_to_objref`Function
```
unsafe_pointer_to_objref(p::Ptr)
```
Convert a `Ptr` to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this is not the case, undefined behavior results, hence this function is considered "unsafe" and should be used with care.
See also [`pointer_from_objref`](#Base.pointer_from_objref).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L121-L129)###
`Base.disable_sigint`Function
```
disable_sigint(f::Function)
```
Disable Ctrl-C handler during execution of a function on the current task, for calling external code that may call julia code that is not interrupt safe. Intended to be called using `do` block syntax as follows:
```
disable_sigint() do
# interrupt-unsafe code
...
end
```
This is not needed on worker threads (`Threads.threadid() != 1`) since the `InterruptException` will only be delivered to the master thread. External functions that do not call julia code or julia runtime automatically disable sigint during their execution.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L454-L470)###
`Base.reenable_sigint`Function
```
reenable_sigint(f::Function)
```
Re-enable Ctrl-C handler during execution of a function. Temporarily reverses the effect of [`disable_sigint`](#Base.disable_sigint).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L479-L484)###
`Base.exit_on_sigint`Function
```
exit_on_sigint(on::Bool)
```
Set `exit_on_sigint` flag of the julia runtime. If `false`, Ctrl-C (SIGINT) is capturable as [`InterruptException`](../base/index#Core.InterruptException) in `try` block. This is the default behavior in REPL, any code run via `-e` and `-E` and in Julia script run with `-i` option.
If `true`, `InterruptException` is not thrown by Ctrl-C. Running code upon such event requires [`atexit`](../base/index#Base.atexit). This is the default behavior in Julia script run without `-i` option.
Function `exit_on_sigint` requires at least Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L493-L507)###
`Base.systemerror`Function
```
systemerror(sysfunc[, errno::Cint=Libc.errno()])
systemerror(sysfunc, iftrue::Bool)
```
Raises a `SystemError` for `errno` with the descriptive string `sysfunc` if `iftrue` is `true`
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L169-L174)###
`Base.windowserror`Function
```
windowserror(sysfunc[, code::UInt32=Libc.GetLastError()])
windowserror(sysfunc, iftrue::Bool)
```
Like [`systemerror`](#Base.systemerror), but for Windows API functions that use [`GetLastError`](../libc/index#Base.Libc.GetLastError) to return an error code instead of setting [`errno`](../libc/index#Base.Libc.errno).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L183-L189)###
`Core.Ptr`Type
```
Ptr{T}
```
A memory address referring to data of type `T`. However, there is no guarantee that the memory is actually valid, or that it actually represents data of the specified type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/pointer.jl#L3-L8)###
`Core.Ref`Type
```
Ref{T}
```
An object that safely references data of type `T`. This type is guaranteed to point to valid, Julia-allocated memory of the correct type. The underlying data is protected from freeing by the garbage collector as long as the `Ref` itself is referenced.
In Julia, `Ref` objects are dereferenced (loaded or stored) with `[]`.
Creation of a `Ref` to a value `x` of type `T` is usually written `Ref(x)`. Additionally, for creating interior pointers to containers (such as Array or Ptr), it can be written `Ref(a, i)` for creating a reference to the `i`-th element of `a`.
`Ref{T}()` creates a reference to a value of type `T` without initialization. For a bitstype `T`, the value will be whatever currently resides in the memory allocated. For a non-bitstype `T`, the reference will be undefined and attempting to dereference it will result in an error, "UndefRefError: access to undefined reference".
To check if a `Ref` is an undefined reference, use [`isassigned(ref::RefValue)`](#Base.isassigned-Tuple%7BBase.RefValue%7D). For example, `isassigned(Ref{T}())` is `false` if `T` is not a bitstype. If `T` is a bitstype, `isassigned(Ref{T}())` will always be true.
When passed as a `ccall` argument (either as a `Ptr` or `Ref` type), a `Ref` object will be converted to a native pointer to the data it references. For most `T`, or when converted to a `Ptr{Cvoid}`, this is a pointer to the object data. When `T` is an `isbits` type, this value may be safely mutated, otherwise mutation is strictly undefined behavior.
As a special case, setting `T = Any` will instead cause the creation of a pointer to the reference itself when converted to a `Ptr{Any}` (a `jl_value_t const* const*` if T is immutable, else a `jl_value_t *const *`). When converted to a `Ptr{Cvoid}`, it will still return a pointer to the data region as for any other `T`.
A `C_NULL` instance of `Ptr` can be passed to a `ccall` `Ref` argument to initialize it.
**Use in broadcasting**
`Ref` is sometimes used in broadcasting in order to treat the referenced values as a scalar.
**Examples**
```
julia> Ref(5)
Base.RefValue{Int64}(5)
julia> isa.(Ref([1,2,3]), [Array, Dict, Int]) # Treat reference values as scalar during broadcasting
3-element BitVector:
1
0
0
julia> Ref{Function}() # Undefined reference to a non-bitstype, Function
Base.RefValue{Function}(#undef)
julia> try
Ref{Function}()[] # Dereferencing an undefined reference will result in an error
catch e
println(e)
end
UndefRefError()
julia> Ref{Int64}()[]; # A reference to a bitstype refers to an undetermined value if not given
julia> isassigned(Ref{Int64}()) # A reference to a bitstype is always assigned
true
julia> Ref{Int64}(0)[] == 0 # Explicitly give a value for a bitstype reference
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/refpointer.jl#L3-L72)###
`Base.isassigned`Method
```
isassigned(ref::RefValue) -> Bool
```
Test whether the given [`Ref`](#Core.Ref) is associated with a value. This is always true for a [`Ref`](#Core.Ref) of a bitstype object. Return `false` if the reference is undefined.
**Examples**
```
julia> ref = Ref{Function}()
Base.RefValue{Function}(#undef)
julia> isassigned(ref)
false
julia> ref[] = (foobar(x) = x)
foobar (generic function with 1 method)
julia> isassigned(ref)
true
julia> isassigned(Ref{Int}())
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/refvalue.jl#L11-L35)###
`Base.Cchar`Type
```
Cchar
```
Equivalent to the native `char` c-type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L86-L90)###
`Base.Cuchar`Type
```
Cuchar
```
Equivalent to the native `unsigned char` c-type ([`UInt8`](../numbers/index#Core.UInt8)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L6-L10)###
`Base.Cshort`Type
```
Cshort
```
Equivalent to the native `signed short` c-type ([`Int16`](../numbers/index#Core.Int16)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L14-L18)###
`Base.Cstring`Type
```
Cstring
```
A C-style string composed of the native character type [`Cchar`](#Base.Cchar)s. `Cstring`s are NUL-terminated. For C-style strings composed of the native wide character type, see [`Cwstring`](#Base.Cwstring). For more information about string interopability with C, see the [manual](../../manual/calling-c-and-fortran-code/index#man-bits-types).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L138-L147)###
`Base.Cushort`Type
```
Cushort
```
Equivalent to the native `unsigned short` c-type ([`UInt16`](../numbers/index#Core.UInt16)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L22-L26)###
`Base.Cint`Type
```
Cint
```
Equivalent to the native `signed int` c-type ([`Int32`](../numbers/index#Core.Int32)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L30-L34)###
`Base.Cuint`Type
```
Cuint
```
Equivalent to the native `unsigned int` c-type ([`UInt32`](../numbers/index#Core.UInt32)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L38-L42)###
`Base.Clong`Type
```
Clong
```
Equivalent to the native `signed long` c-type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L104-L108)###
`Base.Culong`Type
```
Culong
```
Equivalent to the native `unsigned long` c-type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L111-L115)###
`Base.Clonglong`Type
```
Clonglong
```
Equivalent to the native `signed long long` c-type ([`Int64`](../numbers/index#Core.Int64)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L86-L90)###
`Base.Culonglong`Type
```
Culonglong
```
Equivalent to the native `unsigned long long` c-type ([`UInt64`](../numbers/index#Core.UInt64)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L94-L98)###
`Base.Cintmax_t`Type
```
Cintmax_t
```
Equivalent to the native `intmax_t` c-type ([`Int64`](../numbers/index#Core.Int64)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L70-L74)###
`Base.Cuintmax_t`Type
```
Cuintmax_t
```
Equivalent to the native `uintmax_t` c-type ([`UInt64`](../numbers/index#Core.UInt64)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L78-L82)###
`Base.Csize_t`Type
```
Csize_t
```
Equivalent to the native `size_t` c-type (`UInt`).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L54-L58)###
`Base.Cssize_t`Type
```
Cssize_t
```
Equivalent to the native `ssize_t` c-type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L62-L66)###
`Base.Cptrdiff_t`Type
```
Cptrdiff_t
```
Equivalent to the native `ptrdiff_t` c-type (`Int`).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L46-L50)###
`Base.Cwchar_t`Type
```
Cwchar_t
```
Equivalent to the native `wchar_t` c-type ([`Int32`](../numbers/index#Core.Int32)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L118-L122)###
`Base.Cwstring`Type
```
Cwstring
```
A C-style string composed of the native wide character type [`Cwchar_t`](#Base.Cwchar_t)s. `Cwstring`s are NUL-terminated. For C-style strings composed of the native character type, see [`Cstring`](#Base.Cstring). For more information about string interopability with C, see the [manual](../../manual/calling-c-and-fortran-code/index#man-bits-types).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/c.jl#L125-L135)###
`Base.Cfloat`Type
```
Cfloat
```
Equivalent to the native `float` c-type ([`Float32`](../numbers/index#Core.Float32)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L102-L106)###
`Base.Cdouble`Type
```
Cdouble
```
Equivalent to the native `double` c-type ([`Float64`](../numbers/index#Core.Float64)).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ctypes.jl#L110-L114)
[LLVM Interface](#LLVM-Interface)
==================================
###
`Core.Intrinsics.llvmcall`Function
```
llvmcall(fun_ir::String, returntype, Tuple{argtype1, ...}, argvalue1, ...)
llvmcall((mod_ir::String, entry_fn::String), returntype, Tuple{argtype1, ...}, argvalue1, ...)
llvmcall((mod_bc::Vector{UInt8}, entry_fn::String), returntype, Tuple{argtype1, ...}, argvalue1, ...)
```
Call the LLVM code provided in the first argument. There are several ways to specify this first argument:
* as a literal string, representing function-level IR (similar to an LLVM `define` block), with arguments are available as consecutive unnamed SSA variables (%0, %1, etc.);
* as a 2-element tuple, containing a string of module IR and a string representing the name of the entry-point function to call;
* as a 2-element tuple, but with the module provided as an `Vector{UINt8}` with bitcode.
Note that contrary to `ccall`, the argument types must be specified as a tuple type, and not a tuple of types. All types, as well as the LLVM code, should be specified as literals, and not as variables or expressions (it may be necessary to use `@eval` to generate these literals).
See `test/llvmcall.jl` for usage examples.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1085-L1105)
| programming_docs |
julia Essentials Essentials
==========
[Introduction](#Introduction)
------------------------------
Julia Base contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.
Some general notes:
* To use module functions, use `import Module` to import the module, and `Module.fn(x)` to use the functions.
* Alternatively, `using Module` will import all exported `Module` functions into the current namespace.
* By convention, function names ending with an exclamation point (`!`) modify their arguments. Some functions have both modifying (e.g., `sort!`) and non-modifying (`sort`) versions.
The behaviors of `Base` and standard libraries are stable as defined in [SemVer](https://semver.org/) only if they are documented; i.e., included in the [Julia documentation](https://docs.julialang.org/) and not marked as unstable. See [API FAQ](../../manual/faq/index#man-api) for more information.
[Getting Around](#Getting-Around)
----------------------------------
###
`Base.exit`Function
```
exit(code=0)
```
Stop the program with an exit code. The default exit code is zero, indicating that the program completed successfully. In an interactive session, `exit()` can be called with the keyboard shortcut `^D`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L21-L27)###
`Base.atexit`Function
```
atexit(f)
```
Register a zero-argument function `f()` to be called at process exit. `atexit()` hooks are called in last in first out (LIFO) order and run before object finalizers.
Exit hooks are allowed to call `exit(n)`, in which case Julia will exit with exit code `n` (instead of the original exit code). If more than one exit hook calls `exit(n)`, then Julia will exit with the exit code corresponding to the last called exit hook that calls `exit(n)`. (Because exit hooks are called in LIFO order, "last called" is equivalent to "first registered".)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L354-L365)###
`Base.isinteractive`Function
```
isinteractive() -> Bool
```
Determine whether Julia is running an interactive session.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L35-L39)###
`Base.summarysize`Function
```
Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int
```
Compute the amount of memory, in bytes, used by all unique objects reachable from the argument.
**Keyword Arguments**
* `exclude`: specifies the types of objects to exclude from the traversal.
* `chargeall`: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.
See also [`sizeof`](#Base.sizeof-Tuple%7BType%7D).
**Examples**
```
julia> Base.summarysize(1.0)
8
julia> Base.summarysize(Ref(rand(100)))
848
julia> sizeof(Ref(rand(100)))
8
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/summarysize.jl#L11-L34)###
`Base.require`Function
```
require(into::Module, module::Symbol)
```
This function is part of the implementation of [`using`](#using) / [`import`](#import), if a module is not already defined in `Main`. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).
Loads a source file, in the context of the `Main` module, on every active node, searching standard locations for files. `require` is considered a top-level operation, so it sets the current `include` path but does not use it to search for files (see help for [`include`](#Base.include)). This function is typically used to load library code, and is implicitly called by `using` to load packages.
When searching for files, `require` first looks for package code in the global array [`LOAD_PATH`](../constants/index#Base.LOAD_PATH). `require` is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.
For more details regarding code loading, see the manual sections on [modules](../../manual/modules/index#modules) and [parallel computing](../../manual/distributed-computing/index#code-availability).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1122-L1142)###
`Base.compilecache`Function
```
Base.compilecache(module::PkgId)
```
Creates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored in `DEPOT_PATH[1]/compiled`. See [Module initialization and precompilation](../../manual/modules/index#Module-initialization-and-precompilation) for important notes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1629-L1636)###
`Base.__precompile__`Function
```
__precompile__(isprecompilable::Bool)
```
Specify whether the file calling this function is precompilable, defaulting to `true`. If a module or file is *not* safely precompilable, it should call `__precompile__(false)` in order to throw an error if Julia attempts to precompile it.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1105-L1111)###
`Base.include`Function
```
Base.include([mapexpr::Function,] [m::Module,] path::AbstractString)
```
Evaluate the contents of the input source file in the global scope of module `m`. Every module (except those defined with [`baremodule`](#baremodule)) has its own definition of `include` omitting the `m` argument, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to `include` will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.
The optional first argument `mapexpr` can be used to transform the included code before it is evaluated: for each parsed expression `expr` in `path`, the `include` function actually evaluates `mapexpr(expr)`. If it is omitted, `mapexpr` defaults to [`identity`](#Base.identity).
Julia 1.5 is required for passing the `mapexpr` argument.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1457-L1474)###
`Base.MainInclude.include`Function
```
include([mapexpr::Function,] path::AbstractString)
```
Evaluate the contents of the input source file in the global scope of the containing module. Every module (except those defined with `baremodule`) has its own definition of `include`, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to `include` will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files. The argument `path` is normalized using [`normpath`](../file/index#Base.Filesystem.normpath) which will resolve relative path tokens such as `..` and convert `/` to the appropriate path separator.
The optional first argument `mapexpr` can be used to transform the included code before it is evaluated: for each parsed expression `expr` in `path`, the `include` function actually evaluates `mapexpr(expr)`. If it is omitted, `mapexpr` defaults to [`identity`](#Base.identity).
Use [`Base.include`](#Base.include) to evaluate a file into another module.
Julia 1.5 is required for passing the `mapexpr` argument.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/client.jl#L490-L511)###
`Base.include_string`Function
```
include_string([mapexpr::Function,] m::Module, code::AbstractString, filename::AbstractString="string")
```
Like [`include`](#Base.include), except reads code from the given string rather than from a file.
The optional first argument `mapexpr` can be used to transform the included code before it is evaluated: for each parsed expression `expr` in `code`, the `include_string` function actually evaluates `mapexpr(expr)`. If it is omitted, `mapexpr` defaults to [`identity`](#Base.identity).
Julia 1.5 is required for passing the `mapexpr` argument.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1398-L1409)###
`Base.include_dependency`Function
```
include_dependency(path::AbstractString)
```
In a module, declare that the file specified by `path` (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if this file changes.
This is only needed if your module depends on a file that is not used via [`include`](#Base.include). It has no effect outside of compilation.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1080-L1089)###
`Base.which`Method
```
which(f, types)
```
Returns the method of `f` (a `Method` object) that would be called for arguments of the given `types`.
If `types` is an abstract type, then the method that would be called by `invoke` is returned.
See also: [`parentmodule`](#Base.parentmodule), and `@which` and `@edit` in [`InteractiveUtils`](../../stdlib/interactiveutils/index#man-interactive-utils).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1399-L1407)###
`Base.methods`Function
```
methods(f, [types], [module])
```
Return the method table for `f`.
If `types` is specified, return an array of methods whose types match. If `module` is specified, return an array of methods defined in that module. A list of modules can also be specified as an array.
At least Julia 1.4 is required for specifying a module.
See also: [`which`](#Base.which-Tuple%7BAny,%20Any%7D) and `@which`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L967-L980)###
`Base.@show`Macro
```
@show exs...
```
Prints one or more expressions, and their results, to `stdout`, and returns the last result.
See also: [`show`](#), [`@info`](../../stdlib/logging/index#man-logging), [`println`](../io-network/index#Base.println).
**Examples**
```
julia> x = @show 1+2
1 + 2 = 3
3
julia> @show x^2 x/2;
x ^ 2 = 9
x / 2 = 1.5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L1025-L1042)###
`ans`Keyword
```
ans
```
A variable referring to the last computed value, automatically set at the interactive prompt.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1259-L1263)###
`Base.active_project`Function
```
active_project()
```
Return the path of the active `Project.toml` file. See also [`Base.set_active_project`](#Base.set_active_project).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L285-L289)###
`Base.set_active_project`Function
```
set_active_project(projfile::Union{AbstractString,Nothing})
```
Set the active `Project.toml` file to `projfile`. See also [`Base.active_project`](#Base.active_project).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/initdefs.jl#L314-L318)
[Keywords](#Keywords)
----------------------
This is the list of reserved keywords in Julia: `baremodule`, `begin`, `break`, `catch`, `const`, `continue`, `do`, `else`, `elseif`, `end`, `export`, `false`, `finally`, `for`, `function`, `global`, `if`, `import`, `let`, `local`, `macro`, `module`, `quote`, `return`, `struct`, `true`, `try`, `using`, `while`. Those keywords are not allowed to be used as variable names.
The following two-word sequences are reserved: `abstract type`, `mutable struct`, `primitive type`. However, you can create variables with names: `abstract`, `mutable`, `primitive` and `type`.
Finally: `where` is parsed as an infix operator for writing parametric method and type definitions; `in` and `isa` are parsed as infix operators; and `outer` is parsed as a keyword when used to modify the scope of a variable in an iteration specification of a `for` loop or `generator` expression. Creation of variables named `where`, `in`, `isa` or `outer` is allowed though.
###
`module`Keyword
```
module
```
`module` declares a [`Module`](#Core.Module), which is a separate global variable workspace. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting). Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with somebody else’s. See the [manual section about modules](../../manual/modules/index#modules) for more details.
**Examples**
```
module Foo
import Base.show
export MyType, foo
struct MyType
x
end
bar(x) = 2x
foo(a::MyType) = bar(a.x) + 1
show(io::IO, a::MyType) = print(io, "MyType $(a.x)")
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L78-L103)###
`export`Keyword
```
export
```
`export` is used within modules to tell Julia which functions should be made available to the user. For example: `export foo` makes the name `foo` available when [`using`](#using) the module. See the [manual section about modules](../../manual/modules/index#modules) for details.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L52-L59)###
`import`Keyword
```
import
```
`import Foo` will load the module or package `Foo`. Names from the imported `Foo` module can be accessed with dot syntax (e.g. `Foo.foo` to access the name `foo`). See the [manual section about modules](../../manual/modules/index#modules) for details.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L42-L49)###
`using`Keyword
```
using
```
`using Foo` will load the module or package `Foo` and make its [`export`](#export)ed names available for direct use. Names can also be used via dot syntax (e.g. `Foo.foo` to access the name `foo`), whether they are `export`ed or not. See the [manual section about modules](../../manual/modules/index#modules) for details.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L32-L39)###
`baremodule`Keyword
```
baremodule
```
`baremodule` declares a module that does not contain `using Base` or local definitions of [`eval`](#Base.MainInclude.eval) and [`include`](#Base.include). It does still import `Core`. In other words,
```
module Mod
...
end
```
is equivalent to
```
baremodule Mod
using Base
eval(x) = Core.eval(Mod, x)
include(p) = Base.include(Mod, p)
...
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L129-L157)###
`function`Keyword
```
function
```
Functions are defined with the `function` keyword:
```
function add(a, b)
return a + b
end
```
Or the short form notation:
```
add(a, b) = a + b
```
The use of the [`return`](#return) keyword is exactly the same as in other languages, but is often optional. A function without an explicit `return` statement will return the last expression in the function body.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L611-L630)###
`macro`Keyword
```
macro
```
`macro` defines a method for inserting generated code into a program. A macro maps a sequence of argument expressions to a returned expression, and the resulting expression is substituted directly into the program at the point where the macro is invoked. Macros are a way to run generated code without calling [`eval`](#Base.MainInclude.eval), since the generated code instead simply becomes part of the surrounding program. Macro arguments may include expressions, literal values, and symbols. Macros can be defined for variable number of arguments (varargs), but do not accept keyword arguments. Every macro also implicitly gets passed the arguments `__source__`, which contains the line number and file name the macro is called from, and `__module__`, which is the module the macro is expanded in.
**Examples**
```
julia> macro sayhello(name)
return :( println("Hello, ", $name, "!") )
end
@sayhello (macro with 1 method)
julia> @sayhello "Charlie"
Hello, Charlie!
julia> macro saylots(x...)
return :( println("Say: ", $(x...)) )
end
@saylots (macro with 1 method)
julia> @saylots "hey " "there " "friend"
Say: hey there friend
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L178-L211)###
`return`Keyword
```
return
```
`return x` causes the enclosing function to exit early, passing the given value `x` back to its caller. `return` by itself with no value is equivalent to `return nothing` (see [`nothing`](../constants/index#Core.nothing)).
```
function compare(a, b)
a == b && return "equal to"
a < b ? "less than" : "greater than"
end
```
In general you can place a `return` statement anywhere within a function body, including within deeply nested loops or conditionals, but be careful with `do` blocks. For example:
```
function test1(xs)
for x in xs
iseven(x) && return 2x
end
end
function test2(xs)
map(xs) do x
iseven(x) && return 2x
x
end
end
```
In the first example, the return breaks out of `test1` as soon as it hits an even number, so `test1([5,6,7])` returns `12`.
You might expect the second example to behave the same way, but in fact the `return` there only breaks out of the *inner* function (inside the `do` block) and gives a value back to `map`. `test2([5,6,7])` then returns `[5,12,7]`.
When used in a top-level expression (i.e. outside any function), `return` causes the entire current top-level expression to terminate early.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L659-L699)###
`do`Keyword
```
do
```
Create an anonymous function and pass it as the first argument to a function call. For example:
```
map(1:10) do x
2x
end
```
is equivalent to `map(x->2x, 1:10)`.
Use multiple arguments like so:
```
map(1:10, 11:20) do x, y
x + y
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L926-L948)###
`begin`Keyword
```
begin
```
`begin...end` denotes a block of code.
```
begin
println("Hello, ")
println("World!")
end
```
Usually `begin` will not be necessary, since keywords such as [`function`](#function) and [`let`](#let) implicitly begin blocks of code. See also [`;`](#;).
`begin` may also be used when indexing to represent the first index of a collection or the first index of a dimension of an array.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> A[begin, :]
2-element Array{Int64,1}:
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1108-L1138)###
`end`Keyword
```
end
```
`end` marks the conclusion of a block of expressions, for example [`module`](#module), [`struct`](#struct), [`mutable struct`](#mutable%20struct), [`begin`](#begin), [`let`](#let), [`for`](#for) etc.
`end` may also be used when indexing to represent the last index of a collection or the last index of a dimension of an array.
**Examples**
```
julia> A = [1 2; 3 4]
2×2 Array{Int64, 2}:
1 2
3 4
julia> A[end, :]
2-element Array{Int64, 1}:
3
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L797-L819)###
`let`Keyword
```
let
```
`let` statements create a new hard scope block and introduce new variable bindings each time they run. Whereas assignments might reassign a new value to an existing value location, `let` always creates a new location. This difference is only detectable in the case of variables that outlive their scope via closures. The `let` syntax accepts a comma-separated series of assignments and variable names:
```
let var1 = value1, var2, var3 = value3
code
end
```
The assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like `let x = x`, since the two `x` variables are distinct and have separate storage.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L430-L449)###
`if`Keyword
```
if/elseif/else
```
`if`/`elseif`/`else` performs conditional evaluation, which allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the `if`/`elseif`/`else` conditional syntax:
```
if x < y
println("x is less than y")
elseif x > y
println("x is greater than y")
else
println("x is equal to y")
end
```
If the condition expression `x < y` is true, then the corresponding block is evaluated; otherwise the condition expression `x > y` is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, the `else` block is evaluated. The `elseif` and `else` blocks are optional, and as many `elseif` blocks as desired can be used.
In contrast to some other languages conditions must be of type `Bool`. It does not suffice for conditions to be convertible to `Bool`.
```
julia> if 1 end
ERROR: TypeError: non-boolean (Int64) used in boolean context
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L702-L730)###
`for`Keyword
```
for
```
`for` loops repeatedly evaluate a block of statements while iterating over a sequence of values.
**Examples**
```
julia> for i in [1, 4, 0]
println(i)
end
1
4
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L755-L770)###
`while`Keyword
```
while
```
`while` loops repeatedly evaluate a conditional expression, and continue evaluating the body of the while loop as long as the expression remains true. If the condition expression is false when the while loop is first reached, the body is never evaluated.
**Examples**
```
julia> i = 1
1
julia> while i < 5
println(i)
global i += 1
end
1
2
3
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L773-L794)###
`break`Keyword
```
break
```
Break out of a loop immediately.
**Examples**
```
julia> i = 0
0
julia> while true
global i += 1
i > 5 && break
println(i)
end
1
2
3
4
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L884-L905)###
`continue`Keyword
```
continue
```
Skip the rest of the current loop iteration.
**Examples**
```
julia> for i = 1:6
iseven(i) && continue
println(i)
end
1
3
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L908-L923)###
`try`Keyword
```
try/catch
```
A `try`/`catch` statement allows intercepting errors (exceptions) thrown by [`throw`](#Core.throw) so that program execution can continue. For example, the following code attempts to write a file, but warns the user and proceeds instead of terminating execution if the file cannot be written:
```
try
open("/danger", "w") do f
println(f, "Hello")
end
catch
@warn "Could not write file."
end
```
or, when the file cannot be read into a variable:
```
lines = try
open("/danger", "r") do f
readlines(f)
end
catch
@warn "File not found."
end
```
The syntax `catch e` (where `e` is any variable) assigns the thrown exception object to the given variable within the `catch` block.
The power of the `try`/`catch` construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L822-L857)###
`finally`Keyword
```
finally
```
Run some code when a given block of code exits, regardless of how it exits. For example, here is how we can guarantee that an opened file is closed:
```
f = open("file")
try
operate_on_file(f)
finally
close(f)
end
```
When control leaves the [`try`](#try) block (for example, due to a [`return`](#return), or just finishing normally), [`close(f)`](../io-network/index#Base.close) will be executed. If the `try` block exits due to an exception, the exception will continue propagating. A `catch` block may be combined with `try` and `finally` as well. In this case the `finally` block will run after `catch` has handled the error.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L860-L881)###
`quote`Keyword
```
quote
```
`quote` creates multiple expression objects in a block without using the explicit [`Expr`](#Core.Expr) constructor. For example:
```
ex = quote
x = 1
y = 2
x + y
end
```
Unlike the other means of quoting, `:( ... )`, this form introduces `QuoteNode` elements to the expression tree, which must be considered when directly manipulating the tree. For other purposes, `:( ... )` and `quote .. end` blocks are treated identically.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L452-L468)###
`local`Keyword
```
local
```
`local` introduces a new local variable. See the [manual section on variable scoping](../../manual/variables-and-scoping/index#scope-of-variables) for more information.
**Examples**
```
julia> function foo(n)
x = 0
for i = 1:n
local x # introduce a loop-local x
x = i
end
x
end
foo (generic function with 1 method)
julia> foo(10)
0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L232-L253)###
`global`Keyword
```
global
```
`global x` makes `x` in the current scope and its inner scopes refer to the global variable of that name. See the [manual section on variable scoping](../../manual/variables-and-scoping/index#scope-of-variables) for more information.
**Examples**
```
julia> z = 3
3
julia> function foo()
global z = 6 # use the z variable defined outside foo
end
foo (generic function with 1 method)
julia> foo()
6
julia> z
6
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L256-L279)###
`const`Keyword
```
const
```
`const` is used to declare global variables whose values will not change. In almost all code (and particularly performance sensitive code) global variables should be declared constant in this way.
```
const x = 5
```
Multiple variables can be declared within a single `const`:
```
const y, z = 7, 11
```
Note that `const` only applies to one `=` operation, therefore `const x = y = 1` declares `x` to be constant but not `y`. On the other hand, `const x = const y = 1` declares both `x` and `y` constant.
Note that "constant-ness" does not extend into mutable containers; only the association between a variable and its value is constant. If `x` is an array or dictionary (for example) you can still modify, add, or remove elements.
In some cases changing the value of a `const` variable gives a warning instead of an error. However, this can produce unpredictable behavior or corrupt the state of your program, and so should be avoided. This feature is intended only for convenience during interactive use.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L579-L608)###
`struct`Keyword
```
struct
```
The most commonly used kind of type in Julia is a struct, specified as a name and a set of fields.
```
struct Point
x
y
end
```
Fields can have type restrictions, which may be parameterized:
```
struct Point{X}
x::X
y::Float64
end
```
A struct can also declare an abstract super type via `<:` syntax:
```
struct Point <: AbstractPoint
x
y
end
```
`struct`s are immutable by default; an instance of one of these types cannot be modified after construction. Use [`mutable struct`](#mutable%20struct) instead to declare a type whose instances can be modified.
See the manual section on [Composite Types](../../manual/types/index#Composite-Types) for more details, such as how to define constructors.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1141-L1178)###
`mutable struct`Keyword
```
mutable struct
```
`mutable struct` is similar to [`struct`](#struct), but additionally allows the fields of the type to be set after construction. See the manual section on [Composite Types](../../manual/types/index#Composite-Types) for more information.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1181-L1187)###
`abstract type`Keyword
```
abstract type
```
`abstract type` declares a type that cannot be instantiated, and serves only as a node in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. Abstract types form the conceptual hierarchy which makes Julia’s type system more than just a collection of object implementations. For example:
```
abstract type Number end
abstract type Real <: Number end
```
[`Number`](../numbers/index#Core.Number) has no supertype, whereas [`Real`](../numbers/index#Core.Real) is an abstract subtype of `Number`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L62-L75)###
`primitive type`Keyword
```
primitive type
```
`primitive type` declares a concrete type whose data consists only of a series of bits. Classic examples of primitive types are integers and floating-point values. Some example built-in primitive type declarations:
```
primitive type Char 32 end
primitive type Bool <: Integer 8 end
```
The number after the name indicates how many bits of storage the type requires. Currently, only sizes that are multiples of 8 bits are supported. The [`Bool`](../numbers/index#Core.Bool) declaration shows how a primitive type can be optionally declared to be a subtype of some supertype.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L160-L175)###
`where`Keyword
```
where
```
The `where` keyword creates a type that is an iterated union of other types, over all values of some variable. For example `Vector{T} where T<:Real` includes all [`Vector`](../arrays/index#Base.Vector)s where the element type is some kind of `Real` number.
The variable bound defaults to [`Any`](#Core.Any) if it is omitted:
```
Vector{T} where T # short for `where T<:Any`
```
Variables can also have lower bounds:
```
Vector{T} where T>:Int
Vector{T} where Int<:T<:Real
```
There is also a concise syntax for nested `where` expressions. For example, this:
```
Pair{T, S} where S<:Array{T} where T<:Number
```
can be shortened to:
```
Pair{T, S} where {T<:Number, S<:Array{T}}
```
This form is often found on method signatures.
Note that in this form, the variables are listed outermost-first. This matches the order in which variables are substituted when a type is "applied" to parameter values using the syntax `T{p1, p2, ...}`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1200-L1233)###
`...`Keyword
```
...
```
The "splat" operator, `...`, represents a sequence of arguments. `...` can be used in function definitions, to indicate that the function accepts an arbitrary number of arguments. `...` can also be used to apply a function to a sequence of arguments.
**Examples**
```
julia> add(xs...) = reduce(+, xs)
add (generic function with 1 method)
julia> add(1, 2, 3, 4, 5)
15
julia> add([1, 2, 3]...)
6
julia> add(7, 1:100..., 1000:1100...)
111107
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L951-L973)###
`;`Keyword
```
;
```
`;` has a similar role in Julia as in many C-like languages, and is used to delimit the end of the previous statement.
`;` is not necessary at the end of a line, but can be used to separate statements on a single line or to join statements into a single expression.
Adding `;` at the end of a line in the REPL will suppress printing the result of that expression.
In function declarations, and optionally in calls, `;` separates regular arguments from keywords.
While constructing arrays, if the arguments inside the square brackets are separated by `;` then their contents are vertically concatenated together.
In the standard REPL, typing `;` on an empty line will switch to shell mode.
**Examples**
```
julia> function foo()
x = "Hello, "; x *= "World!"
return x
end
foo (generic function with 1 method)
julia> bar() = (x = "Hello, Mars!"; return x)
bar (generic function with 1 method)
julia> foo();
julia> bar()
"Hello, Mars!"
julia> function plot(x, y; style="solid", width=1, color="black")
###
end
julia> [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> echo hello
hello
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L976-L1023)###
`=`Keyword
```
=
```
`=` is the assignment operator.
* For variable `a` and expression `b`, `a = b` makes `a` refer to the value of `b`.
* For functions `f(x)`, `f(x) = x` defines a new function constant `f`, or adds a new method to `f` if `f` is already defined; this usage is equivalent to `function f(x); x; end`.
* `a[i] = v` calls [`setindex!`](../collections/index#Base.setindex!)`(a,v,i)`.
* `a.b = c` calls [`setproperty!`](#Base.setproperty!)`(a,:b,c)`.
* Inside a function call, `f(a=b)` passes `b` as the value of keyword argument `a`.
* Inside parentheses with commas, `(a=1,)` constructs a [`NamedTuple`](#Core.NamedTuple).
**Examples**
Assigning `a` to `b` does not create a copy of `b`; instead use [`copy`](#Base.copy) or [`deepcopy`](#Base.deepcopy).
```
julia> b = [1]; a = b; b[1] = 2; a
1-element Array{Int64, 1}:
2
julia> b = [1]; a = copy(b); b[1] = 2; a
1-element Array{Int64, 1}:
1
```
Collections passed to functions are also not copied. Functions can modify (mutate) the contents of the objects their arguments refer to. (The names of functions which do this are conventionally suffixed with '!'.)
```
julia> function f!(x); x[:] .+= 1; end
f! (generic function with 1 method)
julia> a = [1]; f!(a); a
1-element Array{Int64, 1}:
2
```
Assignment can operate on multiple variables in parallel, taking values from an iterable:
```
julia> a, b = 4, 5
(4, 5)
julia> a, b = 1:3
1:3
julia> a, b
(1, 2)
```
Assignment can operate on multiple variables in series, and will return the value of the right-hand-most expression:
```
julia> a = [1]; b = [2]; c = [3]; a = b = c
1-element Array{Int64, 1}:
3
julia> b[1] = 2; a, b, c
([2], [2], [2])
```
Assignment at out-of-bounds indices does not grow a collection. If the collection is a [`Vector`](../arrays/index#Base.Vector) it can instead be grown with [`push!`](../collections/index#Base.push!) or [`append!`](../collections/index#Base.append!).
```
julia> a = [1, 1]; a[3] = 2
ERROR: BoundsError: attempt to access 2-element Array{Int64, 1} at index [3]
[...]
julia> push!(a, 2, 3)
4-element Array{Int64, 1}:
1
1
2
3
```
Assigning `[]` does not eliminate elements from a collection; instead use [`filter!`](../collections/index#Base.filter!).
```
julia> a = collect(1:3); a[a .<= 1] = []
ERROR: DimensionMismatch: tried to assign 0 elements to 1 destinations
[...]
julia> filter!(x -> x > 1, a) # in-place & thus more efficient than a = a[a .> 1]
2-element Array{Int64, 1}:
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L295-L377)###
`?:`Keyword
```
a ? b : c
```
Short form for conditionals; read "if `a`, evaluate `b` otherwise evaluate `c`". Also known as the [ternary operator](https://en.wikipedia.org/wiki/%3F:).
This syntax is equivalent to `if a; b else c end`, but is often used to emphasize the value `b`-or-`c` which is being used as part of a larger expression, rather than the side effects that evaluating `b` or `c` may have.
See the manual section on [control flow](../../manual/control-flow/index#man-conditional-evaluation) for more details.
**Examples**
```
julia> x = 1; y = 2;
julia> x > y ? println("x is larger") : println("y is larger")
y is larger
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L733-L752)
[Standard Modules](#Standard-Modules)
--------------------------------------
###
`Main`Module
```
Main
```
`Main` is the top-level module, and Julia starts with `Main` set as the current module. Variables defined at the prompt go in `Main`, and `varinfo` lists variables in `Main`.
```
julia> @__MODULE__
Main
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2833-L2841)###
`Core`Module
```
Core
```
`Core` is the module that contains all identifiers considered "built in" to the language, i.e. part of the core language and not libraries. Every module implicitly specifies `using Core`, since you can't do anything without those definitions.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2826-L2830)###
`Base`Module
```
Base
```
The base library of Julia. `Base` is a module that contains basic functionality (the contents of `base/`). All modules implicitly contain `using Base`, since this is needed in the vast majority of cases.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2844-L2848)
[Base Submodules](#Base-Submodules)
------------------------------------
###
`Base.Broadcast`Module
```
Base.Broadcast
```
Module containing the broadcasting implementation.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/broadcast.jl#L3-L7)###
`Base.Docs`Module
```
Docs
```
The `Docs` module provides the `@doc` macro which can be used to set and retrieve documentation metadata for Julia objects.
Please see the manual section on [documentation](../../manual/documentation/index#man-documentation) for more information.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/Docs.jl#L3-L11)###
`Base.Iterators`Module
Methods for working with Iterators.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L3-L5)###
`Base.Libc`Module
Interface to libc, the C standard library.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L4-L6)###
`Base.Meta`Module
Convenience functions for metaprogramming.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L3-L5)###
`Base.StackTraces`Module
Tools for collecting and manipulating stack traces. Mainly used for building errors.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/stacktraces.jl#L3-L5)###
`Base.Sys`Module
Provide methods for retrieving information about hardware and the operating system.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L4-L6)###
`Base.Threads`Module
Multithreading support.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/threads.jl#L3-L5)###
`Base.GC`Module
```
Base.GC
```
Module with garbage collection utilities.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L70-L74)
[All Objects](#All-Objects)
----------------------------
###
`Core.:===`Function
```
===(x,y) -> Bool
≡(x,y) -> Bool
```
Determine whether `x` and `y` are identical, in the sense that no program could distinguish them. First the types of `x` and `y` are compared. If those are identical, mutable objects are compared by address in memory and immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes called "egal". It always returns a `Bool` value.
**Examples**
```
julia> a = [1, 2]; b = [1, 2];
julia> a == b
true
julia> a === b
false
julia> a === a
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L285-L308)###
`Core.isa`Function
```
isa(x, type) -> Bool
```
Determine whether `x` is of the given `type`. Can also be used as an infix operator, e.g. `x isa type`.
**Examples**
```
julia> isa(1, Int)
true
julia> isa(1, Matrix)
false
julia> isa(1, Char)
false
julia> isa(1, Number)
true
julia> 1 isa Number
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1731-L1754)###
`Base.isequal`Function
```
isequal(x, y)
```
Similar to [`==`](../math/index#Base.:==), except for the treatment of floating point numbers and of missing values. `isequal` treats all floating-point `NaN` values as equal to each other, treats `-0.0` as unequal to `0.0`, and [`missing`](#Base.missing) as equal to `missing`. Always returns a `Bool` value.
`isequal` is an equivalence relation - it is reflexive (`===` implies `isequal`), symmetric (`isequal(a, b)` implies `isequal(b, a)`) and transitive (`isequal(a, b)` and `isequal(b, c)` implies `isequal(a, c)`).
**Implementation**
The default implementation of `isequal` calls `==`, so a type that does not involve floating-point values generally only needs to define `==`.
`isequal` is the comparison function used by hash tables (`Dict`). `isequal(x,y)` must imply that `hash(x) == hash(y)`.
This typically means that types for which a custom `==` or `isequal` method exists must implement a corresponding [`hash`](#Base.hash) method (and vice versa). Collections typically implement `isequal` by calling `isequal` recursively on all contents.
Furthermore, `isequal` is linked with [`isless`](#Base.isless), and they work together to define a fixed total ordering, where exactly one of `isequal(x, y)`, `isless(x, y)`, or `isless(y, x)` must be `true` (and the other two `false`).
Scalar types generally do not need to implement `isequal` separate from `==`, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on `isnan`, `signbit`, and `==`).
**Examples**
```
julia> isequal([1., NaN], [1., NaN])
true
julia> [1., NaN] == [1., NaN]
false
julia> 0.0 == -0.0
true
julia> isequal(0.0, -0.0)
false
julia> missing == missing
missing
julia> isequal(missing, missing)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L88-L139)
```
isequal(x)
```
Create a function that compares its argument to `x` using [`isequal`](#Base.isequal), i.e. a function equivalent to `y -> isequal(y, x)`.
The returned function is of type `Base.Fix2{typeof(isequal)}`, which can be used to implement specialized methods.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1115-L1123)###
`Base.isless`Function
```
isless(x, y)
```
Test whether `x` is less than `y`, according to a fixed total order (defined together with [`isequal`](#Base.isequal)). `isless` is not defined on all pairs of values `(x, y)`. However, if it is defined, it is expected to satisfy the following:
* If `isless(x, y)` is defined, then so is `isless(y, x)` and `isequal(x, y)`, and exactly one of those three yields `true`.
* The relation defined by `isless` is transitive, i.e., `isless(x, y) && isless(y, z)` implies `isless(x, z)`.
Values that are normally unordered, such as `NaN`, are ordered after regular values. [`missing`](#Base.missing) values are ordered last.
This is the default comparison used by [`sort`](../sort/index#Base.sort).
**Implementation**
Non-numeric types with a total order should implement this function. Numeric types only need to implement it if they have special values such as `NaN`. Types with a partial order should implement [`<`](#). See the documentation on [Alternate orderings](../sort/index#Alternate-orderings) for how to define alternate ordering methods that can be used in sorting and related functions.
**Examples**
```
julia> isless(1, 3)
true
julia> isless("Red", "Blue")
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L149-L181)###
`Base.ifelse`Function
```
ifelse(condition::Bool, x, y)
```
Return `x` if `condition` is `true`, otherwise return `y`. This differs from `?` or `if` in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using `ifelse` instead of an `if` statement can eliminate the branch in generated code and provide higher performance in tight loops.
**Examples**
```
julia> ifelse(1 > 2, 1, 2)
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L475-L488)###
`Core.typeassert`Function
```
typeassert(x, type)
```
Throw a [`TypeError`](#Core.TypeError) unless `x isa type`. The syntax `x::type` calls this function.
**Examples**
```
julia> typeassert(2.5, Int)
ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2673-L2686)###
`Core.typeof`Function
```
typeof(x)
```
Get the concrete type of `x`.
See also [`eltype`](../collections/index#Base.eltype).
**Examples**
```
julia> a = 1//2;
julia> typeof(a)
Rational{Int64}
julia> M = [1 2; 3.5 4];
julia> typeof(M)
Matrix{Float64} (alias for Array{Float64, 2})
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2054-L2073)###
`Core.tuple`Function
```
tuple(xs...)
```
Construct a tuple of the given objects.
See also [`Tuple`](#Core.Tuple), [`NamedTuple`](#Core.NamedTuple).
**Examples**
```
julia> tuple(1, 'b', pi)
(1, 'b', π)
julia> ans === (1, 'b', π)
true
julia> Tuple(Real[1, 2, pi]) # takes a collection
(1, 2, π)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1922-L1940)###
`Base.ntuple`Function
```
ntuple(f::Function, n::Integer)
```
Create a tuple of length `n`, computing each element as `f(i)`, where `i` is the index of the element.
**Examples**
```
julia> ntuple(i -> 2*i, 4)
(2, 4, 6, 8)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ntuple.jl#L5-L16)
```
ntuple(f, ::Val{N})
```
Create a tuple of length `N`, computing each element as `f(i)`, where `i` is the index of the element. By taking a `Val(N)` argument, it is possible that this version of ntuple may generate more efficient code than the version taking the length as an integer. But `ntuple(f, N)` is preferable to `ntuple(f, Val(N))` in cases where `N` cannot be determined at compile time.
**Examples**
```
julia> ntuple(i -> 2*i, Val(4))
(2, 4, 6, 8)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/ntuple.jl#L52-L68)###
`Base.objectid`Function
```
objectid(x) -> UInt
```
Get a hash value for `x` based on object identity. `objectid(x)==objectid(y)` if `x === y`.
See also [`hash`](#Base.hash), [`IdDict`](../collections/index#Base.IdDict).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L333-L339)###
`Base.hash`Function
```
hash(x[, h::UInt]) -> UInt
```
Compute an integer hash code such that `isequal(x,y)` implies `hash(x)==hash(y)`. The optional second argument `h` is a hash code to be mixed with the result.
New types should implement the 2-argument form, typically by calling the 2-argument `hash` method recursively in order to mix hashes of the contents with each other (and with `h`). Typically, any type that implements `hash` should also implement its own [`==`](../math/index#Base.:==) (hence [`isequal`](#Base.isequal)) to guarantee the property mentioned above. Types supporting subtraction (operator `-`) should also implement [`widen`](#Base.widen), which is required to hash values inside heterogeneous arrays.
See also: [`objectid`](#Base.objectid), [`Dict`](../collections/index#Base.Dict), [`Set`](../collections/index#Base.Set).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/hashing.jl#L5-L19)###
`Base.finalizer`Function
```
finalizer(f, x)
```
Register a function `f(x)` to be called when there are no program-accessible references to `x`, and return `x`. The type of `x` must be a `mutable struct`, otherwise the behavior of this function is unpredictable.
`f` must not cause a task switch, which excludes most I/O operations such as `println`. Using the `@async` macro (to defer context switching to outside of the finalizer) or `ccall` to directly invoke IO functions in C may be helpful for debugging purposes.
**Examples**
```
finalizer(my_mutable_struct) do x
@async println("Finalizing $x.")
end
finalizer(my_mutable_struct) do x
ccall(:jl_safe_printf, Cvoid, (Cstring, Cstring), "Finalizing %s.", repr(x))
end
```
A finalizer may be registered at object construction. In the following example note that we implicitly rely on the finalizer returning the newly created mutable struct `x`.
**Example**
```
mutable struct MyMutableStruct
bar
function MyMutableStruct(bar)
x = new(bar)
f(t) = @async println("Finalizing $t.")
finalizer(f, x)
end
end
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L7-L43)###
`Base.finalize`Function
```
finalize(x)
```
Immediately run finalizers registered for object `x`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L62-L66)###
`Base.copy`Function
```
copy(x)
```
Create a shallow copy of `x`: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.
See also [`copy!`](../arrays/index#Base.copy!), [`copyto!`](../c/index#Base.copyto!).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L358-L366)###
`Base.deepcopy`Function
```
deepcopy(x)
```
Create a deep copy of `x`: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling `deepcopy` on an object should generally have the same effect as serializing and then deserializing it.
While it isn't normally necessary, user-defined types can override the default `deepcopy` behavior by defining a specialized version of the function `deepcopy_internal(x::T, dict::IdDict)` (which shouldn't otherwise be used), where `T` is the type to be specialized for, and `dict` keeps track of objects copied so far within the recursion. Within the definition, `deepcopy_internal` should be used in place of `deepcopy`, and the `dict` variable should be updated as appropriate before returning.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/deepcopy.jl#L8-L23)###
`Base.getproperty`Function
```
getproperty(value, name::Symbol)
getproperty(value, name::Symbol, order::Symbol)
```
The syntax `a.b` calls `getproperty(a, :b)`. The syntax `@atomic order a.b` calls `getproperty(a, :b, :order)` and the syntax `@atomic a.b` calls `getproperty(a, :b, :sequentially_consistent)`.
**Examples**
```
julia> struct MyType
x
end
julia> function Base.getproperty(obj::MyType, sym::Symbol)
if sym === :special
return obj.x + 1
else # fallback to getfield
return getfield(obj, sym)
end
end
julia> obj = MyType(1);
julia> obj.special
2
julia> obj.x
1
```
See also [`getfield`](#Core.getfield), [`propertynames`](#Base.propertynames) and [`setproperty!`](#Base.setproperty!).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2689-L2723)###
`Base.setproperty!`Function
```
setproperty!(value, name::Symbol, x)
setproperty!(value, name::Symbol, x, order::Symbol)
```
The syntax `a.b = c` calls `setproperty!(a, :b, c)`. The syntax `@atomic order a.b = c` calls `setproperty!(a, :b, c, :order)` and the syntax `@atomic a.b = c` calls `getproperty(a, :b, :sequentially_consistent)`.
See also [`setfield!`](#Core.setfield!), [`propertynames`](#Base.propertynames) and [`getproperty`](#Base.getproperty).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2726-L2737)###
`Base.propertynames`Function
```
propertynames(x, private=false)
```
Get a tuple or a vector of the properties (`x.property`) of an object `x`. This is typically the same as [`fieldnames(typeof(x))`](#Base.fieldnames), but types that overload [`getproperty`](#Base.getproperty) should generally overload `propertynames` as well to get the properties of an instance of the type.
`propertynames(x)` may return only "public" property names that are part of the documented interface of `x`. If you want it to also return "private" fieldnames intended for internal use, pass `true` for the optional second argument. REPL tab completion on `x.` shows only the `private=false` properties.
See also: [`hasproperty`](#Base.hasproperty), [`hasfield`](#Base.hasfield).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1736-L1750)###
`Base.hasproperty`Function
```
hasproperty(x, s::Symbol)
```
Return a boolean indicating whether the object `x` has `s` as one of its own properties.
This function requires at least Julia 1.2.
See also: [`propertynames`](#Base.propertynames), [`hasfield`](#Base.hasfield).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1755-L1764)###
`Core.getfield`Function
```
getfield(value, name::Symbol, [order::Symbol])
getfield(value, i::Int, [order::Symbol])
```
Extract a field from a composite `value` by name or position. Optionally, an ordering can be defined for the operation. If the field was declared `@atomic`, the specification is strongly recommended to be compatible with the stores to that location. Otherwise, if not declared as `@atomic`, this parameter must be `:not_atomic` if specified. See also [`getproperty`](#Base.getproperty) and [`fieldnames`](#Base.fieldnames).
**Examples**
```
julia> a = 1//2
1//2
julia> getfield(a, :num)
1
julia> a.num
1
julia> getfield(a, 1)
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1943-L1968)###
`Core.setfield!`Function
```
setfield!(value, name::Symbol, x, [order::Symbol])
setfield!(value, i::Int, x, [order::Symbol])
```
Assign `x` to a named field in `value` of composite type. The `value` must be mutable and `x` must be a subtype of `fieldtype(typeof(value), name)`. Additionally, an ordering can be specified for this operation. If the field was declared `@atomic`, this specification is mandatory. Otherwise, if not declared as `@atomic`, it must be `:not_atomic` if specified. See also [`setproperty!`](#Base.setproperty!).
**Examples**
```
julia> mutable struct MyMutableStruct
field::Int
end
julia> a = MyMutableStruct(1);
julia> setfield!(a, :field, 2);
julia> getfield(a, :field)
2
julia> a = 1//2
1//2
julia> setfield!(a, :num, 3);
ERROR: setfield!: immutable struct of type Rational cannot be changed
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1971-L2001)###
`Core.isdefined`Function
```
isdefined(m::Module, s::Symbol, [order::Symbol])
isdefined(object, s::Symbol, [order::Symbol])
isdefined(object, index::Int, [order::Symbol])
```
Tests whether a global variable or object field is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index. Optionally, an ordering can be defined for the operation. If the field was declared `@atomic`, the specification is strongly recommended to be compatible with the stores to that location. Otherwise, if not declared as `@atomic`, this parameter must be `:not_atomic` if specified.
To test whether an array element is defined, use [`isassigned`](../arrays/index#Base.isassigned) instead.
See also [`@isdefined`](#Base.@isdefined).
**Examples**
```
julia> isdefined(Base, :sum)
true
julia> isdefined(Base, :NonExistentMethod)
false
julia> a = 1//2;
julia> isdefined(a, 2)
true
julia> isdefined(a, 3)
false
julia> isdefined(a, :num)
true
julia> isdefined(a, :numerator)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2076-L2114)###
`Base.@isdefined`Macro
```
@isdefined s -> Bool
```
Tests whether variable `s` is defined in the current scope.
See also [`isdefined`](#Core.isdefined) for field properties and [`isassigned`](../arrays/index#Base.isassigned) for array indexes or [`haskey`](../collections/index#Base.haskey) for other mappings.
**Examples**
```
julia> @isdefined newvar
false
julia> newvar = 1
1
julia> @isdefined newvar
true
julia> function f()
println(@isdefined x)
x = 3
println(@isdefined x)
end
f (generic function with 1 method)
julia> f()
false
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L119-L149)###
`Base.convert`Function
```
convert(T, x)
```
Convert `x` to a value of type `T`.
If `T` is an [`Integer`](../numbers/index#Core.Integer) type, an [`InexactError`](#Core.InexactError) will be raised if `x` is not representable by `T`, for example if `x` is not integer-valued, or is outside the range supported by `T`.
**Examples**
```
julia> convert(Int, 3.0)
3
julia> convert(Int, 3.5)
ERROR: InexactError: Int64(3.5)
Stacktrace:
[...]
```
If `T` is a [`AbstractFloat`](../numbers/index#Core.AbstractFloat) type, then it will return the closest value to `x` representable by `T`.
```
julia> x = 1/3
0.3333333333333333
julia> convert(Float32, x)
0.33333334f0
julia> convert(BigFloat, x)
0.333333333333333314829616256247390992939472198486328125
```
If `T` is a collection type and `x` a collection, the result of `convert(T, x)` may alias all or part of `x`.
```
julia> x = Int[1, 2, 3];
julia> y = convert(Vector{Int}, x);
julia> y === x
true
```
See also: [`round`](#), [`trunc`](../math/index#Base.trunc), [`oftype`](#Base.oftype), [`reinterpret`](../arrays/index#Base.reinterpret).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L164-L210)###
`Base.promote`Function
```
promote(xs...)
```
Convert all arguments to a common type, and return them all (as a tuple). If no arguments can be converted, an error is raised.
See also: [`promote_type`], [`promote_rule`].
**Examples**
```
julia> promote(Int8(1), Float16(4.5), Float32(4.1))
(1.0f0, 4.5f0, 4.1f0)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/promotion.jl#L317-L330)###
`Base.oftype`Function
```
oftype(x, y)
```
Convert `y` to the type of `x` (`convert(typeof(x), y)`).
**Examples**
```
julia> x = 4;
julia> y = 3.;
julia> oftype(x, y)
3
julia> oftype(y, x)
4.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L373-L390)###
`Base.widen`Function
```
widen(x)
```
If `x` is a type, return a "larger" type, defined so that arithmetic operations `+` and `-` are guaranteed not to overflow nor lose precision for any combination of values that type `x` can hold.
For fixed-size integer types less than 128 bits, `widen` will return a type with twice the number of bits.
If `x` is a value, it is converted to `widen(typeof(x))`.
**Examples**
```
julia> widen(Int32)
Int64
julia> widen(1.5f0)
1.5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L874-L894)###
`Base.identity`Function
```
identity(x)
```
The identity function. Returns its argument.
See also: [`one`](../numbers/index#Base.one), [`oneunit`](../numbers/index#Base.oneunit), and [`LinearAlgebra`](../../stdlib/linearalgebra/index#man-linalg)'s `I`.
**Examples**
```
julia> identity("Well, what did you expect?")
"Well, what did you expect?"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L513-L525)
[Properties of Types](#Properties-of-Types)
--------------------------------------------
###
[Type relations](#Type-relations)
###
`Base.supertype`Function
```
supertype(T::DataType)
```
Return the supertype of DataType `T`.
**Examples**
```
julia> supertype(Int32)
Signed
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L32-L42)###
`Core.Type`Type
```
Core.Type{T}
```
`Core.Type` is an abstract type which has all type objects as its instances. The only instance of the singleton type `Core.Type{T}` is the object `T`.
**Examples**
```
julia> isa(Type{Float64}, Type)
true
julia> isa(Float64, Type)
true
julia> isa(Real, Type{Float64})
false
julia> isa(Real, Type{Real})
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1306-L1327)###
`Core.DataType`Type
```
DataType <: Type{T}
```
`DataType` represents explicitly declared types that have names, explicitly declared supertypes, and, optionally, parameters. Every concrete value in the system is an instance of some `DataType`.
**Examples**
```
julia> typeof(Real)
DataType
julia> typeof(Int)
DataType
julia> struct Point
x::Int
y
end
julia> typeof(Point)
DataType
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1330-L1353)###
`Core.:<:`Function
```
<:(T1, T2)
```
Subtype operator: returns `true` if and only if all values of type `T1` are also of type `T2`.
**Examples**
```
julia> Float64 <: AbstractFloat
true
julia> Vector{Int} <: AbstractArray
true
julia> Matrix{Float64} <: Matrix{AbstractFloat}
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L5-L22)###
`Base.:>:`Function
```
>:(T1, T2)
```
Supertype operator, equivalent to `T2 <: T1`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L25-L29)###
`Base.typejoin`Function
```
typejoin(T, S)
```
Return the closest common ancestor of `T` and `S`, i.e. the narrowest type from which they both inherit.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/promotion.jl#L5-L10)###
`Base.typeintersect`Function
```
typeintersect(T::Type, S::Type)
```
Compute a type that contains the intersection of `T` and `S`. Usually this will be the smallest such type or one close to it.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L677-L682)###
`Base.promote_type`Function
```
promote_type(type1, type2)
```
Promotion refers to converting values of mixed types to a single common type. `promote_type` represents the default promotion behavior in Julia when operators (usually mathematical) are given arguments of differing types. `promote_type` generally tries to return a type which can at least approximate most values of either input type without excessively widening. Some loss is tolerated; for example, `promote_type(Int64, Float64)` returns [`Float64`](../numbers/index#Core.Float64) even though strictly, not all [`Int64`](../numbers/index#Core.Int64) values can be represented exactly as `Float64` values.
See also: [`promote`](#Base.promote), [`promote_typejoin`](#Base.promote_typejoin), [`promote_rule`](#Base.promote_rule).
**Examples**
```
julia> promote_type(Int64, Float64)
Float64
julia> promote_type(Int32, Int64)
Int64
julia> promote_type(Float32, BigInt)
BigFloat
julia> promote_type(Int16, Float16)
Float16
julia> promote_type(Int64, Float16)
Float16
julia> promote_type(Int8, UInt16)
UInt16
```
To overload promotion for your own types you should overload [`promote_rule`](#Base.promote_rule). `promote_type` calls `promote_rule` internally to determine the type. Overloading `promote_type` directly can cause ambiguity errors.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/promotion.jl#L240-L279)###
`Base.promote_rule`Function
```
promote_rule(type1, type2)
```
Specifies what type should be used by [`promote`](#Base.promote) when given values of types `type1` and `type2`. This function should not be called directly, but should have definitions added to it for new types as appropriate.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/promotion.jl#L301-L307)###
`Base.promote_typejoin`Function
```
promote_typejoin(T, S)
```
Compute a type that contains both `T` and `S`, which could be either a parent of both types, or a `Union` if appropriate. Falls back to [`typejoin`](#Base.typejoin).
See instead [`promote`](#Base.promote), [`promote_type`](#Base.promote_type).
**Examples**
```
julia> Base.promote_typejoin(Int, Float64)
Real
julia> Base.promote_type(Int, Float64)
Float64
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/promotion.jl#L143-L160)###
`Base.isdispatchtuple`Function
```
isdispatchtuple(T)
```
Determine whether type `T` is a tuple "leaf type", meaning it could appear as a type signature in dispatch and has no subtypes (or supertypes) which could appear in a call.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L595-L601)###
[Declared structure](#Declared-structure)
###
`Base.ismutable`Function
```
ismutable(v) -> Bool
```
Return `true` if and only if value `v` is mutable. See [Mutable Composite Types](../../manual/types/index#Mutable-Composite-Types) for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of `DataType` is mutable.
See also [`isbits`](#Base.isbits), [`isstructtype`](#Base.isstructtype).
**Examples**
```
julia> ismutable(1)
false
julia> ismutable([1,2])
true
```
This function requires at least Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L493-L513)###
`Base.isimmutable`Function
```
isimmutable(v) -> Bool
```
Consider using `!ismutable(v)` instead, as `isimmutable(v)` will be replaced by `!ismutable(v)` in a future release. (Since Julia 1.5)
Return `true` iff value `v` is immutable. See [Mutable Composite Types](../../manual/types/index#Mutable-Composite-Types) for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of `DataType` is mutable.
**Examples**
```
julia> isimmutable(1)
true
julia> isimmutable([1,2])
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/deprecated.jl#L188-L204)###
`Base.isabstracttype`Function
```
isabstracttype(T)
```
Determine whether type `T` was declared as an abstract type (i.e. using the `abstract` keyword).
**Examples**
```
julia> isabstracttype(AbstractArray)
true
julia> isabstracttype(Vector)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L647-L661)###
`Base.isprimitivetype`Function
```
isprimitivetype(T) -> Bool
```
Determine whether type `T` was declared as a primitive type (i.e. using the `primitive` keyword).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L548-L553)###
`Base.issingletontype`Function
```
Base.issingletontype(T)
```
Determine whether type `T` has exactly one possible instance; for example, a struct type with no fields.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L669-L674)###
`Base.isstructtype`Function
```
isstructtype(T) -> Bool
```
Determine whether type `T` was declared as a struct type (i.e. using the `struct` or `mutable struct` keyword).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L533-L538)###
`Base.nameof`Method
```
nameof(t::DataType) -> Symbol
```
Get the name of a (potentially `UnionAll`-wrapped) `DataType` (without its parent module) as a symbol.
**Examples**
```
julia> module Foo
struct S{T}
end
end
Foo
julia> nameof(Foo.S{T} where T)
:S
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L220-L237)###
`Base.fieldnames`Function
```
fieldnames(x::DataType)
```
Get a tuple with the names of the fields of a `DataType`.
See also [`propertynames`](#Base.propertynames), [`hasfield`](#Base.hasfield).
**Examples**
```
julia> fieldnames(Rational)
(:num, :den)
julia> fieldnames(typeof(1+im))
(:re, :im)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L169-L184)###
`Base.fieldname`Function
```
fieldname(x::DataType, i::Integer)
```
Get the name of field `i` of a `DataType`.
**Examples**
```
julia> fieldname(Rational, 1)
:num
julia> fieldname(Rational, 2)
:den
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L135-L148)###
`Core.fieldtype`Function
```
fieldtype(T, name::Symbol | index::Int)
```
Determine the declared type of a field (specified by name or index) in a composite DataType `T`.
**Examples**
```
julia> struct Foo
x::Int64
y::String
end
julia> fieldtype(Foo, :x)
Int64
julia> fieldtype(Foo, 2)
String
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L715-L733)###
`Base.fieldtypes`Function
```
fieldtypes(T::Type)
```
The declared types of all fields in a composite DataType `T` as a tuple.
This function requires at least Julia 1.1.
**Examples**
```
julia> struct Foo
x::Int64
y::String
end
julia> fieldtypes(Foo)
(Int64, String)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L812-L830)###
`Base.fieldcount`Function
```
fieldcount(t::Type)
```
Get the number of fields that an instance of the given type would have. An error is thrown if the type is too abstract to determine this.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L772-L777)###
`Base.hasfield`Function
```
hasfield(T::Type, name::Symbol)
```
Return a boolean indicating whether `T` has `name` as one of its own fields.
See also [`fieldnames`](#Base.fieldnames), [`fieldcount`](#Base.fieldcount), [`hasproperty`](#Base.hasproperty).
This function requires at least Julia 1.2.
**Examples**
```
julia> struct Foo
bar::Int
end
julia> hasfield(Foo, :bar)
true
julia> hasfield(Foo, :x)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L192-L214)###
`Core.nfields`Function
```
nfields(x) -> Int
```
Get the number of fields in the given object.
**Examples**
```
julia> a = 1//2;
julia> nfields(a)
2
julia> b = 1
1
julia> nfields(b)
0
julia> ex = ErrorException("I've done a bad thing");
julia> nfields(ex)
1
```
In these examples, `a` is a [`Rational`](../numbers/index#Base.Rational), which has two fields. `b` is an `Int`, which is a primitive bitstype with no fields at all. `ex` is an [`ErrorException`](#Core.ErrorException), which has one field.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1559-L1586)###
`Base.isconst`Function
```
isconst(m::Module, s::Symbol) -> Bool
```
Determine whether a global is declared `const` in a given module `m`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L263-L267)
```
isconst(t::DataType, s::Union{Int,Symbol}) -> Bool
```
Determine whether a field `s` is declared `const` in a given type `t`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L271-L275)###
[Memory layout](#Memory-layout)
###
`Base.sizeof`Method
```
sizeof(T::DataType)
sizeof(obj)
```
Size, in bytes, of the canonical binary representation of the given `DataType` `T`, if any. Or the size, in bytes, of object `obj` if it is not a `DataType`.
See also [`summarysize`](#Base.summarysize).
**Examples**
```
julia> sizeof(Float32)
4
julia> sizeof(ComplexF64)
16
julia> sizeof(1.0)
8
julia> sizeof(collect(1.0:10.0))
80
```
If `DataType` `T` does not have a specific size, an error is thrown.
```
julia> sizeof(AbstractArray)
ERROR: Abstract type AbstractArray does not have a definite size.
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L440-L472)###
`Base.isconcretetype`Function
```
isconcretetype(T)
```
Determine whether type `T` is a concrete type, meaning it could have direct instances (values `x` such that `typeof(x) === T`).
See also: [`isbits`](#Base.isbits), [`isabstracttype`](#Base.isabstracttype), [`issingletontype`](#Base.issingletontype).
**Examples**
```
julia> isconcretetype(Complex)
false
julia> isconcretetype(Complex{Float32})
true
julia> isconcretetype(Vector{Complex})
true
julia> isconcretetype(Vector{Complex{Float32}})
true
julia> isconcretetype(Union{})
false
julia> isconcretetype(Union{Int,String})
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L616-L644)###
`Base.isbits`Function
```
isbits(x)
```
Return `true` if `x` is an instance of an [`isbitstype`](#Base.isbitstype) type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L588-L592)###
`Base.isbitstype`Function
```
isbitstype(T)
```
Return `true` if type `T` is a "plain data" type, meaning it is immutable and contains no references to other values, only `primitive` types and other `isbitstype` types. Typical examples are numeric types such as [`UInt8`](../numbers/index#Core.UInt8), [`Float64`](../numbers/index#Core.Float64), and [`Complex{Float64}`](../numbers/index#Base.Complex). This category of types is significant since they are valid as type parameters, may not track [`isdefined`](#Core.isdefined) / [`isassigned`](../arrays/index#Base.isassigned) status, and have a defined layout that is compatible with C.
See also [`isbits`](#Base.isbits), [`isprimitivetype`](#Base.isprimitivetype), [`ismutable`](#Base.ismutable).
**Examples**
```
julia> isbitstype(Complex{Float64})
true
julia> isbitstype(Complex)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L563-L585)###
`Base.fieldoffset`Function
```
fieldoffset(type, i)
```
The byte offset of field `i` of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct:
```
julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)];
julia> structinfo(Base.Filesystem.StatStruct)
13-element Vector{Tuple{UInt64, Symbol, Type}}:
(0x0000000000000000, :desc, Union{RawFD, String})
(0x0000000000000008, :device, UInt64)
(0x0000000000000010, :inode, UInt64)
(0x0000000000000018, :mode, UInt64)
(0x0000000000000020, :nlink, Int64)
(0x0000000000000028, :uid, UInt64)
(0x0000000000000030, :gid, UInt64)
(0x0000000000000038, :rdev, UInt64)
(0x0000000000000040, :size, Int64)
(0x0000000000000048, :blksize, Int64)
(0x0000000000000050, :blocks, Int64)
(0x0000000000000058, :mtime, Float64)
(0x0000000000000060, :ctime, Float64)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L687-L712)###
`Base.datatype_alignment`Function
```
Base.datatype_alignment(dt::DataType) -> Int
```
Memory allocation minimum alignment for instances of this type. Can be called on any `isconcretetype`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L356-L361)###
`Base.datatype_haspadding`Function
```
Base.datatype_haspadding(dt::DataType) -> Bool
```
Return whether the fields of instances of this type are packed in memory, with no intervening padding bytes. Can be called on any `isconcretetype`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L395-L401)###
`Base.datatype_pointerfree`Function
```
Base.datatype_pointerfree(dt::DataType) -> Bool
```
Return whether instances of this type can contain references to gc-managed memory. Can be called on any `isconcretetype`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L421-L426)###
[Special values](#Special-values)
###
`Base.typemin`Function
```
typemin(T)
```
The lowest value representable by the given (real) numeric DataType `T`.
**Examples**
```
julia> typemin(Float16)
-Inf16
julia> typemin(Float32)
-Inf32
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L742-L755)###
`Base.typemax`Function
```
typemax(T)
```
The highest value representable by the given (real) numeric `DataType`.
See also: [`floatmax`](#Base.floatmax), [`typemin`](#Base.typemin), [`eps`](#Base.eps-Tuple%7BType%7B<:AbstractFloat%7D%7D).
**Examples**
```
julia> typemax(Int8)
127
julia> typemax(UInt32)
0xffffffff
julia> typemax(Float64)
Inf
julia> floatmax(Float32) # largest finite floating point number
3.4028235f38
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/int.jl#L758-L779)###
`Base.floatmin`Function
```
floatmin(T = Float64)
```
Return the smallest positive normal number representable by the floating-point type `T`.
**Examples**
```
julia> floatmin(Float16)
Float16(6.104e-5)
julia> floatmin(Float32)
1.1754944f-38
julia> floatmin()
2.2250738585072014e-308
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L834-L851)###
`Base.floatmax`Function
```
floatmax(T = Float64)
```
Return the largest finite number representable by the floating-point type `T`.
See also: [`typemax`](#Base.typemax), [`floatmin`](#Base.floatmin), [`eps`](#Base.eps-Tuple%7BType%7B<:AbstractFloat%7D%7D).
**Examples**
```
julia> floatmax(Float16)
Float16(6.55e4)
julia> floatmax(Float32)
3.4028235f38
julia> floatmax()
1.7976931348623157e308
julia> typemax(Float64)
Inf
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L854-L875)###
`Base.maxintfloat`Function
```
maxintfloat(T=Float64)
```
The largest consecutive integer-valued floating-point number that is exactly represented in the given floating-point type `T` (which defaults to `Float64`).
That is, `maxintfloat` returns the smallest positive integer-valued floating-point number `n` such that `n+1` is *not* exactly representable in the type `T`.
When an `Integer`-type value is needed, use `Integer(maxintfloat(T))`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/floatfuncs.jl#L19-L29)
```
maxintfloat(T, S)
```
The largest consecutive integer representable in the given floating-point type `T` that also does not exceed the maximum integer representable by the integer type `S`. Equivalently, it is the minimum of `maxintfloat(T)` and [`typemax(S)`](#Base.typemax).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/floatfuncs.jl#L35-L41)###
`Base.eps`Method
```
eps(::Type{T}) where T<:AbstractFloat
eps()
```
Return the *machine epsilon* of the floating point type `T` (`T = Float64` by default). This is defined as the gap between 1 and the next largest value representable by `typeof(one(T))`, and is equivalent to `eps(one(T))`. (Since `eps(T)` is a bound on the *relative error* of `T`, it is a "dimensionless" quantity like [`one`](../numbers/index#Base.one).)
**Examples**
```
julia> eps()
2.220446049250313e-16
julia> eps(Float32)
1.1920929f-7
julia> 1.0 + eps()
1.0000000000000002
julia> 1.0 + eps()/2
1.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L881-L904)###
`Base.eps`Method
```
eps(x::AbstractFloat)
```
Return the *unit in last place* (ulp) of `x`. This is the distance between consecutive representable floating point values at `x`. In most cases, if the distance on either side of `x` is different, then the larger of the two is taken, that is
```
eps(x) == max(x-prevfloat(x), nextfloat(x)-x)
```
The exceptions to this rule are the smallest and largest finite values (e.g. `nextfloat(-Inf)` and `prevfloat(Inf)` for [`Float64`](../numbers/index#Core.Float64)), which round to the smaller of the values.
The rationale for this behavior is that `eps` bounds the floating point rounding error. Under the default `RoundNearest` rounding mode, if $y$ is a real number and $x$ is the nearest floating point number to $y$, then
\[|y-x| \leq \operatorname{eps}(x)/2.\]
See also: [`nextfloat`](../numbers/index#Base.nextfloat), [`issubnormal`](../numbers/index#Base.issubnormal), [`floatmax`](#Base.floatmax).
**Examples**
```
julia> eps(1.0)
2.220446049250313e-16
julia> eps(prevfloat(2.0))
2.220446049250313e-16
julia> eps(2.0)
4.440892098500626e-16
julia> x = prevfloat(Inf) # largest finite Float64
1.7976931348623157e308
julia> x + eps(x)/2 # rounds up
Inf
julia> x + prevfloat(eps(x)/2) # rounds down
1.7976931348623157e308
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/float.jl#L907-L950)###
`Base.instances`Function
```
instances(T::Type)
```
Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see `@enum`).
**Example**
```
julia> @enum Color red blue green
julia> instances(Color)
(red, blue, green)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L835-L848)
[Special Types](#Special-Types)
--------------------------------
###
`Core.Any`Type
```
Any::DataType
```
`Any` is the union of all types. It has the defining property `isa(x, Any) == true` for any `x`. `Any` therefore describes the entire universe of possible values. For example `Integer` is a subset of `Any` that includes `Int`, `Int8`, and other integer types.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2491-L2497)###
`Core.Union`Type
```
Union{Types...}
```
A type union is an abstract type which includes all instances of any of its argument types. The empty union [`Union{}`](#Union%7B%7D) is the bottom type of Julia.
**Examples**
```
julia> IntOrString = Union{Int,AbstractString}
Union{Int64, AbstractString}
julia> 1 :: IntOrString
1
julia> "Hello!" :: IntOrString
"Hello!"
julia> 1.0 :: IntOrString
ERROR: TypeError: in typeassert, expected Union{Int64, AbstractString}, got a value of type Float64
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2515-L2535)###
`Union{}`Keyword
```
Union{}
```
`Union{}`, the empty [`Union`](#Core.Union) of types, is the type that has no values. That is, it has the defining property `isa(x, Union{}) == false` for any `x`. `Base.Bottom` is defined as its alias and the type of `Union{}` is `Core.TypeofBottom`.
**Examples**
```
julia> isa(nothing, Union{})
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2500-L2512)###
`Core.UnionAll`Type
```
UnionAll
```
A union of types over all values of a type parameter. `UnionAll` is used to describe parametric types where the values of some parameters are not known.
**Examples**
```
julia> typeof(Vector)
UnionAll
julia> typeof(Vector{Int})
DataType
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2539-L2553)###
`Core.Tuple`Type
```
Tuple{Types...}
```
Tuples are an abstraction of the arguments of a function – without the function itself. The salient aspects of a function's arguments are their order and their types. Therefore a tuple type is similar to a parameterized immutable type where each parameter is the type of one field. Tuple types may have any number of parameters.
Tuple types are covariant in their parameters: `Tuple{Int}` is a subtype of `Tuple{Any}`. Therefore `Tuple{Any}` is considered an abstract type, and tuple types are only concrete if their parameters are. Tuples do not have field names; fields are only accessed by index.
See the manual section on [Tuple Types](../../manual/types/index#Tuple-Types).
See also [`Vararg`](#Core.Vararg), [`NTuple`](#Core.NTuple), [`tuple`](#Core.tuple), [`NamedTuple`](#Core.NamedTuple).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2622-L2636)###
`Core.NTuple`Type
```
NTuple{N, T}
```
A compact way of representing the type for a tuple of length `N` where all elements are of type `T`.
**Examples**
```
julia> isa((1, 2, 3, 4, 5, 6), NTuple{6, Int})
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/tuple.jl#L4-L14)###
`Core.NamedTuple`Type
```
NamedTuple
```
`NamedTuple`s are, as their name suggests, named [`Tuple`](#Core.Tuple)s. That is, they're a tuple-like collection of values, where each entry has a unique name, represented as a [`Symbol`](#Core.Symbol). Like `Tuple`s, `NamedTuple`s are immutable; neither the names nor the values can be modified in place after construction.
Accessing the value associated with a name in a named tuple can be done using field access syntax, e.g. `x.a`, or using [`getindex`](../collections/index#Base.getindex), e.g. `x[:a]` or `x[(:a, :b)]`. A tuple of the names can be obtained using [`keys`](../collections/index#Base.keys), and a tuple of the values can be obtained using [`values`](../collections/index#Base.values).
Iteration over `NamedTuple`s produces the *values* without the names. (See example below.) To iterate over the name-value pairs, use the [`pairs`](../collections/index#Base.pairs) function.
The [`@NamedTuple`](#Base.@NamedTuple) macro can be used for conveniently declaring `NamedTuple` types.
**Examples**
```
julia> x = (a=1, b=2)
(a = 1, b = 2)
julia> x.a
1
julia> x[:a]
1
julia> x[(:a,)]
(a = 1,)
julia> keys(x)
(:a, :b)
julia> values(x)
(1, 2)
julia> collect(x)
2-element Vector{Int64}:
1
2
julia> collect(pairs(x))
2-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 2
```
In a similar fashion as to how one can define keyword arguments programmatically, a named tuple can be created by giving a pair `name::Symbol => value` or splatting an iterator yielding such pairs after a semicolon inside a tuple literal:
```
julia> (; :a => 1)
(a = 1,)
julia> keys = (:a, :b, :c); values = (1, 2, 3);
julia> (; zip(keys, values)...)
(a = 1, b = 2, c = 3)
```
As in keyword arguments, identifiers and dot expressions imply names:
```
julia> x = 0
0
julia> t = (; x)
(x = 0,)
julia> (; t.x)
(x = 0,)
```
Implicit names from identifiers and dot expressions are available as of Julia 1.5.
Use of `getindex` methods with multiple `Symbol`s is available as of Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/namedtuple.jl#L3-L85)###
`Base.@NamedTuple`Macro
```
@NamedTuple{key1::Type1, key2::Type2, ...}
@NamedTuple begin key1::Type1; key2::Type2; ...; end
```
This macro gives a more convenient syntax for declaring `NamedTuple` types. It returns a `NamedTuple` type with the given keys and types, equivalent to `NamedTuple{(:key1, :key2, ...), Tuple{Type1,Type2,...}}`. If the `::Type` declaration is omitted, it is taken to be `Any`. The `begin ... end` form allows the declarations to be split across multiple lines (similar to a `struct` declaration), but is otherwise equivalent.
For example, the tuple `(a=3.1, b="hello")` has a type `NamedTuple{(:a, :b),Tuple{Float64,String}}`, which can also be declared via `@NamedTuple` as:
```
julia> @NamedTuple{a::Float64, b::String}
NamedTuple{(:a, :b), Tuple{Float64, String}}
julia> @NamedTuple begin
a::Float64
b::String
end
NamedTuple{(:a, :b), Tuple{Float64, String}}
```
This macro is available as of Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/namedtuple.jl#L382-L408)###
`Base.Val`Type
```
Val(c)
```
Return `Val{c}()`, which contains no run-time data. Types like this can be used to pass the information between functions through the value `c`, which must be an `isbits` value or a `Symbol`. The intent of this construct is to be able to dispatch on constants directly (at compile time) without having to test the value of the constant at run time.
**Examples**
```
julia> f(::Val{true}) = "Good"
f (generic function with 1 method)
julia> f(::Val{false}) = "Bad"
f (generic function with 2 methods)
julia> f(Val(true))
"Good"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L691-L710)###
`Core.Vararg`Constant
```
Vararg{T,N}
```
The last parameter of a tuple type [`Tuple`](#Core.Tuple) can be the special value `Vararg`, which denotes any number of trailing elements. `Vararg{T,N}` corresponds to exactly `N` elements of type `T`. Finally `Vararg{T}` corresponds to zero or more elements of type `T`. `Vararg` tuple types are used to represent the arguments accepted by varargs methods (see the section on [Varargs Functions](../../manual/functions/index#Varargs-Functions) in the manual.)
See also [`NTuple`](#Core.NTuple).
**Examples**
```
julia> mytupletype = Tuple{AbstractString, Vararg{Int}}
Tuple{AbstractString, Vararg{Int64}}
julia> isa(("1",), mytupletype)
true
julia> isa(("1",1), mytupletype)
true
julia> isa(("1",1,2), mytupletype)
true
julia> isa(("1",1,2,3.0), mytupletype)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2592-L2619)###
`Core.Nothing`Type
```
Nothing
```
A type with no fields that is the type of [`nothing`](../constants/index#Core.nothing).
See also: [`isnothing`](#Base.isnothing), [`Some`](#Base.Some), [`Missing`](#Base.Missing).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1280-L1286)###
`Base.isnothing`Function
```
isnothing(x)
```
Return `true` if `x === nothing`, and return `false` if not.
This function requires at least Julia 1.1.
See also [`something`](#Base.something), [`notnothing`](#Base.notnothing), [`ismissing`](#Base.ismissing).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/some.jl#L60-L69)###
`Base.notnothing`Function
```
notnothing(x)
```
Throw an error if `x === nothing`, and return `x` if not.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/some.jl#L52-L56)###
`Base.Some`Type
```
Some{T}
```
A wrapper type used in `Union{Some{T}, Nothing}` to distinguish between the absence of a value ([`nothing`](../constants/index#Core.nothing)) and the presence of a `nothing` value (i.e. `Some(nothing)`).
Use [`something`](#Base.something) to access the value wrapped by a `Some` object.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/some.jl#L3-L10)###
`Base.something`Function
```
something(x...)
```
Return the first value in the arguments which is not equal to [`nothing`](../constants/index#Core.nothing), if any. Otherwise throw an error. Arguments of type [`Some`](#Base.Some) are unwrapped.
See also [`coalesce`](#Base.coalesce), [`skipmissing`](#Base.skipmissing), [`@something`](#Base.@something).
**Examples**
```
julia> something(nothing, 1)
1
julia> something(Some(1), nothing)
1
julia> something(missing, nothing)
missing
julia> something(nothing, nothing)
ERROR: ArgumentError: No value arguments present
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/some.jl#L73-L96)###
`Base.@something`Macro
```
@something(x...)
```
Short-circuiting version of [`something`](#Base.something).
**Examples**
```
julia> f(x) = (println("f($x)"); nothing);
julia> a = 1;
julia> a = @something a f(2) f(3) error("Unable to find default for `a`")
1
julia> b = nothing;
julia> b = @something b f(2) f(3) error("Unable to find default for `b`")
f(2)
f(3)
ERROR: Unable to find default for `b`
[...]
julia> b = @something b f(2) f(3) Some(nothing)
f(2)
f(3)
julia> b === nothing
true
```
This macro is available as of Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/some.jl#L105-L137)###
`Base.Enums.Enum`Type
```
Enum{T<:Integer}
```
The abstract supertype of all enumerated types defined with [`@enum`](#Base.Enums.@enum).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/Enums.jl#L10-L14)###
`Base.Enums.@enum`Macro
```
@enum EnumName[::BaseType] value1[=x] value2[=y]
```
Create an `Enum{BaseType}` subtype with name `EnumName` and enum member values of `value1` and `value2` with optional assigned values of `x` and `y`, respectively. `EnumName` can be used just like other types and enum member values as regular values, such as
**Examples**
```
julia> @enum Fruit apple=1 orange=2 kiwi=3
julia> f(x::Fruit) = "I'm a Fruit with value: $(Int(x))"
f (generic function with 1 method)
julia> f(apple)
"I'm a Fruit with value: 1"
julia> Fruit(1)
apple::Fruit = 1
```
Values can also be specified inside a `begin` block, e.g.
```
@enum EnumName begin
value1
value2
end
```
`BaseType`, which defaults to [`Int32`](../numbers/index#Core.Int32), must be a primitive subtype of `Integer`. Member values can be converted between the enum type and `BaseType`. `read` and `write` perform these conversions automatically. In case the enum is created with a non-default `BaseType`, `Integer(value1)` will return the integer `value1` with the type `BaseType`.
To list all the instances of an enum use `instances`, e.g.
```
julia> instances(Fruit)
(apple, orange, kiwi)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/Enums.jl#L87-L128)###
`Core.Expr`Type
```
Expr(head::Symbol, args...)
```
A type representing compound expressions in parsed julia code (ASTs). Each expression consists of a `head` `Symbol` identifying which kind of expression it is (e.g. a call, for loop, conditional statement, etc.), and subexpressions (e.g. the arguments of a call). The subexpressions are stored in a `Vector{Any}` field called `args`.
See the manual chapter on [Metaprogramming](../../manual/metaprogramming/index#Metaprogramming) and the developer documentation [Julia ASTs](https://docs.julialang.org/en/v1.8/devdocs/ast/#Julia-ASTs).
**Examples**
```
julia> Expr(:call, :+, 1, 2)
:(1 + 2)
julia> dump(:(a ? b : c))
Expr
head: Symbol if
args: Array{Any}((3,))
1: Symbol a
2: Symbol b
3: Symbol c
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L534-L559)###
`Core.Symbol`Type
```
Symbol
```
The type of object used to represent identifiers in parsed julia code (ASTs). Also often used as a name or label to identify an entity (e.g. as a dictionary key). `Symbol`s can be entered using the `:` quote operator:
```
julia> :name
:name
julia> typeof(:name)
Symbol
julia> x = 42
42
julia> eval(:x)
42
```
`Symbol`s can also be constructed from strings or other values by calling the constructor `Symbol(x...)`.
`Symbol`s are immutable and should be compared using `===`. The implementation re-uses the same object for all `Symbol`s with the same name, so comparison tends to be efficient (it can just compare pointers).
Unlike strings, `Symbol`s are "atomic" or "scalar" entities that do not support iteration over characters.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1875-L1903)###
`Core.Symbol`Method
```
Symbol(x...) -> Symbol
```
Create a [`Symbol`](#Core.Symbol) by concatenating the string representations of the arguments together.
**Examples**
```
julia> Symbol("my", "name")
:myname
julia> Symbol("day", 4)
:day4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1906-L1919)###
`Core.Module`Type
```
Module
```
A `Module` is a separate global variable workspace. See [`module`](#module) and the [manual section about modules](../../manual/modules/index#modules) for details.
```
Module(name::Symbol=:anonymous, std_imports=true, default_names=true)
```
Return a module with the specified name. A `baremodule` corresponds to `Module(:ModuleName, false)`
An empty module containing no names at all can be created with `Module(:ModuleName, false, false)`. This module will not import `Base` or `Core` and does not contain a reference to itself.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2812-L2823)
[Generic Functions](#Generic-Functions)
----------------------------------------
###
`Core.Function`Type
```
Function
```
Abstract type of all functions.
**Examples**
```
julia> isa(+, Function)
true
julia> typeof(sin)
typeof(sin) (singleton type of function sin, subtype of Function)
julia> ans <: Function
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1356-L1372)###
`Base.hasmethod`Function
```
hasmethod(f, t::Type{<:Tuple}[, kwnames]; world=get_world_counter()) -> Bool
```
Determine whether the given generic function has a method matching the given `Tuple` of argument types with the upper bound of world age given by `world`.
If a tuple of keyword argument names `kwnames` is provided, this also checks whether the method of `f` matching `t` has the given keyword argument names. If the matching method accepts a variable number of keyword arguments, e.g. with `kwargs...`, any names given in `kwnames` are considered valid. Otherwise the provided names must be a subset of the method's keyword arguments.
See also [`applicable`](#Core.applicable).
Providing keyword argument names requires Julia 1.2 or later.
**Examples**
```
julia> hasmethod(length, Tuple{Array})
true
julia> f(; oranges=0) = oranges;
julia> hasmethod(f, Tuple{}, (:oranges,))
true
julia> hasmethod(f, Tuple{}, (:apples, :bananas))
false
julia> g(; xs...) = 4;
julia> hasmethod(g, Tuple{}, (:a, :b, :c, :d)) # g accepts arbitrary kwargs
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1480-L1515)###
`Core.applicable`Function
```
applicable(f, args...) -> Bool
```
Determine whether the given generic function has a method applicable to the given arguments.
See also [`hasmethod`](#Base.hasmethod).
**Examples**
```
julia> function f(x, y)
x + y
end;
julia> applicable(f, 1)
false
julia> applicable(f, 1, 2)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1661-L1680)###
`Base.isambiguous`Function
```
Base.isambiguous(m1, m2; ambiguous_bottom=false) -> Bool
```
Determine whether two methods `m1` and `m2` may be ambiguous for some call signature. This test is performed in the context of other methods of the same function; in isolation, `m1` and `m2` might be ambiguous, but if a third method resolving the ambiguity has been defined, this returns `false`. Alternatively, in isolation `m1` and `m2` might be ordered, but if a third method cannot be sorted with them, they may cause an ambiguity together.
For parametric types, the `ambiguous_bottom` keyword argument controls whether `Union{}` counts as an ambiguous intersection of type parameters – when `true`, it is considered ambiguous, when `false` it is not.
**Examples**
```
julia> foo(x::Complex{<:Integer}) = 1
foo (generic function with 1 method)
julia> foo(x::Complex{<:Rational}) = 2
foo (generic function with 2 methods)
julia> m1, m2 = collect(methods(foo));
julia> typeintersect(m1.sig, m2.sig)
Tuple{typeof(foo), Complex{Union{}}}
julia> Base.isambiguous(m1, m2, ambiguous_bottom=true)
true
julia> Base.isambiguous(m1, m2, ambiguous_bottom=false)
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1579-L1612)###
`Core.invoke`Function
```
invoke(f, argtypes::Type, args...; kwargs...)
```
Invoke a method for the given generic function `f` matching the specified types `argtypes` on the specified arguments `args` and passing the keyword arguments `kwargs`. The arguments `args` must conform with the specified types in `argtypes`, i.e. conversion is not automatically performed. This method allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).
Be careful when using `invoke` for functions that you don't write. What definition is used for given `argtypes` is an implementation detail unless the function is explicitly states that calling with certain `argtypes` is a part of public API. For example, the change between `f1` and `f2` in the example below is usually considered compatible because the change is invisible by the caller with a normal (non-`invoke`) call. However, the change is visible if you use `invoke`.
**Examples**
```
julia> f(x::Real) = x^2;
julia> f(x::Integer) = 1 + invoke(f, Tuple{Real}, x);
julia> f(2)
5
julia> f1(::Integer) = Integer
f1(::Real) = Real;
julia> f2(x::Real) = _f2(x)
_f2(::Integer) = Integer
_f2(_) = Real;
julia> f1(1)
Integer
julia> f2(1)
Integer
julia> invoke(f1, Tuple{Real}, 1)
Real
julia> invoke(f2, Tuple{Real}, 1)
Integer
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1683-L1728)###
`Base.@invoke`Macro
```
@invoke f(arg::T, ...; kwargs...)
```
Provides a convenient way to call [`invoke`](#Core.invoke); `@invoke f(arg1::T1, arg2::T2; kwargs...)` will be expanded into `invoke(f, Tuple{T1,T2}, arg1, arg2; kwargs...)`. When an argument's type annotation is omitted, it's specified as `Any` argument, e.g. `@invoke f(arg1::T, arg2)` will be expanded into `invoke(f, Tuple{T,Any}, arg1, arg2)`.
This macro requires Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1767-L1777)###
`Base.invokelatest`Function
```
invokelatest(f, args...; kwargs...)
```
Calls `f(args...; kwargs...)`, but guarantees that the most recent method of `f` will be executed. This is useful in specialized circumstances, e.g. long-running event loops or callback functions that may call obsolete versions of a function `f`. (The drawback is that `invokelatest` is somewhat slower than calling `f` directly, and the type of the result cannot be inferred by the compiler.)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L716-L725)###
`Base.@invokelatest`Macro
```
@invokelatest f(args...; kwargs...)
```
Provides a convenient way to call [`Base.invokelatest`](#Base.invokelatest). `@invokelatest f(args...; kwargs...)` will simply be expanded into `Base.invokelatest(f, args...; kwargs...)`.
This macro requires Julia 1.7 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1787-L1796)###
`new`Keyword
```
new, or new{A,B,...}
```
Special function available to inner constructors which creates a new object of the type. The form new{A,B,...} explicitly specifies values of parameters for parametric types. See the manual section on [Inner Constructor Methods](../../manual/constructors/index#man-inner-constructor-methods) for more information.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1190-L1197)###
`Base.:|>`Function
```
|>(x, f)
```
Applies a function to the preceding argument. This allows for easy function chaining.
**Examples**
```
julia> [1:5;] |> (x->x.^2) |> sum |> inv
0.01818181818181818
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L900-L910)###
`Base.:∘`Function
```
f ∘ g
```
Compose functions: i.e. `(f ∘ g)(args...; kwargs...)` means `f(g(args...; kwargs...))`. The `∘` symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing `\circ<tab>`.
Function composition also works in prefix form: `∘(f, g)` is the same as `f ∘ g`. The prefix form supports composition of multiple functions: `∘(f, g, h) = f ∘ g ∘ h` and splatting `∘(fs...)` for composing an iterable collection of functions.
Multiple function composition requires at least Julia 1.4.
Composition of one function ∘(f) requires at least Julia 1.5.
Using keyword arguments requires at least Julia 1.7.
**Examples**
```
julia> map(uppercase∘first, ["apple", "banana", "carrot"])
3-element Vector{Char}:
'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase)
'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
'C': ASCII/Unicode U+0043 (category Lu: Letter, uppercase)
julia> fs = [
x -> 2x
x -> x/2
x -> x-1
x -> x+1
];
julia> ∘(fs...)(3)
3.0
```
See also [`ComposedFunction`](#Base.ComposedFunction), [`!f::Function`](../math/index#Base.:!).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L954-L992)###
`Base.ComposedFunction`Type
```
ComposedFunction{Outer,Inner} <: Function
```
Represents the composition of two callable objects `outer::Outer` and `inner::Inner`. That is
```
ComposedFunction(outer, inner)(args...; kw...) === outer(inner(args...; kw...))
```
The preferred way to construct instance of `ComposedFunction` is to use the composition operator [`∘`](#Base.:%E2%88%98):
```
julia> sin ∘ cos === ComposedFunction(sin, cos)
true
julia> typeof(sin∘cos)
ComposedFunction{typeof(sin), typeof(cos)}
```
The composed pieces are stored in the fields of `ComposedFunction` and can be retrieved as follows:
```
julia> composition = sin ∘ cos
sin ∘ cos
julia> composition.outer === sin
true
julia> composition.inner === cos
true
```
ComposedFunction requires at least Julia 1.6. In earlier versions `∘` returns an anonymous function instead.
See also [`∘`](#Base.:%E2%88%98).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L995-L1025)###
`Base.splat`Function
```
splat(f)
```
Defined as
```
splat(f) = args->f(args...)
```
i.e. given a function returns a new function that takes one argument and splats its argument into the original function. This is useful as an adaptor to pass a multi-argument function in a context that expects a single argument, but passes a tuple as that single argument.
**Example usage:**
```
julia> map(Base.splat(+), zip(1:3,4:6))
3-element Vector{Int64}:
5
7
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1202-L1222)###
`Base.Fix1`Type
```
Fix1(f, x)
```
A type representing a partially-applied version of the two-argument function `f`, with the first argument fixed to the value "x". In other words, `Fix1(f, x)` behaves similarly to `y->f(x, y)`.
See also [`Fix2`](#Base.Fix2).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1079-L1087)###
`Base.Fix2`Type
```
Fix2(f, x)
```
A type representing a partially-applied version of the two-argument function `f`, with the second argument fixed to the value "x". In other words, `Fix2(f, x)` behaves similarly to `y->f(y, x)`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/operators.jl#L1098-L1104)
[Syntax](#Syntax)
------------------
###
`Core.eval`Function
```
Core.eval(m::Module, expr)
```
Evaluate an expression in the given module and return the result.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L176-L180)###
`Base.MainInclude.eval`Function
```
eval(expr)
```
Evaluate an expression in the global scope of the containing module. Every `Module` (except those defined with `baremodule`) has its own 1-argument definition of `eval`, which evaluates expressions in that module.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/client.jl#L481-L487)###
`Base.@eval`Macro
```
@eval [mod,] ex
```
Evaluate an expression with values interpolated into it using `eval`. If two arguments are provided, the first is the module to evaluate in.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L220-L225)###
`Base.evalfile`Function
```
evalfile(path::AbstractString, args::Vector{String}=String[])
```
Load the file using [`include`](#Base.include), evaluate all expressions, and return the value of the last one.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L1498-L1503)###
`Base.esc`Function
```
esc(e)
```
Only valid in the context of an [`Expr`](#Core.Expr) returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the [Macros](../../manual/metaprogramming/index#man-macros) section of the Metaprogramming chapter of the manual for more details and examples.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L494-L500)###
`Base.@inbounds`Macro
```
@inbounds(blk)
```
Eliminates array bounds checking within expressions.
In the example below the in-range check for referencing element `i` of array `A` is skipped to improve performance.
```
function sum(A::AbstractArray)
r = zero(eltype(A))
for i in eachindex(A)
@inbounds r += A[i]
end
return r
end
```
Using `@inbounds` may return incorrect results/crashes/corruption for out-of-bounds indices. The user is responsible for checking it manually. Only use `@inbounds` when it is certain from the information locally available that all accesses are in bounds.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L551-L575)###
`Base.@boundscheck`Macro
```
@boundscheck(blk)
```
Annotates the expression `blk` as a bounds checking block, allowing it to be elided by [`@inbounds`](#Base.@inbounds).
The function in which `@boundscheck` is written must be inlined into its caller in order for `@inbounds` to have effect.
**Examples**
```
julia> @inline function g(A, i)
@boundscheck checkbounds(A, i)
return "accessing ($A)[$i]"
end;
julia> f1() = return g(1:2, -1);
julia> f2() = @inbounds return g(1:2, -1);
julia> f1()
ERROR: BoundsError: attempt to access 2-element UnitRange{Int64} at index [-1]
Stacktrace:
[1] throw_boundserror(::UnitRange{Int64}, ::Tuple{Int64}) at ./abstractarray.jl:455
[2] checkbounds at ./abstractarray.jl:420 [inlined]
[3] g at ./none:2 [inlined]
[4] f1() at ./none:1
[5] top-level scope
julia> f2()
"accessing (1:2)[-1]"
```
The `@boundscheck` annotation allows you, as a library writer, to opt-in to allowing *other code* to remove your bounds checks with [`@inbounds`](#Base.@inbounds). As noted there, the caller must verify—using information they can access—that their accesses are valid before using `@inbounds`. For indexing into your [`AbstractArray`](../arrays/index#Core.AbstractArray) subclasses, for example, this involves checking the indices against its [`axes`](#). Therefore, `@boundscheck` annotations should only be added to a [`getindex`](../collections/index#Base.getindex) or [`setindex!`](../collections/index#Base.setindex!) implementation after you are certain its behavior is correct.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L503-L546)###
`Base.@propagate_inbounds`Macro
```
@propagate_inbounds
```
Tells the compiler to inline a function while retaining the caller's inbounds context.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L637-L641)###
`Base.@inline`Macro
```
@inline
```
Give a hint to the compiler that this function is worth inlining.
Small functions typically do not need the `@inline` annotation, as the compiler does it automatically. By using `@inline` on bigger functions, an extra nudge can be given to the compiler to inline it.
`@inline` can be applied immediately before the definition or in its function body.
```
# annotate long-form definition
@inline function longdef(x)
...
end
# annotate short-form definition
@inline shortdef(x) = ...
# annotate anonymous function that a `do` block creates
f() do
@inline
...
end
```
The usage within a function body requires at least Julia 1.8.
---
```
@inline block
```
Give a hint to the compiler that calls within `block` are worth inlining.
```
# The compiler will try to inline `f`
@inline f(...)
# The compiler will try to inline `f`, `g` and `+`
@inline f(...) + g(...)
```
A callsite annotation always has the precedence over the annotation applied to the definition of the called function:
```
@noinline function explicit_noinline(args...)
# body
end
let
@inline explicit_noinline(args...) # will be inlined
end
```
When there are nested callsite annotations, the innermost annotation has the precedence:
```
@noinline let a0, b0 = ...
a = @inline f(a0) # the compiler will try to inline this call
b = f(b0) # the compiler will NOT try to inline this call
return a, b
end
```
Although a callsite annotation will try to force inlining in regardless of the cost model, there are still chances it can't succeed in it. Especially, recursive calls can not be inlined even if they are annotated as `@inline`d.
The callsite annotation requires at least Julia 1.8.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L183-L256)###
`Base.@noinline`Macro
```
@noinline
```
Give a hint to the compiler that it should not inline a function.
Small functions are typically inlined automatically. By using `@noinline` on small functions, auto-inlining can be prevented.
`@noinline` can be applied immediately before the definition or in its function body.
```
# annotate long-form definition
@noinline function longdef(x)
...
end
# annotate short-form definition
@noinline shortdef(x) = ...
# annotate anonymous function that a `do` block creates
f() do
@noinline
...
end
```
The usage within a function body requires at least Julia 1.8.
---
```
@noinline block
```
Give a hint to the compiler that it should not inline the calls within `block`.
```
# The compiler will try to not inline `f`
@noinline f(...)
# The compiler will try to not inline `f`, `g` and `+`
@noinline f(...) + g(...)
```
A callsite annotation always has the precedence over the annotation applied to the definition of the called function:
```
@inline function explicit_inline(args...)
# body
end
let
@noinline explicit_inline(args...) # will not be inlined
end
```
When there are nested callsite annotations, the innermost annotation has the precedence:
```
@inline let a0, b0 = ...
a = @noinline f(a0) # the compiler will NOT try to inline this call
b = f(b0) # the compiler will try to inline this call
return a, b
end
```
The callsite annotation requires at least Julia 1.8.
---
If the function is trivial (for example returning a constant) it might get inlined anyway.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L261-L333)###
`Base.@nospecialize`Macro
```
@nospecialize
```
Applied to a function argument name, hints to the compiler that the method should not be specialized for different types of that argument, but instead to use precisely the declared type for each argument. This is only a hint for avoiding excess code generation. Can be applied to an argument within a formal argument list, or in the function body. When applied to an argument, the macro must wrap the entire argument expression. When used in a function body, the macro must occur in statement position and before any code.
When used without arguments, it applies to all arguments of the parent scope. In local scope, this means all arguments of the containing function. In global (top-level) scope, this means all methods subsequently defined in the current module.
Specialization can reset back to the default by using [`@specialize`](#Base.@specialize).
```
function example_function(@nospecialize x)
...
end
function example_function(x, @nospecialize(y = 1))
...
end
function example_function(x, y, z)
@nospecialize x y
...
end
@nospecialize
f(y) = [x for x in y]
@specialize
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L53-L90)###
`Base.@specialize`Macro
```
@specialize
```
Reset the specialization hint for an argument back to the default. For details, see [`@nospecialize`](#Base.@nospecialize).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L102-L107)###
`Base.gensym`Function
```
gensym([tag])
```
Generates a symbol which will not conflict with other variable names.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L5-L9)###
`Base.@gensym`Macro
```
@gensym
```
Generates a gensym symbol for a variable. For example, `@gensym x y` is transformed into `x = gensym("x"); y = gensym("y")`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L17-L22)###
`var"name"`Keyword
```
var
```
The syntax `var"#example#"` refers to a variable named `Symbol("#example#")`, even though `#example#` is not a valid Julia identifier name.
This can be useful for interoperability with programming languages which have different rules for the construction of valid identifiers. For example, to refer to the `R` variable `draw.segments`, you can use `var"draw.segments"` in your Julia code.
It is also used to `show` julia source code which has gone through macro hygiene or otherwise contains variable names which can't be parsed normally.
Note that this syntax requires parser support so it is expanded directly by the parser rather than being implemented as a normal string macro `@var_str`.
This syntax requires at least Julia 1.3.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1236-L1256)###
`Base.@goto`Macro
```
@goto name
```
`@goto name` unconditionally jumps to the statement at the location [`@label name`](#Base.@label).
`@label` and `@goto` cannot create jumps to different top-level statements. Attempts cause an error. To still use `@goto`, enclose the `@label` and `@goto` in a block.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L594-L601)###
`Base.@label`Macro
```
@label name
```
Labels a statement with the symbolic label `name`. The label marks the end-point of an unconditional jump with [`@goto name`](#Base.@goto).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L584-L589)###
`Base.SimdLoop.@simd`Macro
```
@simd
```
Annotate a `for` loop to allow the compiler to take extra liberties to allow loop re-ordering
This feature is experimental and could change or disappear in future versions of Julia. Incorrect use of the `@simd` macro may cause unexpected results.
The object iterated over in a `@simd for` loop should be a one-dimensional range. By using `@simd`, you are asserting several properties of the loop:
* It is safe to execute iterations in arbitrary or overlapping order, with special consideration for reduction variables.
* Floating-point operations on reduction variables can be reordered, possibly causing different results than without `@simd`.
In many cases, Julia is able to automatically vectorize inner for loops without the use of `@simd`. Using `@simd` gives the compiler a little extra leeway to make it possible in more situations. In either case, your inner loop should have the following properties to allow vectorization:
* The loop must be an innermost loop
* The loop body must be straight-line code. Therefore, [`@inbounds`](#Base.@inbounds) is currently needed for all array accesses. The compiler can sometimes turn short `&&`, `||`, and `?:` expressions into straight-line code if it is safe to evaluate all operands unconditionally. Consider using the [`ifelse`](#Base.ifelse) function instead of `?:` in the loop if it is safe to do so.
* Accesses must have a stride pattern and cannot be "gathers" (random-index reads) or "scatters" (random-index writes).
* The stride should be unit stride.
The `@simd` does not assert by default that the loop is completely free of loop-carried memory dependencies, which is an assumption that can easily be violated in generic code. If you are writing non-generic code, you can use `@simd ivdep for ... end` to also assert that:
* There exists no loop-carried memory dependencies
* No iteration ever waits on a previous iteration to make forward progress.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/simdloop.jl#L90-L126)###
`Base.@polly`Macro
```
@polly
```
Tells the compiler to apply the polyhedral optimizer Polly to a function.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L650-L654)###
`Base.@generated`Macro
```
@generated f
```
`@generated` is used to annotate a function which will be generated. In the body of the generated function, only types of arguments can be read (not the values). The function returns a quoted expression evaluated when the function is called. The `@generated` macro should not be used on functions mutating the global scope or depending on mutable elements.
See [Metaprogramming](../../manual/metaprogramming/index#Metaprogramming) for further details.
**Example:**
```
julia> @generated function bar(x)
if x <: Integer
return :(x ^ 2)
else
return :(x)
end
end
bar (generic function with 1 method)
julia> bar(4)
16
julia> bar("baz")
"baz"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L807-L835)###
`Base.@pure`Macro
```
@pure ex
```
`@pure` gives the compiler a hint for the definition of a pure function, helping for type inference.
This macro is intended for internal compiler use and may be subject to changes.
In Julia 1.8 and higher, it is favorable to use [`@assume_effects`](#Base.@assume_effects) instead of `@pure`. This is because `@assume_effects` allows a finer grained control over Julia's purity modeling and the effect system enables a wider range of optimizations.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L338-L351)###
`Base.@assume_effects`Macro
```
@assume_effects setting... ex
```
`@assume_effects` overrides the compiler's effect modeling for the given method. `ex` must be a method definition or `@ccall` expression.
Using `Base.@assume_effects` requires Julia version 1.8.
```
julia> Base.@assume_effects :terminates_locally function pow(x)
# this :terminates_locally allows `pow` to be constant-folded
res = 1
1 < x < 20 || error("bad pow")
while x > 1
res *= x
x -= 1
end
return res
end
pow (generic function with 1 method)
julia> code_typed() do
pow(12)
end
1-element Vector{Any}:
CodeInfo(
1 ─ return 479001600
) => Int64
julia> Base.@assume_effects :total !:nothrow @ccall jl_type_intersection(Vector{Int}::Any, Vector{<:Integer}::Any)::Any
Vector{Int64} (alias for Array{Int64, 1})
```
Improper use of this macro causes undefined behavior (including crashes, incorrect answers, or other hard to track bugs). Use with care and only if absolutely required.
In general, each `setting` value makes an assertion about the behavior of the function, without requiring the compiler to prove that this behavior is indeed true. These assertions are made for all world ages. It is thus advisable to limit the use of generic functions that may later be extended to invalidate the assumption (which would cause undefined behavior).
The following `setting`s are supported.
* `:consistent`
* `:effect_free`
* `:nothrow`
* `:terminates_globally`
* `:terminates_locally`
* `:foldable`
* `:total`
**Extended help**
---
**`:consistent`**
The `:consistent` setting asserts that for egal (`===`) inputs:
* The manner of termination (return value, exception, non-termination) will always be the same.
* If the method returns, the results will always be egal.
This in particular implies that the return value of the method must be immutable. Multiple allocations of mutable objects (even with identical contents) are not egal.
The `:consistent`-cy assertion is made world-age wise. More formally, write $fᵢ$ for the evaluation of $f$ in world-age $i$, then we require:
\[∀ i, x, y: x ≡ y → fᵢ(x) ≡ fᵢ(y)\]
However, for two world ages $i$, $j$ s.t. $i ≠ j$, we may have $fᵢ(x) ≢ fⱼ(y)$.
A further implication is that `:consistent` functions may not make their return value dependent on the state of the heap or any other global state that is not constant for a given world age.
The `:consistent`-cy includes all legal rewrites performed by the optimizer. For example, floating-point fastmath operations are not considered `:consistent`, because the optimizer may rewrite them causing the output to not be `:consistent`, even for the same world age (e.g. because one ran in the interpreter, while the other was optimized).
If `:consistent` functions terminate by throwing an exception, that exception itself is not required to meet the egality requirement specified above.
---
**`:effect_free`**
The `:effect_free` setting asserts that the method is free of externally semantically visible side effects. The following is an incomplete list of externally semantically visible side effects:
* Changing the value of a global variable.
* Mutating the heap (e.g. an array or mutable value), except as noted below
* Changing the method table (e.g. through calls to eval)
* File/Network/etc. I/O
* Task switching
However, the following are explicitly not semantically visible, even if they may be observable:
* Memory allocations (both mutable and immutable)
* Elapsed time
* Garbage collection
* Heap mutations of objects whose lifetime does not exceed the method (i.e. were allocated in the method and do not escape).
* The returned value (which is externally visible, but not a side effect)
The rule of thumb here is that an externally visible side effect is anything that would affect the execution of the remainder of the program if the function were not executed.
The `:effect_free` assertion is made both for the method itself and any code that is executed by the method. Keep in mind that the assertion must be valid for all world ages and limit use of this assertion accordingly.
---
**`:nothrow`**
The `:nothrow` settings asserts that this method does not terminate abnormally (i.e. will either always return a value or never return).
It is permissible for `:nothrow` annotated methods to make use of exception handling internally as long as the exception is not rethrown out of the method itself.
`MethodErrors` and similar exceptions count as abnormal termination.
---
**`:terminates_globally`**
The `:terminates_globally` settings asserts that this method will eventually terminate (either normally or abnormally), i.e. does not loop indefinitely.
This `:terminates_globally` assertion covers any other methods called by the annotated method.
The compiler will consider this a strong indication that the method will terminate relatively *quickly* and may (if otherwise legal), call this method at compile time. I.e. it is a bad idea to annotate this setting on a method that *technically*, but not *practically*, terminates.
---
**`:terminates_locally`**
The `:terminates_locally` setting is like `:terminates_globally`, except that it only applies to syntactic control flow *within* the annotated method. It is thus a much weaker (and thus safer) assertion that allows for the possibility of non-termination if the method calls some other method that does not terminate.
`:terminates_globally` implies `:terminates_locally`.
---
**`:foldable`**
This setting is a convenient shortcut for the set of effects that the compiler requires to be guaranteed to constant fold a call at compile time. It is currently equivalent to the following `setting`s:
* `:consistent`
* `:effect_free`
* `:terminates_globally`
This list in particular does not include `:nothrow`. The compiler will still attempt constant propagation and note any thrown error at compile time. Note however, that by the `:consistent`-cy requirements, any such annotated call must consistently throw given the same argument values.
---
**`:total`**
This `setting` is the maximum possible set of effects. It currently implies the following other `setting`s:
* `:consistent`
* `:effect_free`
* `:nothrow`
* `:terminates_globally`
`:total` is a very strong assertion and will likely gain additional semantics in future versions of Julia (e.g. if additional effects are added and included in the definition of `:total`). As a result, it should be used with care. Whenever possible, prefer to use the minimum possible set of specific effect assertions required for a particular application. In cases where a large number of effect overrides apply to a set of functions, a custom macro is recommended over the use of `:total`.
---
**Negated effects**
Effect names may be prefixed by `!` to indicate that the effect should be removed from an earlier meta effect. For example, `:total !:nothrow` indicates that while the call is generally total, it may however throw.
---
**Comparison to `@pure`**
`@assume_effects :foldable` is similar to [`@pure`](#Base.@pure) with the primary distinction that the `:consistent`-cy requirement applies world-age wise rather than globally as described above. However, in particular, a method annotated `@pure` should always be at least `:foldable`. Another advantage is that effects introduced by `@assume_effects` are propagated to callers interprocedurally while a purity defined by `@pure` is not.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L378-L591)###
`Base.@deprecate`Macro
```
@deprecate old new [export_old=true]
```
Deprecate method `old` and specify the replacement call `new`. Prevent `@deprecate` from exporting `old` by setting `export_old` to `false`. `@deprecate` defines a new method with the same signature as `old`.
As of Julia 1.5, functions defined by `@deprecate` do not print warning when `julia` is run without the `--depwarn=yes` flag set, as the default value of `--depwarn` option is `no`. The warnings are printed from tests run by `Pkg.test()`.
**Examples**
```
julia> @deprecate old(x) new(x)
old (generic function with 1 method)
julia> @deprecate old(x) new(x) false
old (generic function with 1 method)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/deprecated.jl#L17-L37)
[Missing Values](#Missing-Values)
----------------------------------
###
`Base.Missing`Type
```
Missing
```
A type with no fields whose singleton instance [`missing`](#Base.missing) is used to represent missing values.
See also: [`skipmissing`](#Base.skipmissing), [`nonmissingtype`](#Base.nonmissingtype), [`Nothing`](#Core.Nothing).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L815-L822)###
`Base.missing`Constant
```
missing
```
The singleton instance of type [`Missing`](#Base.Missing) representing a missing value.
See also: [`NaN`](../numbers/index#Base.NaN), [`skipmissing`](#Base.skipmissing), [`nonmissingtype`](#Base.nonmissingtype).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L825-L831)###
`Base.coalesce`Function
```
coalesce(x...)
```
Return the first value in the arguments which is not equal to [`missing`](#Base.missing), if any. Otherwise return `missing`.
See also [`skipmissing`](#Base.skipmissing), [`something`](#Base.something), [`@coalesce`](#Base.@coalesce).
**Examples**
```
julia> coalesce(missing, 1)
1
julia> coalesce(1, missing)
1
julia> coalesce(nothing, 1) # returns `nothing`
julia> coalesce(missing, missing)
missing
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/missing.jl#L403-L425)###
`Base.@coalesce`Macro
```
@coalesce(x...)
```
Short-circuiting version of [`coalesce`](#Base.coalesce).
**Examples**
```
julia> f(x) = (println("f($x)"); missing);
julia> a = 1;
julia> a = @coalesce a f(2) f(3) error("`a` is still missing")
1
julia> b = missing;
julia> b = @coalesce b f(2) f(3) error("`b` is still missing")
f(2)
f(3)
ERROR: `b` is still missing
[...]
```
This macro is available as of Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/missing.jl#L433-L458)###
`Base.ismissing`Function
```
ismissing(x)
```
Indicate whether `x` is [`missing`](#Base.missing).
See also: [`skipmissing`](#Base.skipmissing), [`isnothing`](#Base.isnothing), [`isnan`](../numbers/index#Base.isnan).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L834-L840)###
`Base.skipmissing`Function
```
skipmissing(itr)
```
Return an iterator over the elements in `itr` skipping [`missing`](#Base.missing) values. The returned object can be indexed using indices of `itr` if the latter is indexable. Indices corresponding to missing values are not valid: they are skipped by [`keys`](../collections/index#Base.keys) and [`eachindex`](../arrays/index#Base.eachindex), and a `MissingException` is thrown when trying to use them.
Use [`collect`](#) to obtain an `Array` containing the non-`missing` values in `itr`. Note that even if `itr` is a multidimensional array, the result will always be a `Vector` since it is not possible to remove missings while preserving dimensions of the input.
See also [`coalesce`](#Base.coalesce), [`ismissing`](#Base.ismissing), [`something`](#Base.something).
**Examples**
```
julia> x = skipmissing([1, missing, 2])
skipmissing(Union{Missing, Int64}[1, missing, 2])
julia> sum(x)
3
julia> x[1]
1
julia> x[2]
ERROR: MissingException: the value at index (2,) is missing
[...]
julia> argmax(x)
3
julia> collect(keys(x))
2-element Vector{Int64}:
1
3
julia> collect(skipmissing([1, missing, 2]))
2-element Vector{Int64}:
1
2
julia> collect(skipmissing([1 missing; 2 missing]))
2-element Vector{Int64}:
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/missing.jl#L191-L239)###
`Base.nonmissingtype`Function
```
nonmissingtype(T::Type)
```
If `T` is a union of types containing `Missing`, return a new type with `Missing` removed.
**Examples**
```
julia> nonmissingtype(Union{Int64,Missing})
Int64
julia> nonmissingtype(Any)
Any
```
This function is exported as of Julia 1.3.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/missing.jl#L21-L38)
[System](#System)
------------------
###
`Base.run`Function
```
run(command, args...; wait::Bool = true)
```
Run a command object, constructed with backticks (see the [Running External Programs](../../manual/running-external-programs/index#Running-External-Programs) section in the manual). Throws an error if anything goes wrong, including the process exiting with a non-zero status (when `wait` is true).
The `args...` allow you to pass through file descriptors to the command, and are ordered like regular unix file descriptors (eg `stdin, stdout, stderr, FD(3), FD(4)...`).
If `wait` is false, the process runs asynchronously. You can later wait for it and check its exit status by calling `success` on the returned process object.
When `wait` is false, the process' I/O streams are directed to `devnull`. When `wait` is true, I/O streams are shared with the parent process. Use [`pipeline`](#Base.pipeline-Tuple%7BAny,%20Any,%20Any,%20Vararg%7BAny%7D%7D) to control I/O redirection.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L460-L476)###
`Base.devnull`Constant
```
devnull
```
Used in a stream redirect to discard all data written to it. Essentially equivalent to `/dev/null` on Unix or `NUL` on Windows. Usage:
```
run(pipeline(`cat test.txt`, devnull))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1266-L1275)###
`Base.success`Function
```
success(command)
```
Run a command object, constructed with backticks (see the [Running External Programs](../../manual/running-external-programs/index#Running-External-Programs) section in the manual), and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L529-L535)###
`Base.process_running`Function
```
process_running(p::Process)
```
Determine whether a process is currently running.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L626-L630)###
`Base.process_exited`Function
```
process_exited(p::Process)
```
Determine whether a process has exited.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L635-L639)###
`Base.kill`Method
```
kill(p::Process, signum=Base.SIGTERM)
```
Send a signal to a process. The default is to terminate the process. Returns successfully if the process has already exited, but throws an error if killing the process failed for other reasons (e.g. insufficient permissions).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L581-L588)###
`Base.Sys.set_process_title`Function
```
Sys.set_process_title(title::AbstractString)
```
Set the process title. No-op on some operating systems.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L302-L306)###
`Base.Sys.get_process_title`Function
```
Sys.get_process_title()
```
Get the process title. On some systems, will always return an empty string.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L290-L294)###
`Base.ignorestatus`Function
```
ignorestatus(command)
```
Mark a command object so that running it will not throw an error if the result code is non-zero.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L211-L215)###
`Base.detach`Function
```
detach(command)
```
Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L220-L224)###
`Base.Cmd`Type
```
Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)
```
Construct a new `Cmd` object, representing an external program and arguments, from `cmd`, while changing the settings of the optional keyword arguments:
* `ignorestatus::Bool`: If `true` (defaults to `false`), then the `Cmd` will not throw an error if the return code is nonzero.
* `detach::Bool`: If `true` (defaults to `false`), then the `Cmd` will be run in a new process group, allowing it to outlive the `julia` process and not have Ctrl-C passed to it.
* `windows_verbatim::Bool`: If `true` (defaults to `false`), then on Windows the `Cmd` will send a command-line string to the process with no quoting or escaping of arguments, even arguments containing spaces. (On Windows, arguments are sent to a program as a single "command-line" string, and programs are responsible for parsing it into arguments. By default, empty arguments and arguments with spaces or tabs are quoted with double quotes `"` in the command line, and `\` or `"` are preceded by backslashes. `windows_verbatim=true` is useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.
* `windows_hide::Bool`: If `true` (defaults to `false`), then on Windows no new console window is displayed when the `Cmd` is executed. This has no effect if a console is already open or on non-Windows systems.
* `env`: Set environment variables to use when running the `Cmd`. `env` is either a dictionary mapping strings to strings, an array of strings of the form `"var=val"`, an array or tuple of `"var"=>val` pairs. In order to modify (rather than replace) the existing environment, initialize `env` with `copy(ENV)` and then set `env["var"]=val` as desired. To add to an environment block within a `Cmd` object without replacing all elements, use [`addenv()`](#Base.addenv) which will return a `Cmd` object with the updated environment.
* `dir::AbstractString`: Specify a working directory for the command (instead of the current directory).
For any keywords that are not specified, the current settings from `cmd` are used. Normally, to create a `Cmd` object in the first place, one uses backticks, e.g.
```
Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L42-L77)###
`Base.setenv`Function
```
setenv(command::Cmd, env; dir)
```
Set environment variables to use when running the given `command`. `env` is either a dictionary mapping strings to strings, an array of strings of the form `"var=val"`, or zero or more `"var"=>val` pair arguments. In order to modify (rather than replace) the existing environment, create `env` through `copy(ENV)` and then setting `env["var"]=val` as desired, or use [`addenv`](#Base.addenv).
The `dir` keyword argument can be used to specify a working directory for the command. `dir` defaults to the currently set `dir` for `command` (which is the current working directory if not specified already).
See also [`Cmd`](#Base.Cmd), [`addenv`](#Base.addenv), [`ENV`](#Base.ENV), [`pwd`](../file/index#Base.Filesystem.pwd).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L245-L259)###
`Base.addenv`Function
```
addenv(command::Cmd, env...; inherit::Bool = true)
```
Merge new environment mappings into the given [`Cmd`](#Base.Cmd) object, returning a new `Cmd` object. Duplicate keys are replaced. If `command` does not contain any environment values set already, it inherits the current environment at time of `addenv()` call if `inherit` is `true`. Keys with value `nothing` are deleted from the env.
See also [`Cmd`](#Base.Cmd), [`setenv`](#Base.setenv), [`ENV`](#Base.ENV).
This function requires Julia 1.6 or later.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L274-L286)###
`Base.withenv`Function
```
withenv(f, kv::Pair...)
```
Execute `f` in an environment that is temporarily modified (not replaced as in `setenv`) by zero or more `"var"=>val` arguments `kv`. `withenv` is generally used via the `withenv(kv...) do ... end` syntax. A value of `nothing` can be used to temporarily unset an environment variable (if it is set). When `withenv` returns, the original environment has been restored.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/env.jl#L157-L165)###
`Base.setcpuaffinity`Function
```
setcpuaffinity(original_command::Cmd, cpus) -> command::Cmd
```
Set the CPU affinity of the `command` by a list of CPU IDs (1-based) `cpus`. Passing `cpus = nothing` means to unset the CPU affinity if the `original_command` has any.
This function is supported only in Linux and Windows. It is not supported in macOS because libuv does not support affinity setting.
This function requires at least Julia 1.8.
**Examples**
In Linux, the `taskset` command line program can be used to see how `setcpuaffinity` works.
```
julia> run(setcpuaffinity(`sh -c 'taskset -p $$'`, [1, 2, 5]));
pid 2273's current affinity mask: 13
```
Note that the mask value `13` reflects that the first, second, and the fifth bits (counting from the least significant position) are turned on:
```
julia> 0b010011
0x13
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L316-L344)###
`Base.pipeline`Method
```
pipeline(from, to, ...)
```
Create a pipeline from a data source to a destination. The source and destination can be commands, I/O streams, strings, or results of other `pipeline` calls. At least one argument must be a command. Strings refer to filenames. When called with more than two arguments, they are chained together from left to right. For example, `pipeline(a,b,c)` is equivalent to `pipeline(pipeline(a,b),c)`. This provides a more concise way to specify multi-stage pipelines.
**Examples**:
```
run(pipeline(`ls`, `grep xyz`))
run(pipeline(`ls`, "out.txt"))
run(pipeline("out.txt", `grep xyz`))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L400-L417)###
`Base.pipeline`Method
```
pipeline(command; stdin, stdout, stderr, append=false)
```
Redirect I/O to or from the given `command`. Keyword arguments specify which of the command's streams should be redirected. `append` controls whether file output appends to the file. This is a more general version of the 2-argument `pipeline` function. `pipeline(from, to)` is equivalent to `pipeline(from, stdout=to)` when `from` is a command, and to `pipeline(to, stdin=from)` when `from` is another kind of data source.
**Examples**:
```
run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt"))
run(pipeline(`update`, stdout="log.txt", append=true))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/cmd.jl#L365-L380)###
`Base.Libc.gethostname`Function
```
gethostname() -> AbstractString
```
Get the local machine's host name.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L262-L266)###
`Base.Libc.getpid`Function
```
getpid() -> Int32
```
Get Julia's process ID.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L253-L257)
```
getpid(process) -> Int32
```
Get the child process ID, if it still exists.
This function requires at least Julia 1.1.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L604-L611)###
`Base.Libc.time`Method
```
time()
```
Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/libc.jl#L244-L248)###
`Base.time_ns`Function
```
time_ns()
```
Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/Base.jl#L86-L90)###
`Base.@time`Macro
```
@time expr
@time "description" expr
```
A macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression. Any time spent garbage collecting (gc), compiling new code, or recompiling invalidated code is shown as a percentage.
Optionally provide a description string to print before the time report.
In some cases the system will look inside the `@time` expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run `@time @eval ...`.
See also [`@showtime`](#Base.@showtime), [`@timev`](#Base.@timev), [`@timed`](#Base.@timed), [`@elapsed`](#Base.@elapsed), and [`@allocated`](#Base.@allocated).
For more serious benchmarking, consider the `@btime` macro from the BenchmarkTools.jl package which among other things evaluates the function multiple times in order to reduce noise.
The option to add a description was introduced in Julia 1.8.
Recompilation time being shown separately from compilation time was introduced in Julia 1.8
```
julia> x = rand(10,10);
julia> @time x * x;
0.606588 seconds (2.19 M allocations: 116.555 MiB, 3.75% gc time, 99.94% compilation time)
julia> @time x * x;
0.000009 seconds (1 allocation: 896 bytes)
julia> @time begin
sleep(0.3)
1+1
end
0.301395 seconds (8 allocations: 336 bytes)
2
julia> @time "A one second sleep" sleep(1)
A one second sleep: 1.005750 seconds (5 allocations: 144 bytes)
julia> for loop in 1:3
@time loop sleep(1)
end
1: 1.006760 seconds (5 allocations: 144 bytes)
2: 1.001263 seconds (5 allocations: 144 bytes)
3: 1.003676 seconds (5 allocations: 144 bytes)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L195-L249)###
`Base.@showtime`Macro
```
@showtime expr
```
Like `@time` but also prints the expression being evaluated for reference.
This macro was added in Julia 1.8.
See also [`@time`](#Base.@time).
```
julia> @showtime sleep(1)
sleep(1): 1.002164 seconds (4 allocations: 128 bytes)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L276-L290)###
`Base.@timev`Macro
```
@timev expr
@timev "description" expr
```
This is a verbose version of the `@time` macro. It first prints the same information as `@time`, then any non-zero memory allocation counters, and then returns the value of the expression.
Optionally provide a description string to print before the time report.
The option to add a description was introduced in Julia 1.8.
See also [`@time`](#Base.@time), [`@timed`](#Base.@timed), [`@elapsed`](#Base.@elapsed), and [`@allocated`](#Base.@allocated).
```
julia> x = rand(10,10);
julia> @timev x * x;
0.546770 seconds (2.20 M allocations: 116.632 MiB, 4.23% gc time, 99.94% compilation time)
elapsed time (ns): 546769547
gc time (ns): 23115606
bytes allocated: 122297811
pool allocs: 2197930
non-pool GC allocs:1327
malloc() calls: 36
realloc() calls: 5
GC pauses: 3
julia> @timev x * x;
0.000010 seconds (1 allocation: 896 bytes)
elapsed time (ns): 9848
bytes allocated: 896
pool allocs: 1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L297-L333)###
`Base.@timed`Macro
```
@timed
```
A macro to execute an expression, and return the value of the expression, elapsed time, total bytes allocated, garbage collection time, and an object with various memory allocation counters.
In some cases the system will look inside the `@timed` expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run `@timed @eval ...`.
See also [`@time`](#Base.@time), [`@timev`](#Base.@timev), [`@elapsed`](#Base.@elapsed), and [`@allocated`](#Base.@allocated).
```
julia> stats = @timed rand(10^6);
julia> stats.time
0.006634834
julia> stats.bytes
8000256
julia> stats.gctime
0.0055765
julia> propertynames(stats.gcstats)
(:allocd, :malloc, :realloc, :poolalloc, :bigalloc, :freecall, :total_time, :pause, :full_sweep)
julia> stats.gcstats.total_time
5576500
```
The return type of this macro was changed from `Tuple` to `NamedTuple` in Julia 1.5.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L422-L457)###
`Base.@elapsed`Macro
```
@elapsed
```
A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.
In some cases the system will look inside the `@elapsed` expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run `@elapsed @eval ...`.
See also [`@time`](#Base.@time), [`@timev`](#Base.@timev), [`@timed`](#Base.@timed), and [`@allocated`](#Base.@allocated).
```
julia> @elapsed sleep(0.3)
0.301391426
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L360-L377)###
`Base.@allocated`Macro
```
@allocated
```
A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression.
See also [`@time`](#Base.@time), [`@timev`](#Base.@timev), [`@timed`](#Base.@timed), and [`@elapsed`](#Base.@elapsed).
```
julia> @allocated rand(10^6)
8000080
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L396-L409)###
`Base.EnvDict`Type
```
EnvDict() -> EnvDict
```
A singleton of this type provides a hash table interface to environment variables.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/env.jl#L59-L63)###
`Base.ENV`Constant
```
ENV
```
Reference to the singleton `EnvDict`, providing a dictionary interface to system environment variables.
(On Windows, system environment variables are case-insensitive, and `ENV` correspondingly converts all keys to uppercase for display, iteration, and copying. Portable code should not rely on the ability to distinguish variables by case, and should beware that setting an ostensibly lowercase variable may result in an uppercase `ENV` key.)
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/env.jl#L66-L76)###
`Base.Sys.isunix`Function
```
Sys.isunix([os])
```
Predicate for testing if the OS provides a Unix-like interface. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L322-L327)###
`Base.Sys.isapple`Function
```
Sys.isapple([os])
```
Predicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L429-L434)###
`Base.Sys.islinux`Function
```
Sys.islinux([os])
```
Predicate for testing if the OS is a derivative of Linux. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L344-L349)###
`Base.Sys.isbsd`Function
```
Sys.isbsd([os])
```
Predicate for testing if the OS is a derivative of BSD. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
The Darwin kernel descends from BSD, which means that `Sys.isbsd()` is `true` on macOS systems. To exclude macOS from a predicate, use `Sys.isbsd() && !Sys.isapple()`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L352-L362)###
`Base.Sys.isfreebsd`Function
```
Sys.isfreebsd([os])
```
Predicate for testing if the OS is a derivative of FreeBSD. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
Not to be confused with `Sys.isbsd()`, which is `true` on FreeBSD but also on other BSD-based systems. `Sys.isfreebsd()` refers only to FreeBSD.
This function requires at least Julia 1.1.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L365-L376)###
`Base.Sys.isopenbsd`Function
```
Sys.isopenbsd([os])
```
Predicate for testing if the OS is a derivative of OpenBSD. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
Not to be confused with `Sys.isbsd()`, which is `true` on OpenBSD but also on other BSD-based systems. `Sys.isopenbsd()` refers only to OpenBSD.
This function requires at least Julia 1.1.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L379-L390)###
`Base.Sys.isnetbsd`Function
```
Sys.isnetbsd([os])
```
Predicate for testing if the OS is a derivative of NetBSD. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
Not to be confused with `Sys.isbsd()`, which is `true` on NetBSD but also on other BSD-based systems. `Sys.isnetbsd()` refers only to NetBSD.
This function requires at least Julia 1.1.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L393-L404)###
`Base.Sys.isdragonfly`Function
```
Sys.isdragonfly([os])
```
Predicate for testing if the OS is a derivative of DragonFly BSD. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
Not to be confused with `Sys.isbsd()`, which is `true` on DragonFly but also on other BSD-based systems. `Sys.isdragonfly()` refers only to DragonFly.
This function requires at least Julia 1.1.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L407-L418)###
`Base.Sys.iswindows`Function
```
Sys.iswindows([os])
```
Predicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation in [Handling Operating System Variation](../../manual/handling-operating-system-variation/index#Handling-Operating-System-Variation).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L421-L426)###
`Base.Sys.windows_version`Function
```
Sys.windows_version()
```
Return the version number for the Windows NT Kernel as a `VersionNumber`, i.e. `v"major.minor.build"`, or `v"0.0.0"` if this is not running on Windows.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L461-L466)###
`Base.Sys.free_memory`Function
```
Sys.free_memory()
```
Get the total free memory in RAM in bytes.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L267-L271)###
`Base.Sys.total_memory`Function
```
Sys.total_memory()
```
Get the total memory in RAM (including that which is currently used) in bytes. This amount may be constrained, e.g., by Linux control groups. For the unconstrained amount, see `Sys.physical_memory()`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L274-L280)###
`Base.Sys.free_physical_memory`Function
```
Sys.free_physical_memory()
```
Get the free memory of the system in bytes. The entire amount may not be available to the current process; use `Sys.free_memory()` for the actually available amount.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L251-L256)###
`Base.Sys.total_physical_memory`Function
```
Sys.total_physical_memory()
```
Get the total memory in RAM (including that which is currently used) in bytes. The entire amount may not be available to the current process; see `Sys.total_memory()`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/sysinfo.jl#L259-L264)###
`Base.@static`Macro
```
@static
```
Partially evaluate an expression at parse time.
For example, `@static Sys.iswindows() ? foo : bar` will evaluate `Sys.iswindows()` and insert either `foo` or `bar` into the expression. This is useful in cases where a construct would be invalid on other platforms, such as a `ccall` to a non-existent function. `@static if Sys.isapple() foo end` and `@static foo <&&,||> bar` are also valid syntax.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/osutils.jl#L3-L13)
[Versioning](#Versioning)
--------------------------
###
`Base.VersionNumber`Type
```
VersionNumber
```
Version number type which follows the specifications of [semantic versioning (semver)](https://semver.org/), composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations.
`VersionNumber` objects can be compared with all of the standard comparison operators (`==`, `<`, `<=`, etc.), with the result following semver rules.
See also [`@v_str`](#Base.@v_str) to efficiently construct `VersionNumber` objects from semver-format literal strings, [`VERSION`](../constants/index#Base.VERSION) for the `VersionNumber` of Julia itself, and [Version Number Literals](../../manual/strings/index#man-version-number-literals) in the manual.
**Examples**
```
julia> a = VersionNumber(1, 2, 3)
v"1.2.3"
julia> a >= v"1.2"
true
julia> b = VersionNumber("2.0.1-rc1")
v"2.0.1-rc1"
julia> b >= v"2.0.1"
false
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/version.jl#L8-L38)###
`Base.@v_str`Macro
```
@v_str
```
String macro used to parse a string to a [`VersionNumber`](#Base.VersionNumber).
**Examples**
```
julia> v"1.2.3"
v"1.2.3"
julia> v"2.0.1-rc1"
v"2.0.1-rc1"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/version.jl#L146-L159)
[Errors](#Errors)
------------------
###
`Base.error`Function
```
error(message::AbstractString)
```
Raise an `ErrorException` with the given message.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L30-L34)
```
error(msg...)
```
Raise an `ErrorException` with the given message.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L37-L41)###
`Core.throw`Function
```
throw(e)
```
Throw an object as an exception.
See also: [`rethrow`](#Base.rethrow), [`error`](#Base.error).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L19-L25)###
`Base.rethrow`Function
```
rethrow()
```
Rethrow the current exception from within a `catch` block. The rethrown exception will continue propagation as if it had not been caught.
The alternative form `rethrow(e)` allows you to associate an alternative exception object `e` with the current backtrace. However this misrepresents the program state at the time of the error so you're encouraged to instead throw a new exception using `throw(e)`. In Julia 1.1 and above, using `throw(e)` will preserve the root cause exception on the stack, as described in [`current_exceptions`](#Base.current_exceptions).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L47-L60)###
`Base.backtrace`Function
```
backtrace()
```
Get a backtrace object for the current program point.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L104-L108)###
`Base.catch_backtrace`Function
```
catch_backtrace()
```
Get the backtrace of the current exception, for use within `catch` blocks.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L118-L122)###
`Base.current_exceptions`Function
```
current_exceptions(task::Task=current_task(); [backtrace::Bool=true])
```
Get the stack of exceptions currently being handled. For nested catch blocks there may be more than one current exception in which case the most recently thrown exception is last in the stack. The stack is returned as an `ExceptionStack` which is an AbstractVector of named tuples `(exception,backtrace)`. If `backtrace` is false, the backtrace in each pair will be set to `nothing`.
Explicitly passing `task` will return the current exception stack on an arbitrary task. This is useful for inspecting tasks which have failed due to uncaught exceptions.
This function went by the experimental name `catch_stack()` in Julia 1.1–1.6, and had a plain Vector-of-tuples as a return type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L132-L149)###
`Base.@assert`Macro
```
@assert cond [text]
```
Throw an [`AssertionError`](#Core.AssertionError) if `cond` is `false`. Preferred syntax for writing assertions. Message `text` is optionally displayed upon assertion failure.
An assert might be disabled at various optimization levels. Assert should therefore only be used as a debugging tool and not used for authentication verification (e.g., verifying passwords), nor should side effects needed for the function to work correctly be used inside of asserts.
**Examples**
```
julia> @assert iseven(3) "3 is an odd number!"
ERROR: AssertionError: 3 is an odd number!
julia> @assert isodd(3) "What even are numbers?"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L197-L217)###
`Base.Experimental.register_error_hint`Function
```
Experimental.register_error_hint(handler, exceptiontype)
```
Register a "hinting" function `handler(io, exception)` that can suggest potential ways for users to circumvent errors. `handler` should examine `exception` to see whether the conditions appropriate for a hint are met, and if so generate output to `io`. Packages should call `register_error_hint` from within their `__init__` function.
For specific exception types, `handler` is required to accept additional arguments:
* `MethodError`: provide `handler(io, exc::MethodError, argtypes, kwargs)`, which splits the combined arguments into positional and keyword arguments.
When issuing a hint, the output should typically start with `\n`.
If you define custom exception types, your `showerror` method can support hints by calling [`Experimental.show_error_hints`](#Base.Experimental.show_error_hints).
**Example**
```
julia> module Hinter
only_int(x::Int) = 1
any_number(x::Number) = 2
function __init__()
Base.Experimental.register_error_hint(MethodError) do io, exc, argtypes, kwargs
if exc.f == only_int
# Color is not necessary, this is just to show it's possible.
print(io, "\nDid you mean to call ")
printstyled(io, "`any_number`?", color=:cyan)
end
end
end
end
```
Then if you call `Hinter.only_int` on something that isn't an `Int` (thereby triggering a `MethodError`), it issues the hint:
```
julia> Hinter.only_int(1.0)
ERROR: MethodError: no method matching only_int(::Float64)
Did you mean to call `any_number`?
Closest candidates are:
...
```
Custom error hints are available as of Julia 1.5.
This interface is experimental and subject to change or removal without notice. To insulate yourself against changes, consider putting any registrations inside an `if isdefined(Base.Experimental, :register_error_hint) ... end` block.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/experimental.jl#L212-L269)###
`Base.Experimental.show_error_hints`Function
```
Experimental.show_error_hints(io, ex, args...)
```
Invoke all handlers from [`Experimental.register_error_hint`](#Base.Experimental.register_error_hint) for the particular exception type `typeof(ex)`. `args` must contain any other arguments expected by the handler for that type.
Custom error hints are available as of Julia 1.5.
This interface is experimental and subject to change or removal without notice.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/experimental.jl#L278-L289)###
`Core.ArgumentError`Type
```
ArgumentError(msg)
```
The arguments passed to a function are invalid. `msg` is a descriptive error message.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2440-L2445)###
`Core.AssertionError`Type
```
AssertionError([msg])
```
The asserted condition did not evaluate to `true`. Optional argument `msg` is a descriptive error string.
**Examples**
```
julia> @assert false "this is not true"
ERROR: AssertionError: this is not true
```
`AssertionError` is usually thrown from [`@assert`](#Base.@assert).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2456-L2469)###
`Core.BoundsError`Type
```
BoundsError([a],[i])
```
An indexing operation into an array, `a`, tried to access an out-of-bounds element at index `i`.
**Examples**
```
julia> A = fill(1.0, 7);
julia> A[8]
ERROR: BoundsError: attempt to access 7-element Vector{Float64} at index [8]
julia> B = fill(1.0, (2,3));
julia> B[2, 4]
ERROR: BoundsError: attempt to access 2×3 Matrix{Float64} at index [2, 4]
julia> B[9]
ERROR: BoundsError: attempt to access 2×3 Matrix{Float64} at index [9]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1475-L1498)###
`Base.CompositeException`Type
```
CompositeException
```
Wrap a `Vector` of exceptions thrown by a [`Task`](../parallel/index#Core.Task) (e.g. generated from a remote worker over a channel or an asynchronously executing local I/O write or a remote worker under `pmap`) with information about the series of exceptions. For example, if a group of workers are executing several tasks, and multiple workers fail, the resulting `CompositeException` will contain a "bundle" of information from each worker indicating where and why the exception(s) occurred.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/task.jl#L38-L45)###
`Base.DimensionMismatch`Type
```
DimensionMismatch([msg])
```
The objects called do not have matching dimensionality. Optional argument `msg` is a descriptive error string.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/array.jl#L5-L10)###
`Core.DivideError`Type
```
DivideError()
```
Integer division was attempted with a denominator value of 0.
**Examples**
```
julia> 2/0
Inf
julia> div(2, 0)
ERROR: DivideError: integer division error
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1757-L1772)###
`Core.DomainError`Type
```
DomainError(val)
DomainError(val, msg)
```
The argument `val` to a function or constructor is outside the valid domain.
**Examples**
```
julia> sqrt(-1)
ERROR: DomainError with -1.0:
sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1516-L1530)###
`Base.EOFError`Type
```
EOFError()
```
No more data was available to read from a file or stream.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L5-L9)###
`Core.ErrorException`Type
```
ErrorException(msg)
```
Generic error type. The error message, in the `.msg` field, may provide more specific details.
**Examples**
```
julia> ex = ErrorException("I've done a bad thing");
julia> ex.msg
"I've done a bad thing"
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1382-L1394)###
`Core.InexactError`Type
```
InexactError(name::Symbol, T, val)
```
Cannot exactly convert `val` to type `T` in a method of function `name`.
**Examples**
```
julia> convert(Float64, 1+2im)
ERROR: InexactError: Float64(1 + 2im)
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1501-L1513)###
`Core.InterruptException`Type
```
InterruptException()
```
The process was stopped by a terminal interrupt (CTRL+C).
Note that, in Julia script started without `-i` (interactive) option, `InterruptException` is not thrown by default. Calling [`Base.exit_on_sigint(false)`](../c/index#Base.exit_on_sigint) in the script can recover the behavior of the REPL. Alternatively, a Julia script can be started with
```
julia -e "include(popfirst!(ARGS))" script.jl
```
to let `InterruptException` be thrown by CTRL+C during the execution.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1642-L1658)###
`Base.KeyError`Type
```
KeyError(key)
```
An indexing operation into an `AbstractDict` (`Dict`) or `Set` like object tried to access or delete a non-existent element.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/abstractdict.jl#L5-L10)###
`Core.LoadError`Type
```
LoadError(file::AbstractString, line::Int, error)
```
An error occurred while [`include`](#Base.include)ing, [`require`](#Base.require)ing, or [`using`](#using) a file. The error specifics should be available in the `.error` field.
LoadErrors are no longer emitted by `@macroexpand`, `@macroexpand1`, and `macroexpand` as of Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2472-L2480)###
`Core.MethodError`Type
```
MethodError(f, args)
```
A method with the required type signature does not exist in the given generic function. Alternatively, there is no unique most-specific method.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2448-L2453)###
`Base.MissingException`Type
```
MissingException(msg)
```
Exception thrown when a [`missing`](#Base.missing) value is encountered in a situation where it is not supported. The error message, in the `msg` field may provide more specific details.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/missing.jl#L7-L13)###
`Core.OutOfMemoryError`Type
```
OutOfMemoryError()
```
An operation allocated too much memory for either the system or the garbage collector to handle properly.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1467-L1472)###
`Core.ReadOnlyMemoryError`Type
```
ReadOnlyMemoryError()
```
An operation tried to write to memory that is read-only.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1375-L1379)###
`Core.OverflowError`Type
```
OverflowError(msg)
```
The result of an expression is too large for the specified type and will cause a wraparound.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1628-L1632)###
`Base.ProcessFailedException`Type
```
ProcessFailedException
```
Indicates problematic exit status of a process. When running commands or pipelines, this is thrown to indicate a nonzero exit code was returned (i.e. that the invoked process failed).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/process.jl#L539-L545)###
`Core.StackOverflowError`Type
```
StackOverflowError()
```
The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1551-L1556)###
`Base.SystemError`Type
```
SystemError(prefix::AbstractString, [errno::Int32])
```
A system call failed with an error code (in the `errno` global variable).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/io.jl#L12-L16)###
`Core.TypeError`Type
```
TypeError(func::Symbol, context::AbstractString, expected::Type, got)
```
A type assertion failure, or calling an intrinsic function with an incorrect argument type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1635-L1639)###
`Core.UndefKeywordError`Type
```
UndefKeywordError(var::Symbol)
```
The required keyword argument `var` was not assigned in a function call.
**Examples**
```
julia> function my_func(;my_arg)
return my_arg + 1
end
my_func (generic function with 1 method)
julia> my_func()
ERROR: UndefKeywordError: keyword argument my_arg not assigned
Stacktrace:
[1] my_func() at ./REPL[1]:2
[2] top-level scope at REPL[2]:1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1607-L1625)###
`Core.UndefRefError`Type
```
UndefRefError()
```
The item or field is not defined for the given object.
**Examples**
```
julia> struct MyType
a::Vector{Int}
MyType() = new()
end
julia> A = MyType()
MyType(#undef)
julia> A.a
ERROR: UndefRefError: access to undefined reference
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1406-L1426)###
`Core.UndefVarError`Type
```
UndefVarError(var::Symbol)
```
A symbol in the current scope is not defined.
**Examples**
```
julia> a
ERROR: UndefVarError: a not defined
julia> a = 1;
julia> a
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L1589-L1604)###
`Base.StringIndexError`Type
```
StringIndexError(str, i)
```
An error occurred when trying to access `str` at index `i` that is not valid.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/strings/string.jl#L3-L7)###
`Core.InitError`Type
```
InitError(mod::Symbol, error)
```
An error occurred when running a module's `__init__` function. The actual error thrown is available in the `.error` field.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2483-L2488)###
`Base.retry`Function
```
retry(f; delays=ExponentialBackOff(), check=nothing) -> Function
```
Return an anonymous function that calls function `f`. If an exception arises, `f` is repeatedly called again, each time `check` returns `true`, after waiting the number of seconds specified in `delays`. `check` should input `delays`'s current state and the `Exception`.
Before Julia 1.2 this signature was restricted to `f::Function`.
**Examples**
```
retry(f, delays=fill(5.0, 3))
retry(f, delays=rand(5:10, 2))
retry(f, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))
retry(http_get, check=(s,e)->e.status == "503")(url)
retry(read, check=(s,e)->isa(e, IOError))(io, 128; all=false)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L270-L289)###
`Base.ExponentialBackOff`Type
```
ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)
```
A [`Float64`](../numbers/index#Core.Float64) iterator of length `n` whose elements exponentially increase at a rate in the interval `factor` \* (1 ± `jitter`). The first element is `first_delay` and all elements are clamped to `max_delay`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/error.jl#L251-L257)
[Events](#Events)
------------------
###
`Base.Timer`Method
```
Timer(callback::Function, delay; interval = 0)
```
Create a timer that runs the function `callback` at each timer expiration.
Waiting tasks are woken and the function `callback` is called after an initial delay of `delay` seconds, and then repeating with the given `interval` in seconds. If `interval` is equal to `0`, the callback is only run once. The function `callback` is called with a single argument, the timer itself. Stop a timer by calling `close`. The `cb` may still be run one final time, if the timer has already expired.
**Examples**
Here the first number is printed after a delay of two seconds, then the following numbers are printed quickly.
```
julia> begin
i = 0
cb(timer) = (global i += 1; println(i))
t = Timer(cb, 2, interval=0.2)
wait(t)
sleep(0.5)
close(t)
end
1
2
3
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncevent.jl#L245-L274)###
`Base.Timer`Type
```
Timer(delay; interval = 0)
```
Create a timer that wakes up tasks waiting for it (by calling [`wait`](../parallel/index#Base.wait) on the timer object).
Waiting tasks are woken after an initial delay of at least `delay` seconds, and then repeating after at least `interval` seconds again elapse. If `interval` is equal to `0`, the timer is only triggered once. When the timer is closed (by [`close`](../io-network/index#Base.close)) waiting tasks are woken with an error. Use [`isopen`](../io-network/index#Base.isopen) to check whether a timer is still active.
`interval` is subject to accumulating time skew. If you need precise events at a particular absolute time, create a new timer at each expiration with the difference to the next time computed.
A `Timer` requires yield points to update its state. For instance, `isopen(t::Timer)` cannot be used to timeout a non-yielding while loop.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncevent.jl#L69-L87)###
`Base.AsyncCondition`Type
```
AsyncCondition()
```
Create a async condition that wakes up tasks waiting for it (by calling [`wait`](../parallel/index#Base.wait) on the object) when notified from C by a call to `uv_async_send`. Waiting tasks are woken with an error when the object is closed (by [`close`](../io-network/index#Base.close)). Use [`isopen`](../io-network/index#Base.isopen) to check whether it is still active.
This provides an implicit acquire & release memory ordering between the sending and waiting threads.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncevent.jl#L5-L15)###
`Base.AsyncCondition`Method
```
AsyncCondition(callback::Function)
```
Create a async condition that calls the given `callback` function. The `callback` is passed one argument, the async condition object itself.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/asyncevent.jl#L40-L45)
[Reflection](#Reflection)
--------------------------
###
`Base.nameof`Method
```
nameof(m::Module) -> Symbol
```
Get the name of a `Module` as a [`Symbol`](#Core.Symbol).
**Examples**
```
julia> nameof(Base.Broadcast)
:Broadcast
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L5-L15)###
`Base.parentmodule`Function
```
parentmodule(m::Module) -> Module
```
Get a module's enclosing `Module`. `Main` is its own parent.
See also: [`names`](#Base.names), [`nameof`](#Base.nameof-Tuple%7BDataType%7D), [`fullname`](#Base.fullname), [`@__MODULE__`](#Base.@__MODULE__).
**Examples**
```
julia> parentmodule(Main)
Main
julia> parentmodule(Base.Broadcast)
Base
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L18-L33)
```
parentmodule(t::DataType) -> Module
```
Determine the module containing the definition of a (potentially `UnionAll`-wrapped) `DataType`.
**Examples**
```
julia> module Foo
struct Int end
end
Foo
julia> parentmodule(Int)
Core
julia> parentmodule(Foo.Int)
Foo
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L241-L259)
```
parentmodule(f::Function) -> Module
```
Determine the module containing the (first) definition of a generic function.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1459-L1464)
```
parentmodule(f::Function, types) -> Module
```
Determine the module containing a given definition of a generic function.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1467-L1471)###
`Base.pathof`Method
```
pathof(m::Module)
```
Return the path of the `m.jl` file that was used to `import` module `m`, or `nothing` if `m` was not imported from a package.
Use [`dirname`](../file/index#Base.Filesystem.dirname) to get the directory part and [`basename`](../file/index#Base.Filesystem.basename) to get the file name part of the path.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L362-L370)###
`Base.pkgdir`Method
```
pkgdir(m::Module[, paths::String...])
```
Return the root directory of the package that imported module `m`, or `nothing` if `m` was not imported from a package. Optionally further path component strings can be provided to construct a path within the package root.
```
julia> pkgdir(Foo)
"/path/to/Foo.jl"
julia> pkgdir(Foo, "src", "file.jl")
"/path/to/Foo.jl/src/file.jl"
```
The optional argument `paths` requires at least Julia 1.7.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L383-L401)###
`Base.moduleroot`Function
```
moduleroot(m::Module) -> Module
```
Find the root module of a given module. This is the first module in the chain of parent modules of `m` which is either a registered root module or which is its own parent module.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L36-L42)###
`__module__`Keyword
```
__module__
```
The argument `__module__` is only visible inside the macro, and it provides information (in the form of a `Module` object) about the expansion context of the macro invocation. See the manual section on [Macro invocation](../../manual/metaprogramming/index#Macro-invocation) for more information.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L214-L220)###
`__source__`Keyword
```
__source__
```
The argument `__source__` is only visible inside the macro, and it provides information (in the form of a `LineNumberNode` object) about the parser location of the `@` sign from the macro invocation. See the manual section on [Macro invocation](../../manual/metaprogramming/index#Macro-invocation) for more information.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L223-L229)###
`Base.@__MODULE__`Macro
```
@__MODULE__ -> Module
```
Get the `Module` of the toplevel eval, which is the `Module` code is currently being read from.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L52-L57)###
`Base.@__FILE__`Macro
```
@__FILE__ -> AbstractString
```
Expand to a string with the path to the file containing the macrocall, or an empty string if evaluated by `julia -e <expr>`. Return `nothing` if the macro was missing parser source information. Alternatively see [`PROGRAM_FILE`](../constants/index#Base.PROGRAM_FILE).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L2178-L2185)###
`Base.@__DIR__`Macro
```
@__DIR__ -> AbstractString
```
Expand to a string with the absolute path to the directory of the file containing the macrocall. Return the current working directory if run from a REPL or if evaluated by `julia -e <expr>`.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L2191-L2197)###
`Base.@__LINE__`Macro
```
@__LINE__ -> Int
```
Expand to the line number of the location of the macrocall. Return `0` if the line number could not be determined.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/essentials.jl#L871-L876)###
`Base.fullname`Function
```
fullname(m::Module)
```
Get the fully-qualified name of a module as a tuple of symbols. For example,
**Examples**
```
julia> fullname(Base.Iterators)
(:Base, :Iterators)
julia> fullname(Main)
(:Main,)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L62-L75)###
`Base.names`Function
```
names(x::Module; all::Bool = false, imported::Bool = false)
```
Get an array of the names exported by a `Module`, excluding deprecated names. If `all` is true, then the list also includes non-exported names defined in the module, deprecated names, and compiler-generated names. If `imported` is true, then names explicitly imported from other modules are also included.
As a special case, all names defined in `Main` are considered "exported", since it is not idiomatic to explicitly export names from `Main`.
See also: [`@locals`](#Base.@locals), [`@__MODULE__`](#Base.@__MODULE__).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L88-L101)###
`Base.nameof`Method
```
nameof(f::Function) -> Symbol
```
Get the name of a generic `Function` as a symbol. For anonymous functions, this is a compiler-generated name. For explicitly-declared subtypes of `Function`, it is the name of the function's type.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1437-L1443)###
`Base.functionloc`Method
```
functionloc(f::Function, types)
```
Returns a tuple `(filename,line)` giving the location of a generic `Function` definition.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/methodshow.jl#L173-L177)###
`Base.functionloc`Method
```
functionloc(m::Method)
```
Returns a tuple `(filename,line)` giving the location of a `Method` definition.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/methodshow.jl#L160-L164)###
`Base.@locals`Macro
```
@locals()
```
Construct a dictionary of the names (as symbols) and values of all local variables defined as of the call site.
This macro requires at least Julia 1.1.
**Examples**
```
julia> let x = 1, y = 2
Base.@locals
end
Dict{Symbol, Any} with 2 entries:
:y => 2
:x => 1
julia> function f(x)
local y
show(Base.@locals); println()
for i = 1:1
show(Base.@locals); println()
end
y = 2
show(Base.@locals); println()
nothing
end;
julia> f(42)
Dict{Symbol, Any}(:x => 42)
Dict{Symbol, Any}(:i => 1, :x => 42)
Dict{Symbol, Any}(:y => 2, :x => 42)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L294-L328)
[Internals](#Internals)
------------------------
###
`Base.GC.gc`Function
```
GC.gc([full=true])
```
Perform garbage collection. The argument `full` determines the kind of collection: A full collection (default) sweeps all objects, which makes the next GC scan much slower, while an incremental collection may only sweep so-called young objects.
Excessive use will likely lead to poor performance.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L82-L92)###
`Base.GC.enable`Function
```
GC.enable(on::Bool)
```
Control whether garbage collection is enabled using a boolean argument (`true` for enabled, `false` for disabled). Return previous GC state.
Disabling garbage collection should be used only with caution, as it can cause memory use to grow without bound.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L96-L105)###
`Base.GC.@preserve`Macro
```
GC.@preserve x1 x2 ... xn expr
```
Mark the objects `x1, x2, ...` as being *in use* during the evaluation of the expression `expr`. This is only required in unsafe code where `expr` *implicitly uses* memory or other resources owned by one of the `x`s.
*Implicit use* of `x` covers any indirect use of resources logically owned by `x` which the compiler cannot see. Some examples:
* Accessing memory of an object directly via a `Ptr`
* Passing a pointer to `x` to `ccall`
* Using resources of `x` which would be cleaned up in the finalizer.
`@preserve` should generally not have any performance impact in typical use cases where it briefly extends object lifetime. In implementation, `@preserve` has effects such as protecting dynamically allocated objects from garbage collection.
**Examples**
When loading from a pointer with `unsafe_load`, the underlying object is implicitly used, for example `x` is implicitly used by `unsafe_load(p)` in the following:
```
julia> let
x = Ref{Int}(101)
p = Base.unsafe_convert(Ptr{Int}, x)
GC.@preserve x unsafe_load(p)
end
101
```
When passing pointers to `ccall`, the pointed-to object is implicitly used and should be preserved. (Note however that you should normally just pass `x` directly to `ccall` which counts as an explicit use.)
```
julia> let
x = "Hello"
p = pointer(x)
Int(GC.@preserve x @ccall strlen(p::Cstring)::Csize_t)
# Preferred alternative
Int(@ccall strlen(x::Cstring)::Csize_t)
end
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L129-L176)###
`Base.GC.safepoint`Function
```
GC.safepoint()
```
Inserts a point in the program where garbage collection may run. This can be useful in rare cases in multi-threaded programs where some threads are allocating memory (and hence may need to run GC) but other threads are doing only simple operations (no allocation, task switches, or I/O). Calling this function periodically in non-allocating threads allows garbage collection to run.
This function is available as of Julia 1.4.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L185-L197)###
`Base.GC.enable_logging`Function
```
GC.enable_logging(on::Bool)
```
When turned on, print statistics about each GC to stderr.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/gcutils.jl#L200-L204)###
`Base.Meta.lower`Function
```
lower(m, x)
```
Takes the expression `x` and returns an equivalent expression in lowered form for executing in module `m`. See also [`code_lowered`](#Base.code_lowered).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L157-L163)###
`Base.Meta.@lower`Macro
```
@lower [m] x
```
Return lowered form of the expression `x` in module `m`. By default `m` is the module in which the macro is called. See also [`lower`](#Base.Meta.lower).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L166-L172)###
`Base.Meta.parse`Method
```
parse(str, start; greedy=true, raise=true, depwarn=true)
```
Parse the expression string and return an expression (which could later be passed to eval for execution). `start` is the code unit index into `str` of the first character to start parsing at (as with all string indexing, these are not character indices). If `greedy` is `true` (default), `parse` will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return `Expr(:incomplete, "(error message)")`. If `raise` is `true` (default), syntax errors other than incomplete expressions will raise an error. If `raise` is `false`, `parse` will return an expression that will raise an error upon evaluation. If `depwarn` is `false`, deprecation warnings will be suppressed.
```
julia> Meta.parse("(α, β) = 3, 5", 1) # start of string
(:((α, β) = (3, 5)), 16)
julia> Meta.parse("(α, β) = 3, 5", 1, greedy=false)
(:((α, β)), 9)
julia> Meta.parse("(α, β) = 3, 5", 16) # end of string
(nothing, 16)
julia> Meta.parse("(α, β) = 3, 5", 11) # index of 3
(:((3, 5)), 16)
julia> Meta.parse("(α, β) = 3, 5", 11, greedy=false)
(3, 13)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L202-L232)###
`Base.Meta.parse`Method
```
parse(str; raise=true, depwarn=true)
```
Parse the expression string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If `raise` is `true` (default), syntax errors will raise an error; otherwise, `parse` will return an expression that will raise an error upon evaluation. If `depwarn` is `false`, deprecation warnings will be suppressed.
```
julia> Meta.parse("x = 3")
:(x = 3)
julia> Meta.parse("x = ")
:($(Expr(:incomplete, "incomplete: premature end of input")))
julia> Meta.parse("1.0.2")
ERROR: Base.Meta.ParseError("invalid numeric constant \"1.0.\"")
Stacktrace:
[...]
julia> Meta.parse("1.0.2"; raise = false)
:($(Expr(:error, "invalid numeric constant \"1.0.\"")))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L242-L266)###
`Base.Meta.ParseError`Type
```
ParseError(msg)
```
The expression passed to the [`parse`](#Base.Meta.parse-Tuple%7BAbstractString,%20Int64%7D) function could not be interpreted as a valid Julia expression.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L183-L188)###
`Core.QuoteNode`Type
```
QuoteNode
```
A quoted piece of code, that does not support interpolation. See the [manual section about QuoteNodes](../../manual/metaprogramming/index#man-quote-node) for details.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/docs/basedocs.jl#L2851-L2855)###
`Base.macroexpand`Function
```
macroexpand(m::Module, x; recursive=true)
```
Take the expression `x` and return an equivalent expression with all macros removed (expanded) for executing in module `m`. The `recursive` keyword controls whether deeper levels of nested macros are also expanded. This is demonstrated in the example below:
```
julia> module M
macro m1()
42
end
macro m2()
:(@m1())
end
end
M
julia> macroexpand(M, :(@m2()), recursive=true)
42
julia> macroexpand(M, :(@m2()), recursive=false)
:(#= REPL[16]:6 =# M.@m1)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L88-L112)###
`Base.@macroexpand`Macro
```
@macroexpand
```
Return equivalent expression with all macros removed (expanded).
There are differences between `@macroexpand` and [`macroexpand`](#Base.macroexpand).
* While [`macroexpand`](#Base.macroexpand) takes a keyword argument `recursive`, `@macroexpand` is always recursive. For a non recursive macro version, see [`@macroexpand1`](#Base.@macroexpand1).
* While [`macroexpand`](#Base.macroexpand) has an explicit `module` argument, `@macroexpand` always expands with respect to the module in which it is called.
This is best seen in the following example:
```
julia> module M
macro m()
1
end
function f()
(@macroexpand(@m),
macroexpand(M, :(@m)),
macroexpand(Main, :(@m))
)
end
end
M
julia> macro m()
2
end
@m (macro with 1 method)
julia> M.f()
(1, 1, 2)
```
With `@macroexpand` the expression expands where `@macroexpand` appears in the code (module `M` in the example). With `macroexpand` the expression expands in the module given as the first argument.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L121-L159)###
`Base.@macroexpand1`Macro
```
@macroexpand1
```
Non recursive version of [`@macroexpand`](#Base.@macroexpand).
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/expr.jl#L165-L169)###
`Base.code_lowered`Function
```
code_lowered(f, types; generated=true, debuginfo=:default)
```
Return an array of the lowered forms (IR) for the methods matching the given generic function and type signature.
If `generated` is `false`, the returned `CodeInfo` instances will correspond to fallback implementations. An error is thrown if no fallback implementation exists. If `generated` is `true`, these `CodeInfo` instances will correspond to the method bodies yielded by expanding the generators.
The keyword `debuginfo` controls the amount of code metadata present in the output.
Note that an error will be thrown if `types` are not leaf types when `generated` is `true` and any of the corresponding methods are an `@generated` method.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L880-L895)###
`Base.code_typed`Function
```
code_typed(f, types; kw...)
```
Returns an array of type-inferred lowered form (IR) for the methods matching the given generic function and type signature.
**Keyword Arguments**
* `optimize=true`: controls whether additional optimizations, such as inlining, are also applied.
* `debuginfo=:default`: controls the amount of code metadata present in the output,
possible options are `:source` or `:none`.
**Internal Keyword Arguments**
This section should be considered internal, and is only for who understands Julia compiler internals.
* `world=Base.get_world_counter()`: optional, controls the world age to use when looking up methods,
use current world age if not specified.
* `interp=Core.Compiler.NativeInterpreter(world)`: optional, controls the interpreter to use,
use the native interpreter Julia uses if not specified.
**Example**
One can put the argument types in a tuple to get the corresponding `code_typed`.
```
julia> code_typed(+, (Float64, Float64))
1-element Vector{Any}:
CodeInfo(
1 ─ %1 = Base.add_float(x, y)::Float64
└── return %1
) => Float64
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/reflection.jl#L1189-L1223)###
`Base.precompile`Function
```
precompile(f, args::Tuple{Vararg{Any}})
```
Compile the given function `f` for the argument tuple (of types) `args`, but do not execute it.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/loading.jl#L2204-L2208)###
`Base.jit_total_bytes`Function
```
Base.jit_total_bytes()
```
Return the total amount (in bytes) allocated by the just-in-time compiler for e.g. native code and data.
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/timing.jl#L90-L95)
[Meta](#Meta)
--------------
###
`Base.Meta.quot`Function
```
Meta.quot(ex)::Expr
```
Quote expression `ex` to produce an expression with head `quote`. This can for instance be used to represent objects of type `Expr` in the AST. See also the manual section about [QuoteNode](../../manual/metaprogramming/index#man-quote-node).
**Examples**
```
julia> eval(Meta.quot(:x))
:x
julia> dump(Meta.quot(:x))
Expr
head: Symbol quote
args: Array{Any}((1,))
1: Symbol x
julia> eval(Meta.quot(:(1+2)))
:(1 + 2)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L24-L45)###
`Base.isexpr`Function
```
Meta.isexpr(ex, head[, n])::Bool
```
Return true if `ex` is an `Expr` with the given type `head` and optionally that the argument list is of length `n`. `head` may be a `Symbol` or collection of `Symbol`s. For example, to check that a macro was passed a function call expression, you might use `isexpr(ex, :call)`.
**Examples**
```
julia> ex = :(f(x))
:(f(x))
julia> Meta.isexpr(ex, :block)
false
julia> Meta.isexpr(ex, :call)
true
julia> Meta.isexpr(ex, [:block, :call]) # multiple possible heads
true
julia> Meta.isexpr(ex, :call, 1)
false
julia> Meta.isexpr(ex, :call, 2)
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L48-L76)###
`Base.isidentifier`Function
```
isidentifier(s) -> Bool
```
Return whether the symbol or string `s` contains characters that are parsed as a valid ordinary identifier (not a binary/unary operator) in Julia code; see also [`Base.isoperator`](#Base.isoperator).
Internally Julia allows any sequence of characters in a `Symbol` (except `\0`s), and macros automatically use variable names containing `#` in order to avoid naming collision with the surrounding code. In order for the parser to recognize a variable, it uses a limited set of characters (greatly extended by Unicode). `isidentifier()` makes it possible to query the parser directly whether a symbol contains valid characters.
**Examples**
```
julia> Meta.isidentifier(:x), Meta.isidentifier("1x")
(true, false)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L1335-L1354)###
`Base.isoperator`Function
```
isoperator(s::Symbol)
```
Return `true` if the symbol can be used as an operator, `false` otherwise.
**Examples**
```
julia> Meta.isoperator(:+), Meta.isoperator(:f)
(true, false)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L1369-L1379)###
`Base.isunaryoperator`Function
```
isunaryoperator(s::Symbol)
```
Return `true` if the symbol can be used as a unary (prefix) operator, `false` otherwise.
**Examples**
```
julia> Meta.isunaryoperator(:-), Meta.isunaryoperator(:√), Meta.isunaryoperator(:f)
(true, true, false)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L1382-L1392)###
`Base.isbinaryoperator`Function
```
isbinaryoperator(s::Symbol)
```
Return `true` if the symbol can be used as a binary (infix) operator, `false` otherwise.
**Examples**
```
julia> Meta.isbinaryoperator(:-), Meta.isbinaryoperator(:√), Meta.isbinaryoperator(:f)
(true, false, false)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/show.jl#L1397-L1407)###
`Base.Meta.show_sexpr`Function
```
Meta.show_sexpr([io::IO,], ex)
```
Show expression `ex` as a lisp style S-expression.
**Examples**
```
julia> Meta.show_sexpr(:(f(x, g(y,z))))
(:call, :f, :x, (:call, :g, :y, :z))
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/meta.jl#L109-L119)
| programming_docs |
julia Iteration utilities Iteration utilities
===================
###
`Base.Iterators.Stateful`Type
```
Stateful(itr)
```
There are several different ways to think about this iterator wrapper:
1. It provides a mutable wrapper around an iterator and its iteration state.
2. It turns an iterator-like abstraction into a `Channel`-like abstraction.
3. It's an iterator that mutates to become its own rest iterator whenever an item is produced.
`Stateful` provides the regular iterator interface. Like other mutable iterators (e.g. [`Channel`](../parallel/index#Base.Channel)), if iteration is stopped early (e.g. by a [`break`](../base/index#break) in a [`for`](../base/index#for) loop), iteration can be resumed from the same spot by continuing to iterate over the same iterator object (in contrast, an immutable iterator would restart from the beginning).
**Examples**
```
julia> a = Iterators.Stateful("abcdef");
julia> isempty(a)
false
julia> popfirst!(a)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> collect(Iterators.take(a, 3))
3-element Vector{Char}:
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
julia> collect(a)
2-element Vector{Char}:
'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
'f': ASCII/Unicode U+0066 (category Ll: Letter, lowercase)
julia> Iterators.reset!(a); popfirst!(a)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> Iterators.reset!(a, "hello"); popfirst!(a)
'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
```
```
julia> a = Iterators.Stateful([1,1,1,2,3,4]);
julia> for x in a; x == 1 || break; end
julia> peek(a)
3
julia> sum(a) # Sum the remaining elements
7
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L1248-L1305)###
`Base.Iterators.zip`Function
```
zip(iters...)
```
Run multiple iterators at the same time, until any of them is exhausted. The value type of the `zip` iterator is a tuple of values of its subiterators.
`zip` orders the calls to its subiterators in such a way that stateful iterators will not advance when another iterator finishes in the current iteration.
See also: [`enumerate`](#Base.Iterators.enumerate), [`splat`](../base/index#Base.splat).
**Examples**
```
julia> a = 1:5
1:5
julia> b = ["e","d","b","c","a"]
5-element Vector{String}:
"e"
"d"
"b"
"c"
"a"
julia> c = zip(a,b)
zip(1:5, ["e", "d", "b", "c", "a"])
julia> length(c)
5
julia> first(c)
(1, "e")
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L293-L327)###
`Base.Iterators.enumerate`Function
```
enumerate(iter)
```
An iterator that yields `(i, x)` where `i` is a counter starting at 1, and `x` is the `i`th value from the given iterator. It's useful when you need not only the values `x` over which you are iterating, but also the number of iterations so far. Note that `i` may not be valid for indexing `iter`; it's also possible that `x != iter[i]`, if `iter` has indices that do not start at 1. See the `pairs(IndexLinear(), iter)` method if you want to ensure that `i` is an index.
**Examples**
```
julia> a = ["a", "b", "c"];
julia> for (index, value) in enumerate(a)
println("$index $value")
end
1 a
2 b
3 c
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L138-L160)###
`Base.Iterators.rest`Function
```
rest(iter, state)
```
An iterator that yields the same elements as `iter`, but starting at the given `state`.
See also: [`Iterators.drop`](#Base.Iterators.drop), [`Iterators.peel`](#Base.Iterators.peel), [`Base.rest`](../collections/index#Base.rest).
**Examples**
```
julia> collect(Iterators.rest([1,2,3,4], 2))
3-element Vector{Int64}:
2
3
4
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L560-L575)###
`Base.Iterators.countfrom`Function
```
countfrom(start=1, step=1)
```
An iterator that counts forever, starting at `start` and incrementing by `step`.
**Examples**
```
julia> for v in Iterators.countfrom(5, 2)
v > 10 && break
println(v)
end
5
7
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L628-L643)###
`Base.Iterators.take`Function
```
take(iter, n)
```
An iterator that generates at most the first `n` elements of `iter`.
See also: [`drop`](#Base.Iterators.drop), [`peel`](#Base.Iterators.peel), [`first`](../collections/index#Base.first), [`take!`](#).
**Examples**
```
julia> a = 1:2:11
1:2:11
julia> collect(a)
6-element Vector{Int64}:
1
3
5
7
9
11
julia> collect(Iterators.take(a,3))
3-element Vector{Int64}:
1
3
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L667-L694)###
`Base.Iterators.takewhile`Function
```
takewhile(pred, iter)
```
An iterator that generates element from `iter` as long as predicate `pred` is true, afterwards, drops every element.
This function requires at least Julia 1.4.
**Examples**
```
julia> s = collect(1:5)
5-element Vector{Int64}:
1
2
3
4
5
julia> collect(Iterators.takewhile(<(3),s))
2-element Vector{Int64}:
1
2
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L782-L807)###
`Base.Iterators.drop`Function
```
drop(iter, n)
```
An iterator that generates all but the first `n` elements of `iter`.
**Examples**
```
julia> a = 1:2:11
1:2:11
julia> collect(a)
6-element Vector{Int64}:
1
3
5
7
9
11
julia> collect(Iterators.drop(a,4))
2-element Vector{Int64}:
9
11
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L726-L750)###
`Base.Iterators.dropwhile`Function
```
dropwhile(pred, iter)
```
An iterator that drops element from `iter` as long as predicate `pred` is true, afterwards, returns every element.
This function requires at least Julia 1.4.
**Examples**
```
julia> s = collect(1:5)
5-element Vector{Int64}:
1
2
3
4
5
julia> collect(Iterators.dropwhile(<(3),s))
3-element Vector{Int64}:
3
4
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L829-L855)###
`Base.Iterators.cycle`Function
```
cycle(iter)
```
An iterator that cycles through `iter` forever. If `iter` is empty, so is `cycle(iter)`.
See also: [`Iterators.repeated`](#Base.Iterators.repeated), [`repeat`](../arrays/index#Base.repeat).
**Examples**
```
julia> for (i, v) in enumerate(Iterators.cycle("hello"))
print(v)
i > 10 && break
end
hellohelloh
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L879-L895)###
`Base.Iterators.repeated`Function
```
repeated(x[, n::Int])
```
An iterator that generates the value `x` forever. If `n` is specified, generates `x` that many times (equivalent to `take(repeated(x), n)`).
See also: [`Iterators.cycle`](#Base.Iterators.cycle), [`repeat`](../arrays/index#Base.repeat).
**Examples**
```
julia> a = Iterators.repeated([1 2], 4);
julia> collect(a)
4-element Vector{Matrix{Int64}}:
[1 2]
[1 2]
[1 2]
[1 2]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L921-L940)###
`Base.Iterators.product`Function
```
product(iters...)
```
Return an iterator over the product of several iterators. Each generated element is a tuple whose `i`th element comes from the `i`th argument iterator. The first iterator changes the fastest.
See also: [`zip`](#Base.Iterators.zip), [`Iterators.flatten`](#Base.Iterators.flatten).
**Examples**
```
julia> collect(Iterators.product(1:2, 3:5))
2×3 Matrix{Tuple{Int64, Int64}}:
(1, 3) (1, 4) (1, 5)
(2, 3) (2, 4) (2, 5)
julia> ans == [(x,y) for x in 1:2, y in 3:5] # collects a generator involving Iterators.product
true
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L958-L977)###
`Base.Iterators.flatten`Function
```
flatten(iter)
```
Given an iterator that yields iterators, return an iterator that yields the elements of those iterators. Put differently, the elements of the argument iterator are concatenated.
**Examples**
```
julia> collect(Iterators.flatten((1:2, 8:9)))
4-element Vector{Int64}:
1
2
8
9
julia> [(x,y) for x in 0:1 for y in 'a':'c'] # collects generators involving Iterators.flatten
6-element Vector{Tuple{Int64, Char}}:
(0, 'a')
(0, 'b')
(0, 'c')
(1, 'a')
(1, 'b')
(1, 'c')
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L1092-L1117)###
`Base.Iterators.partition`Function
```
partition(collection, n)
```
Iterate over a collection `n` elements at a time.
**Examples**
```
julia> collect(Iterators.partition([1,2,3,4,5], 2))
3-element Vector{SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}}:
[1, 2]
[3, 4]
[5]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L1166-L1179)###
`Base.Iterators.map`Function
```
Iterators.map(f, iterators...)
```
Create a lazy mapping. This is another syntax for writing `(f(args...) for args in zip(iterators...))`.
This function requires at least Julia 1.6.
**Examples**
```
julia> collect(Iterators.map(x -> x^2, 1:3))
3-element Vector{Int64}:
1
4
9
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L27-L44)###
`Base.Iterators.filter`Function
```
Iterators.filter(flt, itr)
```
Given a predicate function `flt` and an iterable object `itr`, return an iterable object which upon iteration yields the elements `x` of `itr` that satisfy `flt(x)`. The order of the original iterator is preserved.
This function is *lazy*; that is, it is guaranteed to return in $Θ(1)$ time and use $Θ(1)$ additional space, and `flt` will not be called by an invocation of `filter`. Calls to `flt` will be made when iterating over the returned iterable object. These calls are not cached and repeated calls will be made when reiterating.
See [`Base.filter`](../collections/index#Base.filter) for an eager implementation of filtering for arrays.
**Examples**
```
julia> f = Iterators.filter(isodd, [1, 2, 3, 4, 5])
Base.Iterators.Filter{typeof(isodd), Vector{Int64}}(isodd, [1, 2, 3, 4, 5])
julia> foreach(println, f)
1
3
5
julia> [x for x in [1, 2, 3, 4, 5] if isodd(x)] # collects a generator over Iterators.filter
3-element Vector{Int64}:
1
3
5
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L435-L466)###
`Base.Iterators.accumulate`Function
```
Iterators.accumulate(f, itr; [init])
```
Given a 2-argument function `f` and an iterator `itr`, return a new iterator that successively applies `f` to the previous value and the next element of `itr`.
This is effectively a lazy version of [`Base.accumulate`](../arrays/index#Base.accumulate).
Keyword argument `init` is added in Julia 1.5.
**Examples**
```
julia> a = Iterators.accumulate(+, [1,2,3,4]);
julia> foreach(println, a)
1
3
6
10
julia> b = Iterators.accumulate(/, (2, 5, 2, 5); init = 100);
julia> collect(b)
4-element Vector{Float64}:
50.0
10.0
5.0
1.0
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L495-L526)###
`Base.Iterators.reverse`Function
```
Iterators.reverse(itr)
```
Given an iterator `itr`, then `reverse(itr)` is an iterator over the same collection but in the reverse order.
This iterator is "lazy" in that it does not make a copy of the collection in order to reverse it; see [`Base.reverse`](#) for an eager implementation.
Not all iterator types `T` support reverse-order iteration. If `T` doesn't, then iterating over `Iterators.reverse(itr::T)` will throw a [`MethodError`](../base/index#Core.MethodError) because of the missing [`iterate`](../collections/index#Base.iterate) methods for `Iterators.Reverse{T}`. (To implement these methods, the original iterator `itr::T` can be obtained from `r = Iterators.reverse(itr)` by `r.itr`.)
**Examples**
```
julia> foreach(println, Iterators.reverse(1:5))
5
4
3
2
1
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L70-L94)###
`Base.Iterators.only`Function
```
only(x)
```
Return the one and only element of collection `x`, or throw an [`ArgumentError`](../base/index#Core.ArgumentError) if the collection has zero or multiple elements.
See also [`first`](../collections/index#Base.first), [`last`](../collections/index#Base.last).
This method requires at least Julia 1.4.
**Examples**
```
julia> only(["a"])
"a"
julia> only("a")
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> only(())
ERROR: ArgumentError: Tuple contains 0 elements, must contain exactly 1 element
Stacktrace:
[...]
julia> only(('a', 'b'))
ERROR: ArgumentError: Tuple contains 2 elements, must contain exactly 1 element
Stacktrace:
[...]
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L1375-L1404)###
`Base.Iterators.peel`Function
```
peel(iter)
```
Returns the first element and an iterator over the remaining elements.
If the iterator is empty return `nothing` (like `iterate`).
Prior versions throw a BoundsError if the iterator is empty.
See also: [`Iterators.drop`](#Base.Iterators.drop), [`Iterators.take`](#Base.Iterators.take).
**Examples**
```
julia> (a, rest) = Iterators.peel("abc");
julia> a
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> collect(rest)
2-element Vector{Char}:
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
```
[source](https://github.com/JuliaLang/julia/blob/17cfb8e65ead377bf1b4598d8a9869144142c84e/base/iterators.jl#L580-L604)
codeception Introduction Introduction
============
The idea behind testing is not new. You can’t sleep well if you are not confident that your latest commit didn’t take down the entire application. Having your application covered with tests gives you more trust in the stability of your application. That’s all.
In most cases tests don’t guarantee that the application works 100% as it is supposed to. You can’t predict all possible scenarios and exceptional situations for complex apps, but with tests you can cover the most important parts of your app and at least be sure they work as predicted.
There are plenty of ways to test your application. The most popular paradigm is [Unit Testing](https://en.wikipedia.org/wiki/Unit_testing). For web applications, testing just the controller and/or the model doesn’t prove that your application is working. To test the behavior of your application as a whole, you should write functional or acceptance tests.
Codeception supports all three testing types. Out of the box you have tools for writing unit, functional, and acceptance tests in a unified framework.
| | Unit Tests | Functional Tests | Acceptance Tests |
| --- | --- | --- | --- |
| Scope of the test | Single PHP class | PHP Framework (Routing, Controllers, etc.) | Page in browser (Chrome, Firefox, or [PhpBrowser](03-acceptancetests#PhpBrowser)) |
| Testing computer needs access to project’s PHP files | Yes | Yes | No |
| Webserver required | No | No | Yes |
| JavaScript | No | No | Yes |
| Additional software required | None | None | Selenium for browser testing |
| Speed | Fast | Fast | Slow |
| Configuration file | `unit.suite.yml` | `functional.suite.yml` | `acceptance.suite.yml` |
One of the main advantages of Codeception is that you don’t have to decide on just *one* type of testing. You should have all three! And chances are, that you will (sooner or later) need all three. That’s why Codeception consists of three so-called “suites”: A “unit suite” for all unit tests, a “functional suite” for all functional tests, and an “acceptance suite” for all acceptance tests.
Let’s review those three testing types in reverse order.
### Acceptance Tests
How does your client, manager, tester, or any other non-technical person know your website is working? By opening the browser, accessing the site, clicking on links, filling in the forms, and actually seeing the content on a web page. They have no idea of the programming language, framework, database, web-server, or why the application did (or did not) behave as expected.
This is what acceptance tests are doing. They cover scenarios from a user’s perspective. With acceptance tests, you can be confident that users, following all the defined scenarios, won’t get errors.
> **Any website** can be covered with acceptance tests, even if you use a very exotic CMS or framework.
>
>
#### Sample acceptance test
```
<?php
$I->amOnPage('/');
$I->click('Sign Up');
$I->submitForm('#signup', [
'username' => 'MilesDavis',
'email' => '[email protected]'
]);
$I->see('Thank you for Signing Up!');
```
### Functional Tests
What if you could check our application without running it on a server? That way you could see detailed exceptions on errors, have our tests run faster, and check the database against predictable and expected results. That’s what functional tests are for.
For functional tests, you emulate a web request (`$_GET` and `$_POST` variables) which returns the HTML response. Inside a test, you can make assertions about the response, and you can check if the data was successfully stored in the database.
For functional tests, your application needs to be structured in order to run in a test environment. Codeception provides connectors to all popular PHP frameworks.
#### Sample functional test
```
<?php
$I->amOnPage('/');
$I->click('Sign Up');
$I->submitForm('#signup', ['username' => 'MilesDavis', 'email' => '[email protected]']);
$I->see('Thank you for Signing Up!');
$I->seeEmailSent('[email protected]', 'Thank you for registration');
$I->seeInDatabase('users', ['email' => '[email protected]']);
```
> This looks very similar to acceptance tests. The behavior is the same, however, the test is executed inside PHP without launching a browser.
>
>
### Unit Tests
Testing pieces of code before coupling them together is highly important as well. This way, you can be sure that some deeply hidden feature still works, even if it was not covered by functional or acceptance tests. This also shows care in producing stable and testable code.
Codeception is created on top of [PHPUnit](https://www.phpunit.de/). If you have experience writing unit tests with PHPUnit you can continue doing so. Codeception has no problem executing standard PHPUnit tests, but, additionally, Codeception provides some well-built tools to make your unit tests simpler and cleaner.
Requirements and code can change rapidly, and unit tests should be updated every time to fit the requirements. The better you understand the testing scenario, the faster you can update it for new behavior.
#### Sample integration test
```
<?php
public function testSavingUser()
{
$user = new User();
$user->setName('Miles');
$user->setSurname('Davis');
$user->save();
$this->assertEquals('Miles Davis', $user->getFullName());
$this->tester->seeInDatabase('users', [
'name' => 'Miles',
'surname' => 'Davis'
]);
}
```
Conclusion
----------
The Codeception framework was developed to actually make testing fun. It allows writing unit, functional, integration, and acceptance tests in a single, coherent style.
All Codeception tests are written in a descriptive manner. Just by looking at the test body, you can clearly understand what is being tested and how it is performed.
* **Next Chapter: [GettingStarted >](02-gettingstarted)**
| programming_docs |
codeception Codeception Documentation Codeception Documentation
=========================
- [Introduction](01-introduction)
- [Getting Started](02-gettingstarted)
- [Acceptance Tests](03-acceptancetests)
- [Functional Tests](04-functionaltests)
- [Unit Tests](05-unittests)
- [Modules And Helpers](06-modulesandhelpers)
- [Reusing Test Code](06-reusingtestcode)
- [Advanced Usage](07-advancedusage)
- [BDD](07-bdd)
- [Customization](08-customization)
- [Data](09-data)
- [API Testing](10-apitesting)
- [Codecoverage](11-codecoverage)
- [Continuous Integration](12-continuousintegration)
- [Parallel Execution](12-parallelexecution)
codeception Continuous Integration Continuous Integration
======================
Once you get testing suite up and running you are interested in running your tests regularly. If you ensure that tests are running on every code change or at least once a day you can be sure that no regression is introduced. This allows to keep you system stable. But developers are not so passionate about running all tests manually, they also can forget to execute tests before pushing code to production… The solution is simple, test execution should be automated. Instead of running them locally it is better to have dedicated server responsible for running tests for a team. This way we can ensure that everyone’s tests executed, which commit made a regression in codebase, and that we can deploy only once tests pass.
There are many Continuous Integration Servers out there. We will try to list basic steps to setup Codeception tests with them. If your CI system is not mentioned, you can get the idea by analogy. Please also help us to extend this guide by adding instructions for different CIs.
Jenkins
-------
[Jenkins](https://jenkins-ci.org/) is one of the most popular open-source solution on market. It is easy to setup and is easy to customize by applying various plugins.
### Preparing Jenkins
It is recommended to have the next plugins installed:
* **Git Plugin** - for building tests for Git repo
* **Green Balls** - to display success results in green.
* **xUnit Plugin**, **jUnit Plugin** - to process and display Codeception XML reports
* **HTML Publisher Plugin** - to process Codeception HTML reports
* **AnsiColor** - to show colorized console output.
### Basic Setup
At first we need to create build project. Depending on your needs you can set up periodical build or trigger build once the change is pushed to GitHub (you will need GitHub plugin for that).
We need to define build steps. The most simple setup may look like this:
```
vendor/bin/codecept run
```
Then we can start the very first job and check the execution progress. If tests fail we will see that in console:
### XML Reports
But we don’t want to analyze console output for each failing build. Especially If Jenkins can collect and display the results inside its web UI. Codeception can export its results using JUnit XML format. To generate XML report on each build we will need to append `--xml` option to Codeception execution command. Codeception will print `result.xml` file containing information about test status with steps and stack traces for failing tests.
Now let’s update our build step to generate xml:
```
vendor/bin/codecept run --xml
```
and ask Jenkins to collect resulted XML. This can be done as part of Post-build actions. Let’s add *Publish xUnit test result report* action and configure it to use with PHPUnit reports.
Now we should specify path to PHPUnit style XML reports. In case of standard Codeception setup we should specify `tests/_output/*.xml` as a pattern for matching resulted XMLs. Now we save the project and rebuild it.
Now for all builds we will see results trend graph that shows us percentage of passing and failing tests. We also will see a **Latest Test Result** link which will lead to to the page where all executed tests and their stats listed in a table.
### HTML Reports
To get more details on steps executed you can generate HTML report and use Jenkins to display them.
```
vendor/bin/codecept run --html
```
Now we need HTML Publisher plugin configured to display generated HTML files. It should be added as post-build action similar way we did it for XML reports.
Jenkins should locate `report.html` at `tests/_output/`. Now Jenkins will display HTML reports for each build.
TeamCity
--------
TeamCity is a hosted solution from JetBrains. The setup of it can be a bit tricky as TeamCity uses its own reporter format for parsing test results. PHPUnit since version 5.x has integrated support for this format, so does Codeception. What we need to do is to configure Codeception to use custom reporter. By default there is `--report` option which provides an alternative output. You can change the reporter class in `codeception.yml` configuration:
```
reporters:
report: PHPUnit_Util_Log_TeamCity
```
As an alternative you can use 3rd-party [TeamCity extension](https://github.com/neronmoon/TeamcityCodeception) for better reporting.
After you create build project you should define build step with Codeception which is
```
vendor/bin/codecept run --report
```
Once you execute your first build you should see detailed report inside TeamCity interface:
TravisCI
--------
Travis CI is popular service CI with good GitHub integration. Codeception is self-tested with Travis CI. There nothing special about configuration. Just add to the bottom line of travis configuration:
```
php vendor/bin/codecept run
```
More details on configuration can be learned from Codeception’s [`.travis.yml`](https://github.com/Codeception/Codeception/blob/3.0/.travis.yml).
Travis doesn’t provide visualization for XML or HTML reports so you can’t view reports in format any different than console output. However, Codeception produces nice console output with detailed error reports.
GitLab
------
If a file `.gitlab-ci.yml` exists in the root of the git repository, GitLab will run a pipeline each time you push to the gitlab server. The file configures the docker image that will be called. Below is a sample which loads a php7 docker image, clones your files, installs composer dependencies, runs the built-in php webserver and finally runs codeception:
```
# Select image from https://hub.docker.com/_/php/
image: php:7.0
# Select what we should cache
cache:
paths:
- vendor/
before_script:
# Install git and unzip (composer will need them)
- apt-get update && apt-get install -qqy git unzip
# Install composer
- curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Install all project dependencies
- composer install
# Run webserver
- php -S localhost:8085 --docroot public &>/dev/null&
# Test
test:
script:
- vendor/bin/codecept run
```
For acceptance testing you can use `codeception/codeception` docker image as base. See example below:
```
image:
name: codeception/codeception
# clear image entrypoint to make bash being available
entrypoint: [""]
# run selenium chrome as a local service (put "host: 'selenium__standalone-chrome'" in environment configuration)
services:
- selenium/standalone-chrome:latest
# Select what we should cache
cache:
paths:
- vendor/
before_script:
# Install all project dependencies
- composer install
# Test
test:
script:
- vendor/bin/codecept run acceptance --xml --html
artifacts:
when: always
expire_in: 1 week
paths:
- tests/_output
# make the report available in Gitlab UI. see https://docs.gitlab.com/ee/ci/unit_test_reports.html
reports:
junit: tests/_output/report.xml
```
Conclusion
----------
It is highly recommended to use Continuous Integration system in development. Codeception is easy to install and run in any CI systems. However, each of them has their differences you should take into account. You can use different reporters to provide output in format expected by CI system.
* **Next Chapter: [ParallelExecution >](12-parallelexecution)**
* **Previous Chapter: [< Codecoverage](11-codecoverage)**
codeception Customization Customization
=============
In this chapter we will explain how you can extend and customize the file structure and test execution routines.
### Namespaces
To avoid naming conflicts between Actor classes and Helper classes, they should be separated into namespaces. To create test suites with namespaces you can add `--namespace` option to the bootstrap command:
```
php vendor/bin/codecept bootstrap --namespace frontend
```
This will bootstrap a new project with the `namespace: frontend` parameter in the `codeception.yml` file. Helpers will be in the `frontend\Codeception\Module` namespace and Actor classes will be in the `frontend` namespace.
Once each of your applications (bundles) has its own namespace and different Helper or Actor classes, you can execute all the tests in a single runner. Run the Codeception tests as usual, using the meta-config we created earlier:
```
php vendor/bin/codecept run
```
This will launch the test suites for all three applications and merge the reports from all of them. This is very useful when you run your tests on a Continuous Integration server and you want to get a single report in JUnit and HTML format. The code coverage report will be merged too.
If you want to run a specific suite from the application you can execute:
```
vendor/bin/codecept run unit -c frontend
```
Where `unit` is the name of suite and the `-c` option specifies the path to the `codeception.yml` configuration file to use. In this example we will assume that there is `frontend/codeception.yml` configuration file and that we will execute the unit tests for only that app.
Bootstrap
---------
To prepare environment for testing you can execute custom PHP script before all tests or just before a specific suite. This way you can initialize autoloader, check availability of a website, etc.
### Global Bootstrap
To run bootstrap script before all suites place it in `tests` directory (absolute paths supported as well). Then set a `bootstrap` config key in `codeception.yml`:
```
yml
# file will be loaded from tests/bootstrap.php
bootstrap: bootstrap.php
```
### Suite Bootstrap
To run a script for a specific suite, place it into the suite directory and add to suite config:
```
yml
# inside <suitename>.suite.yml
# file will be loaded from tests/<suitename>/bootstrap.php
bootstrap: bootstrap.php
```
### On Fly Bootstrap
Bootstrap script can be executed with `--bootstrap` option for `codecept run` command:
```
vendor/bin/codecept run --bootstrap bootstrap.php
```
In this case, bootstrap script will be executed before the Codeception is initialized. Bootstrap script should be located in current working directory or by an absolute path.
> Bootstrap is a classical way to run custom PHP code before your tests. However, we recommend you to use Extensions instead of bootstrap scripts for better flexibility. If you need configuration, conditional enabling or disabling bootstrap script, extensions should work for you better.
>
>
Extension
---------
Codeception has limited capabilities to extend its core features. Extensions are not supposed to override current functionality, but can be useful if you are an experienced developer and you want to hook into the testing flow.
By default, one `RunFailed` Extension is already enabled in your global `codeception.yml`. It allows you to rerun failed tests by using the `-g failed` option:
```
vendor/bin/codecept run -g failed
```
Codeception comes with bundled extensions located in `ext` directory. For instance, you can enable the Logger extension to log the test execution with Monolog:
```
extensions:
enabled:
- Codeception\Extension\RunFailed # default extension
- Codeception\Extension\Logger: # enabled extension
max_files: 5 # logger configuration
```
But what are extensions, anyway? Basically speaking, extensions are nothing more than event listeners based on the [Symfony Event Dispatcher](https://symfony.com/doc/current/components/event_dispatcher/introduction.html) component.
### Events
Here are the events and event classes. The events are listed in the order in which they happen during execution. All listed events are available as constants in `Codeception\Events` class.
| Event | When? | Triggered by |
| --- | --- | --- |
| `suite.before` | Before suite is executed | [Suite, Settings](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/SuiteEvent.php) |
| `test.start` | Before test is executed | [Test](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/TestEvent.php) |
| `test.before` | At the very beginning of test execution | [Codeception Test](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/TestEvent.php) |
| `step.before` | Before step | [Step](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/StepEvent.php) |
| `step.after` | After step | [Step](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/StepEvent.php) |
| `step.fail` | After failed step | [Step](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/StepEvent.php) |
| `test.fail` | After failed test | [Test, Fail](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/FailEvent.php) |
| `test.error` | After test ended with error | [Test, Fail](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/FailEvent.php) |
| `test.incomplete` | After executing incomplete test | [Test, Fail](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/FailEvent.php) |
| `test.skipped` | After executing skipped test | [Test, Fail](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/FailEvent.php) |
| `test.success` | After executing successful test | [Test](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/TestEvent.php) |
| `test.after` | At the end of test execution | [Codeception Test](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/TestEvent.php) |
| `test.end` | After test execution | [Test](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/TestEvent.php) |
| `suite.after` | After suite was executed | [Suite, Result, Settings](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/SuiteEvent.php) |
| `test.fail.print` | When test fails are printed | [Test, Fail](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/FailEvent.php) |
| `result.print.after` | After result was printed | [Result, Printer](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Event/PrintResultEvent.php) |
There may be some confusion between `test.start`/`test.before` and `test.after`/`test.end`. The start and end events are triggered by PHPUnit, but the before and after events are triggered by Codeception. Thus, when you are using classical PHPUnit tests (extended from `PHPUnit\Framework\TestCase`), the before/after events won’t be triggered for them. During the `test.before` event you can mark a test as skipped or incomplete, which is not possible in `test.start`. You can learn more from [Codeception internal event listeners](https://github.com/Codeception/Codeception/tree/4.0/src/Codeception/Subscriber).
The extension class itself is inherited from `Codeception\Extension`:
```
<?php
use \Codeception\Events;
class MyCustomExtension extends \Codeception\Extension
{
// list events to listen to
// Codeception\Events constants used to set the event
public static $events = array(
Events::SUITE_AFTER => 'afterSuite',
Events::TEST_BEFORE => 'beforeTest',
Events::STEP_BEFORE => 'beforeStep',
Events::TEST_FAIL => 'testFailed',
Events::RESULT_PRINT_AFTER => 'print',
);
// methods that handle events
public function afterSuite(\Codeception\Event\SuiteEvent $e) {}
public function beforeTest(\Codeception\Event\TestEvent $e) {}
public function beforeStep(\Codeception\Event\StepEvent $e) {}
public function testFailed(\Codeception\Event\FailEvent $e) {}
public function print(\Codeception\Event\PrintResultEvent $e) {}
}
```
By implementing event handling methods you can listen for events and even update passed objects. Extensions have some basic methods you can use:
* `write` - prints to the screen
* `writeln` - prints to the screen with a new-line character at the end
* `getModule` - allows you to access a module
* `hasModule` - checks if a module is enabled
* `getModuleNames` - list all enabled modules
* `_reconfigure` - can be implemented instead of overriding the constructor
### Enabling Extension
Once you’ve implemented a simple extension class, you can require it in `tests/_bootstrap.php`, load it with Composer’s autoloader defined in `composer.json`, or store the class inside `tests/_support`dir.
You can then enable it in `codeception.yml`
```
extensions:
enabled: [MyCustomExtension]
```
Extensions can also be enabled per suite inside suite configs (like `acceptance.suite.yml`) and for a specific environment.
To enable extension dynamically, execute the `run` command with `--ext` option. Provide a class name as a parameter:
```
php vendor/bin/codecept run --ext MyCustomExtension
php vendor/bin/codecept run --ext "\My\Extension"
```
If a class is in a `Codeception\Extension` namespace you can skip it and provide only a shortname. So Recorder extension can be started like this:
```
php vendor/bin/codecept run --ext Recorder
```
### Configuring Extension
In the extension, you can access the currently passed options via the `options` property. You also can access the global configuration via the `\Codeception\Configuration::config()` method. If you want to have custom options for your extension, you can pass them in the `codeception.yml` file:
```
extensions:
enabled: [MyCustomExtension]
config:
MyCustomExtension:
param: value
```
The passed in configuration is accessible via the `config` property: `$this->config['param']`.
Check out a very basic extension [Notifier](https://github.com/Codeception/Notifier).
### Custom Commands
You can add your own commands to Codeception.
Your custom commands have to implement the interface Codeception\CustomCommandInterface, because there has to be a function to get the name of the command.
You have to register your command in the file `codeception.yml`:
```
extensions:
commands: [Project\Command\MyCustomCommand]
```
If you want to activate the Command globally, because you are using more then one `codeception.yml` file, you have to register your command in the `codeception.dist.yml` in the root folder of your project.
Please see the [complete example](https://github.com/Codeception/Codeception/blob/4.0/tests/data/register_command/examples/MyCustomCommand.php)
Group Objects
-------------
Group Objects are extensions listening for the events of tests belonging to a specific group. When a test is added to a group:
```
<?php
/**
* @group admin
*/
public function testAdminCreatingNewBlogPost(\AcceptanceTester $I)
{
}
```
This test will trigger the following events:
* `test.before.admin`
* `step.before.admin`
* `step.after.admin`
* `test.success.admin`
* `test.fail.admin`
* `test.after.admin`
A group object is built to listen for these events. It is useful when an additional setup is required for some of your tests. Let’s say you want to load fixtures for tests that belong to the `admin` group:
```
<?php
namespace Group;
class Admin extends \Codeception\GroupObject
{
public static $group = 'admin';
public function _before(\Codeception\Event\TestEvent $e)
{
$this->writeln('inserting additional admin users...');
$db = $this->getModule('Db');
$db->haveInDatabase('users', ['name' => 'bill', 'role' => 'admin']);
$db->haveInDatabase('users', ['name' => 'john', 'role' => 'admin']);
$db->haveInDatabase('users', ['name' => 'mark', 'role' => 'banned']);
}
public function _after(\Codeception\Event\TestEvent $e)
{
$this->writeln('cleaning up admin users...');
// ...
}
}
```
GroupObjects can also be used to update the module configuration before running a test. For instance, for `nocleanup` group we prevent Doctrine2 module from wrapping test into transaction:
```
<?php
public static $group = 'nocleanup';
public function _before(\Codeception\Event\TestEvent $e)
{
$this->getModule('Doctrine2')->_reconfigure(['cleanup' => false]);
}
```
A group class can be created with `php vendor/bin/codecept generate:group groupname` command. Group classes will be stored in the `tests/_support/Group` directory.
A group class can be enabled just like you enable an extension class. In the file `codeception.yml`:
```
extensions:
enabled: [Group\Admin]
```
Now the Admin group class will listen for all events of tests that belong to the `admin` group.
Step Decorators
---------------
Actor classes include generated steps taken from corresponding modules and helpers. You can introduce wrappers for those steps by using step decorators.
Step decorators are used to implement conditional assertions. When enabled, conditional assertions take all method prefixed by `see` or `dontSee` and introduce new steps prefixed with `canSee` and `cantSee`. Contrary to standard assertions those assertions won’t stop test on failure. This is done by wrapping action into try/catch blocks.
List of available step decorators:
* [ConditionalAssertion](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Step/ConditionalAssertion.php) - failed assertion will be logged, but test will continue.
* [TryTo](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Step/TryTo.php) - failed action will be ignored.
* [Retry](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Step/Retry.php) - failed action will be retried automatically.
Step decorators can be added to suite config inside `steps` block:
```
yml
step_decorators:
- Codeception/Step/TryTo
- Codeception/Step/Retry
- Codeception/Step/ConditionalAssertion
```
You can introduce your own step decorators. Take a look into sample decorator classes and create your own class which implements `Codeception\Step\GeneratedStep` interface. A class should provide `getTemplate` method which returns a code block and variables passed into a template. Make your class accessible by autoloader and you can have your own step decorators working.
Custom Reporters
----------------
Alternative reporters can be implemented as extension. There are [DotReporter](https://codeception.com/extensions#DotReporter) and [SimpleReporter](https://codeception.com/extensions#SimpleReporter) extensions included. Use them to change output or use them as an example to build your own reporter. They can be easily enabled with `--ext` option
```
php vendor/bin/codecept run --ext DotReporter
```
If you want to use it as default reporter enable it in `codeception.yml`.
But what if you need to change the output format of the XML or JSON results triggered with the `--xml` or `--json` options? Codeception uses PHPUnit printers and overrides them. If you need to customize one of the standard reporters you can override them too. If you are thinking on implementing your own reporter you should add a `reporters` section to `codeception.yml` and override one of the standard printer classes with one of your own:
```
reporters:
xml: Codeception\PHPUnit\Log\JUnit
html: Codeception\PHPUnit\ResultPrinter\HTML
report: Codeception\PHPUnit\ResultPrinter\Report
```
All PHPUnit printers implement the [PHPUnit\_Framework\_TestListener](https://phpunit.de/manual/current/en/extending-phpunit.html#extending-phpunit.PHPUnit_Framework_TestListener) interface. It is recommended to read the code of the original reporter before overriding it.
Installation Templates
----------------------
Codeception setup can be customized for the needs of your application. If you build a distributable application and you have a personalized configuration you can build an Installation template which will help your users to start testing on their projects.
Codeception has built-in installation templates for
* [Acceptance tests](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Template/Acceptance.php)
* [Unit tests](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Template/Unit.php)
* [REST API tests](https://github.com/Codeception/Codeception/blob/4.0/src/Codeception/Template/Api.php)
They can be executed with `init` command:
```
php vendor/bin/codecept init Acceptance
```
To init tests in specific folder use `--path` option:
```
php vendor/bin/codecept init Acceptance --path acceptance_tests
```
You will be asked several questions and then config files will be generated and all necessary directories will be created. Learn from the examples above to build a custom Installation Template. Here are the basic rules you should follow:
* Templates should be inherited from [`Codeception\InitTemplate`](reference/inittemplate) class and implement `setup` method.
* Template class should be placed in `Codeception\Template` namespace so Codeception could locate them by class name
* Use methods like `say`, `saySuccess`, `sayWarning`, `sayError`, `ask`, to interact with a user.
* Use `createDirectoryFor`, `createEmptyDirectory` methods to create directories
* Use `createHelper`, `createActor` methods to create helpers and actors.
* Use [Codeception generators](https://github.com/Codeception/Codeception/tree/4.0/src/Codeception/Lib/Generator) to create other support classes.
One Runner for Multiple Applications
------------------------------------
If your project consists of several applications (frontend, admin, api) or you are using the Symfony framework with its bundles, you may be interested in having all tests for all applications (bundles) executed in one runner. In this case you will get one report that covers the whole project.
Place the `codeception.yml` file into the root folder of your project and specify the paths to the other `codeception.yml` configurations that you want to include:
```
include:
- frontend/src/*Bundle
- admin
- api/rest
paths:
output: _output
settings:
colors: false
```
You should also specify the path to the `log` directory, where the reports and logs will be saved.
> Wildcards (\*) can be used to specify multiple directories at once.
>
>
Conclusion
----------
Each feature mentioned above may help dramatically when using Codeception to automate the testing of large projects, although some features may require advanced knowledge of PHP. There is no “best practice” or “use cases” when we talk about groups, extensions, or other powerful features of Codeception. If you see you have a problem that can be solved using these extensions, then give them a try.
* **Next Chapter: [Data >](09-data)**
* **Previous Chapter: [< BDD](07-bdd)**
| programming_docs |
codeception Functional Tests Functional Tests
================
Now that we’ve written some acceptance tests, functional tests are almost the same, with one major difference: Functional tests don’t require a web server.
Under the hood, Codeception uses Symfony’s [BrowserKit](https://symfony.com/doc/current/components/browser_kit.html) to “send” requests to your app. So there’s no real HTTP request made, but rather a BrowserKit [Request object](https://github.com/symfony/browser-kit/blob/master/Request.php) with the required properties is passed to your framework’s (front-)controller.
As a first step, you need to enable Codeception’s module for your framework in `functional.suite.yml` (see below).
All of Codeception’s framework modules share the same interface, and thus your tests are not bound to any one of them. This is a sample functional test:
```
<?php
// LoginCest.php
class LoginCest
{
public function tryLogin(FunctionalTester $I)
{
$I->amOnPage('/');
$I->click('Login');
$I->fillField('Username', 'Miles');
$I->fillField('Password', 'Davis');
$I->click('Enter');
$I->see('Hello, Miles', 'h1');
// $I->seeEmailIsSent(); // only for Symfony
}
}
```
As you see, the syntax is the same for functional and acceptance tests.
Limitations
-----------
Functional tests are usually much faster than acceptance tests. But functional tests are less stable as they run Codeception and the application in one environment. If your application was not designed to run in long lived processes (e.g. if you use the `exit` operator or global variables), then functional tests are probably not for you.
### Headers, Cookies, Sessions
One of the common issues with functional tests is the use of PHP functions that deal with headers, sessions and cookies. As you may already know, the `header` function triggers an error if it is executed after PHP has already output something. In functional tests we run the application multiple times, thus we will get lots of irrelevant errors in the result.
### External URLs
Functional tests cannot access external URLs, just URLs within your project. You can use PhpBrowser to open external URLs.
### Shared Memory
In functional testing, unlike running the application the traditional way, the PHP application does not stop after it has finished processing a request. Since all requests are run in one memory container, they are not isolated. So **if you see that your tests are mysteriously failing when they shouldn’t - try to execute a single test.** This will show if the tests were failing because they weren’t isolated during the run. Keep your memory clean, avoid memory leaks and clean global and static variables.
Enabling Framework Modules
--------------------------
You have a functional testing suite in the `tests/functional` directory. To start, you need to include one of the framework modules in the suite configuration file: `tests/functional.suite.yml`.
### Symfony
To perform Symfony integration you just need to include the Symfony module into your test suite. If you also use Doctrine2, don’t forget to include it too. To make the Doctrine2 module connect using the `doctrine` service from Symfony, you should specify the Symfony module as a dependency for Doctrine2:
```
# functional.suite.yml
actor: FunctionalTester
modules:
enabled:
- Symfony
- Doctrine2:
depends: Symfony # connect to Symfony
```
By default this module will search for AppKernel in the `app` directory.
The module uses the Symfony Profiler to provide additional information and assertions.
[See the full reference](modules/symfony)
### Laravel5
The [Laravel5](modules/laravel5) module is included and requires no configuration:
```
# functional.suite.yml
actor: FunctionalTester
modules:
enabled:
- Laravel5
```
### Yii2
Yii2 tests are included in [Basic](https://github.com/yiisoft/yii2-app-basic) and [Advanced](https://github.com/yiisoft/yii2-app-advanced) application templates. Follow the Yii2 guides to start.
### Zend Framework 2
Use [the ZF2 module](modules/zf2) to run functional tests inside Zend Framework 2:
```
# functional.suite.yml
actor: FunctionalTester
modules:
enabled:
- ZF2
```
### Zend Expressive
[Zend Expressive](modules/zendexpressive) tests can be executed with enabling a corresponding module.
```
# functional.suite.yml
actor: FunctionalTester
modules:
enabled:
- ZendExpressive
```
> See module reference to more configuration options
>
>
### Phalcon 4
The `Phalcon4` module requires creating a bootstrap file which returns an instance of `\Phalcon\Mvc\Application`. To start writing functional tests with Phalcon support you should enable the `Phalcon4` module and provide the path to this bootstrap file:
```
# functional.suite.yml
actor: FunctionalTester
modules:
enabled:
- Phalcon4:
bootstrap: 'app/config/bootstrap.php'
cleanup: true
savepoints: true
```
[See the full reference](modules/phalcon4)
Writing Functional Tests
------------------------
Functional tests are written in the same manner as [Acceptance Tests](03-acceptancetests) with the `PhpBrowser` module enabled. All framework modules and the `PhpBrowser` module share the same methods and the same engine.
Therefore we can open a web page with `amOnPage` method:
```
<?php
$I->amOnPage('/login');
```
We can click links to open web pages:
```
<?php
$I->click('Logout');
// click link inside .nav element
$I->click('Logout', '.nav');
// click by CSS
$I->click('a.logout');
// click with strict locator
$I->click(['class' => 'logout']);
```
We can submit forms as well:
```
<?php
$I->submitForm('form#login', ['name' => 'john', 'password' => '123456']);
// alternatively
$I->fillField('#login input[name=name]', 'john');
$I->fillField('#login input[name=password]', '123456');
$I->click('Submit', '#login');
```
And do assertions:
```
<?php
$I->see('Welcome, john');
$I->see('Logged in successfully', '.notice');
$I->seeCurrentUrlEquals('/profile/john');
```
Framework modules also contain additional methods to access framework internals. For instance, Laravel5, Phalcon, and Yii2 modules have a `seeRecord` method which uses the ActiveRecord layer to check that a record exists in the database.
Take a look at the complete reference for the module you are using. Most of its methods are common to all modules but some of them are unique.
You can also access framework globals inside a test or access the dependency injection container inside the `Helper\Functional` class:
```
<?php
namespace Helper;
class Functional extends \Codeception\Module
{
function doSomethingWithMyService()
{
$service = $this->getModule('Symfony')->grabServiceFromContainer('myservice');
$service->doSomething();
}
}
```
Also check all available *Public Properties* of the used modules to get full access to their data.
Error Reporting
---------------
By default Codeception uses the `E_ALL & ~E_STRICT & ~E_DEPRECATED` error reporting level. In functional tests you might want to change this level depending on your framework’s error policy. The error reporting level can be set in the suite configuration file:
```
actor: FunctionalTester
...
error_level: E_ALL & ~E_STRICT & ~E_DEPRECATED
```
`error_level` can also be set globally in `codeception.yml` file. In order to do that, you need to specify `error_level` as a part of `settings`. For more information, see [Global Configuration](reference/configuration). Note that suite specific `error_level` value will override global value.
Conclusion
----------
Functional tests are great if you are using powerful frameworks. By using functional tests you can access and manipulate their internal state. This makes your tests shorter and faster. In other cases, if you don’t use frameworks there is no practical reason to write functional tests. If you are using a framework other than the ones listed here, create a module for it and share it with the community.
* **Next Chapter: [UnitTests >](05-unittests)**
* **Previous Chapter: [< AcceptanceTests](03-acceptancetests)**
codeception Parallel Execution Parallel Execution
==================
When execution time of your tests is longer than a coffee break, it is a good reason to think about making your tests faster. If you have already tried to run them on SSD drive, and the execution time still upsets you, it might be a good idea to run your tests in parallel.
Where to start
--------------
Codeception does not provide a command like `run-parallel`. There is no common solution that can play well for everyone. Here are the questions you will need to answer:
* How parallel processes will be executed?
* How parallel processes won’t affect each other?
* Will they use different databases?
* Will they use different hosts?
* How should I split my tests across parallel processes?
There are two approaches to achieve parallelization. We can use [Docker](https://docker.com) and run each process inside isolated containers, and have those containers executed simultaneously.
Docker works really well for isolating testing environments. By the time of writing this chapter, we didn’t have an awesome tool like it. This chapter demonstrates how to manage parallel execution manually. As you will see we spend too much effort trying to isolate tests which Docker does for free. Today we **recommend using Docker** for parallel testing.
Docker
------
Please make sure you have `docker` installed. Docker experience is required as well.
### Using Codeception Docker image
Run official Codeception image from DockerHub:
`docker run codeception/codeception` Running tests from a project, by mounting the current path as a host-volume into the container. The **default working directory in the container is `/project`**.
`docker run -v ${PWD}:/project codeception/codeception run` To prepare application and tests to be executed inside containers you will need to use [Docker Compose](https://docs.docker.com/compose/) to run multiple containers and connect them together.
Define all required services in `docker-compose.yml` file. Make sure to follow Docker philisophy: 1 service = 1 container. So each process should be defined as its own service. Those services can use official Docker images pulled from DockerHub. Directories with code and tests should be mounted using `volume` directive. And exposed ports should be explicitly set using `ports` directive.
We prepared a sample config with codeception, web server, database, and selenium with Chrome to be executed together.
```
version: '3'
services:
codecept:
image: codeception/codeception
depends_on:
- chrome
- web
volumes:
- .:/project
web:
image: php:7-apache
depends_on:
- db
volumes:
- .:/var/www/html
db:
image: percona:5.6
chrome:
image: selenium/standalone-chrome
```
Codeception service will execute command `codecept run` but only after all services are started. This is defined using `depends_on` parameter.
It is easy to add more custom services. For instance to use Redis you just simple add this lines:
```
redis:
image: redis:3
```
By default the image has codecept as its entrypoint, to run the tests simply supply the run command
```
docker-compose run --rm codecept help
```
Run suite
```
docker-compose run --rm codecept run acceptance
```
```
docker-compose run --rm codecept run acceptance LoginCest
```
Development bash
```
docker-compose run --rm --entrypoint bash codecept
```
And finally to execute testing in parallel you should define how you split your tests and run parallel processes for `docker-compose`. Here we split tests by suites, but you can use different groups to split your tests. In section below you will learn how to do that with Robo.
```
docker-compose --project-name test-web run -d --rm codecept run --html report-web.html web & \
docker-compose --project-name test-unit run -d --rm codecept run --html report-unit.html unit & \
docker-compose --project-name test-functional run -d --rm codecept run --html report-functional.html functional
```
At the end, it is worth specifying that Docker setup can be complicated and please make sure you understand Docker and Docker Compose before proceed. We prepared some links that might help you:
* [Acceptance Tests Demo Repository](https://github.com/dmstr/docker-acception)
* [Dockerized Codeception Internal Tests](https://github.com/Codeception/Codeception/blob/master/tests/README.md#dockerized-testing)
* [Phundament App with Codeception](https://gist.github.com/schmunk42/d6893a64963509ff93daea80f722f694)
If you want to automate splitting tests by parallel processes, and executing them using PHP script you should use Robo task runner to do that.
Robo
----
### What to do
Parallel Test Execution consists of 3 steps:
* splitting tests
* running tests in parallel
* merging results
We propose to perform those steps using a task runner. In this guide we will use [**Robo**](http://robo.li) task runner. It is a modern PHP task runner that is very easy to use. It uses [Symfony Process](https://symfony.com/doc/current/components/process.html) to spawn background and parallel processes. Just what we need for the step 2! What about steps 1 and 3? We have created robo [tasks](https://github.com/Codeception/robo-paracept) for splitting tests into groups and merging resulting JUnit XML reports.
To conclude, we need:
* [Robo](http://robo.li), a task runner.
* [robo-paracept](https://github.com/Codeception/robo-paracept) - Codeception tasks for parallel execution.
Preparing Robo and Robo-paracept
--------------------------------
Execute this command in an empty folder to install Robo and Robo-paracept :
```
$ composer require codeception/robo-paracept --dev
```
You need to install Codeception after, if codeception is already installed it will not work.
```
$ composer require codeception/codeception
```
### Preparing Robo
Initializes basic RoboFile in the root of your project
```
$ robo init
```
Open `RoboFile.php` to edit it
```
<?php
class RoboFile extends \Robo\Tasks
{
// define public methods as commands
}
```
Each public method in robofile can be executed as a command from console. Let’s define commands for 3 steps and include autoload.
```
<?php
require_once 'vendor/autoload.php';
class Robofile extends \Robo\Tasks
{
use \Codeception\Task\MergeReports;
use \Codeception\Task\SplitTestsByGroups;
public function parallelSplitTests()
{
}
public function parallelRun()
{
}
public function parallelMergeResults()
{
}
}
```
If you run `robo`, you can see the respective commands:
```
$ robo
Robo version 0.6.0
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
help Displays help for a command
list Lists commands
parallel
parallel:merge-results
parallel:run
parallel:split-tests
```
#### Step 1: Split Tests
Codeception can organize tests into [groups](07-advancedusage#Groups). Starting from 2.0 it can load information about a group from a files. Sample text file with a list of file names can be treated as a dynamically configured group. Take a look into sample group file:
```
tests/functional/LoginCept.php
tests/functional/AdminCest.php:createUser
tests/functional/AdminCest.php:deleteUser
```
Tasks from `\Codeception\Task\SplitTestsByGroups` will generate non-intersecting group files. You can either split your tests by files or by single tests:
```
<?php
function parallelSplitTests()
{
// Split your tests by files
$this->taskSplitTestFilesByGroups(5)
->projectRoot('.')
->testsFrom('tests/acceptance')
->groupsTo('tests/_data/paracept_')
->run();
/*
// Split your tests by single tests (alternatively)
$this->taskSplitTestsByGroups(5)
->projectRoot('.')
->testsFrom('tests/acceptance')
->groupsTo('tests/_data/paracept_')
->run();
*/
}
```
Let’s prepare group files:
```
$ robo parallel:split-tests
[Codeception\Task\SplitTestFilesByGroupsTask] Processing 33 files
[Codeception\Task\SplitTestFilesByGroupsTask] Writing tests/_data/paracept_1
[Codeception\Task\SplitTestFilesByGroupsTask] Writing tests/_data/paracept_2
[Codeception\Task\SplitTestFilesByGroupsTask] Writing tests/_data/paracept_3
[Codeception\Task\SplitTestFilesByGroupsTask] Writing tests/_data/paracept_4
[Codeception\Task\SplitTestFilesByGroupsTask] Writing tests/_data/paracept_5
```
Now we have group files. We should update `codeception.yml` to load generated group files. In our case we have groups: *paracept\_1*, *paracept\_2*, *paracept\_3*, *paracept\_4*, *paracept\_5*.
```
groups:
paracept_*: tests/_data/paracept_*
```
Let’s try to execute tests from the second group:
```
$ codecept run acceptance -g paracept_2
```
#### Step 2: Running Tests
Robo has `ParallelExec` task to spawn background processes.
##### Inside Container
If you are using [Docker](#docker) containers you can launch multiple Codeception containers for different groups:
```
public function parallelRun()
{
$parallel = $this->taskParallelExec();
for ($i = 1; $i <= 5; $i++) {
$parallel->process(
$this->taskExec('docker-compose run --rm codecept run')
->option('group', "paracept_$i") // run for groups paracept_*
->option('xml', "tests/_log/result_$i.xml") // provide xml report
);
}
return $parallel->run();
}
```
##### Locally
If you want to run tests locally just use preinstalled `taskCodecept` task of Robo to define Codeception commands and put them inside `parallelExec`.
```
<?php
public function parallelRun()
{
$parallel = $this->taskParallelExec();
for ($i = 1; $i <= 5; $i++) {
$parallel->process(
$this->taskCodecept() // use built-in Codecept task
->suite('acceptance') // run acceptance tests
->group("paracept_$i") // for all paracept_* groups
->xml("tests/_log/result_$i.xml") // save XML results
);
}
return $parallel->run();
}
```
In case you don’t use containers you can isolate processes by starting different web servers and databases per each test process.
We can define different databases for different processes. This can be done using [Environments](07-advancedusage#Environments). Let’s define 5 new environments in `acceptance.suite.yml`:
```
actor: AcceptanceTester
modules:
enabled:
- Db:
dsn: 'mysql:dbname=testdb;host=127.0.0.1'
user: 'root'
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
- WebDriver:
url: 'http://localhost/'
env:
env1:
modules:
config:
Db:
dsn: 'mysql:dbname=testdb_1;host=127.0.0.1'
WebDriver:
url: 'http://test1.localhost/'
env2:
modules:
config:
Db:
dsn: 'mysql:dbname=testdb_2;host=127.0.0.1'
WebDriver:
url: 'http://test2.localhost/'
env3:
modules:
config:
Db:
dsn: 'mysql:dbname=testdb_3;host=127.0.0.1'
WebDriver:
url: 'http://test3.localhost/'
env4:
modules:
config:
Db:
dsn: 'mysql:dbname=testdb_4;host=127.0.0.1'
WebDriver:
url: 'http://test4.localhost/'
env5:
modules:
config:
Db:
dsn: 'mysql:dbname=testdb_5;host=127.0.0.1'
WebDriver:
url: 'http://test5.localhost/'
```
---
After the `parallelRun` method is defined you can execute tests with
```
$ robo parallel:run
```
#### Step 3: Merge Results
In case of `parallelExec` task we recommend to save results as JUnit XML, which can be merged and plugged into Continuous Integration server.
```
<?php
function parallelMergeResults()
{
$merge = $this->taskMergeXmlReports();
for ($i=1; $i<=5; $i++) {
$merge->from("tests/_output/result_paracept_$i.xml");
}
$merge->into("tests/_output/result_paracept.xml")->run();
}
```
Now, we can execute :
```
$ robo parallel:merge-results
```
`result_paracept.xml` file will be generated. It can be processed and analyzed.
#### All Together
To create one command to rule them all we can define new public method `parallelAll` and execute all commands. We will save the result of `parallelRun` and use it for our final exit code:
```
<?php
function parallelAll()
{
$this->parallelSplitTests();
$result = $this->parallelRun();
$this->parallelMergeResults();
return $result;
}
```
Conclusion
----------
Codeception does not provide tools for parallel test execution. This is a complex task and solutions may vary depending on a project. We use [Robo](http://robo.li) task runner as an external tool to perform all required steps. To prepare our tests to be executed in parallel we use Codeception features of dynamic groups and environments. To do even more we can create Extensions and Group classes to perform dynamic configuration depending on a test process.
* **Previous Chapter: [< ContinuousIntegration](12-continuousintegration)**
| programming_docs |
codeception Code Coverage Code Coverage
=============
At some point you want to review which parts of your application are tested well and which are not. Just for this case the [CodeCoverage](https://en.wikipedia.org/wiki/Code_coverage) is used. When you execute your tests to collect coverage report, you will receive statistics of all classes, methods, and lines triggered by these tests. The ratio between all lines in script and all touched lines is a main coverage criterion. In the ideal world you should get 100% code coverage, but in reality 80% is really enough. Because even 100% code coverage rate doesn’t save you from fatal errors and crashes.
The required information is provided by [SebastianBergmann\CodeCoverage](https://github.com/sebastianbergmann/php-code-coverage), and you can use any of the supported drivers.
| Driver | Description |
| --- | --- |
| [Xdebug](https://github.com/xdebug/xdebug) | Great for debugging, but too slow when collecting coverage |
| [phpdbg](https://www.php.net/manual/en/book.phpdbg.php) | Faster than `Xdebug` but inaccurate |
| [pcov](https://github.com/krakjoe/pcov) | Fast and accurate, but no debug functionality — perfect for CI |
Coverage data can be collected manually for both local and remote tests. Remote tests may be executed on different nodes, or locally but running through web server. It may look hard to collect code coverage for Selenium tests or PhpBrowser tests. But Codeception supports remote codecoverage as well as local.
### Configuration
To enable code coverage put these lines in the global configuration file `codeception.yml`:
```
coverage:
enabled: true
```
That’s ok for now. But what files should be present in final coverage report? Pass an array of files or directory to include/exclude sections. The path ending with ‘\*’ matches the directory. Also you can use ‘\*’ mask in a file name, i.e. `app/models/*Model.php` to match all models.
There is a shortcut if you don’t need that complex filters:
```
coverage:
enabled: true
include:
- app/*
exclude:
- app/cache/*
```
Include and exclude options can be redefined for each suite in corresponding config files.
By default, if coverage is reported to be < 35% it is marked as low, and >70% is high coverage. You can also define high and low boundaries with `low_limit` and `high_limit` config options:
```
coverage:
enabled: true
low_limit: 30
high_limit: 60
```
By default, show all whitelisted files in `--coverage-text` output not just the ones with coverage information is set to false, config option:
```
coverage:
enabled: true
show_uncovered: false
```
By default, show only the coverage report summary in `--coverage-text` output is set to false, config option:
```
coverage:
enabled: true
show_only_summary: false
```
For further information please refer to the [PHPUnit configuration docs](https://phpunit.readthedocs.io/en/latest/configuration.html)
Local CodeCoverage
------------------
The basic codecoverage can be collected for functional and unit tests. If you performed configuration steps from above, you are ready to go. All you need is to execute codeception with `--coverage` option.
To generate a clover xml report or a tasty html report append also `--coverage-xml` and `--coverage-html` options.
```
codecept run --coverage --coverage-xml --coverage-html
```
XML and HTML reports are stored to the `_output` directory. The best way to review report is to open `index.html` from `tests/_output/coverage` in your browser. XML clover reports are used by IDEs (like PHPStorm) or Continuous Integration servers (like Jenkins).
Remote CodeCoverage
-------------------
### Local Server
If you run your application via Webserver (Apache, Nginx, PHP WebServer) you don’t have a direct access to tested code, so collecting coverage becomes a non-trivial task. The same goes for scripts that are tested on different nodes. To get access to this code you need `xdebug` installed with `remote_enable` option turned on. Codeception also requires a little spy to interact with your application. As your application runs standalone, without even knowing it is being tested, a small file should be included in order to collect coverage info.
This file is called `c3.php` and is [available on GitHub](https://github.com/Codeception/c3). `c3.php` should be downloaded and included in your application at the very first line from controller. By sending special headers Codeception will command your application when to start codecoverage collection and when to stop it. After the suite is finished, a report will be stored and Codeception will grab it from your application.
Please, follow installation instructions described in a [readme file](https://github.com/Codeception/c3).
To connect to `c3` Codeception uses url config from PhpBrowser or WebDriver module. But URL of index with `c3.php` included can be specified explicitly with `c3_url` parameter defined:
```
coverage:
# url of file which includes c3 router.
c3_url: 'http://127.0.0.1:8000/index-test.php/'
```
> note: we can’t have multiple `c3_url` on same host difference only by port. Please, use alias of domain (i.e. `frontend.test:8000`,`backend.test:8080`) instead.
>
>
After the `c3.php` file is included in application you can start gather coverage. In case you execute your application locally there is nothing to be changed in config. All codecoverage reports will be collected as usual and merged afterwards. Think of it: Codeception runs remote coverage in the same way as local.
#### Custom cookie domain
It’s possible to override the cookie domain set by Codeception during code coverage. Typical case for that is when you have several subdomains that your acceptance tests are visiting, e.g. `mysite.com` and `admin.mysite.com`. By default, Codeception will run code coverage only for the domain set in the url of the `WebDriver/url` (or `c3_url` if defined), thus leaving out other subdomains from code coverage. To avoid that and to include all relevant subdomains in code covereage, it’s advised to set `.mysite.com` as the cookie domain option:
```
coverage:
cookie_domain: ".mysite.com"
```
### Remote Server
But if you run tests on different server (or your webserver doesn’t use code from current directory) a single option `remote` should be added to config. For example, let’s turn on remote coverage for acceptance suite in `acceptance.suite.yml`:
```
coverage:
remote: true
```
In this case remote Code Coverage results won’t be merged with local ones, if this option is enabled. Merging is possible only in case a remote and local files have the same path. But in case of running tests on a remote server we are not sure of it.
CodeCoverage results from remote server will be saved to `tests/_output` directory. Please note that remote codecoverage results won’t be displayed in console by the reason mentioned above: local and remote results can’t be merged, and console displays results for local codecoverage.
### Working Directory (Docker/Shared Mounts)
If your remote server is accessed through a shared mount, or a mounted folder (IE: Docker Volumes), you can still get merged coverage details. Use the `work_dir` option to specify the work directory. When CodeCoverage runs, Codeception will update any path that matches the `work_dir` option to match the local current project directory.
Given a docker command similar to:
```
docker run -v $(pwd):/workdir -w /workdir...
```
Use the below configuration to allow coverage mergers.
```
coverage:
remote: false
work_dir: /workdir
```
### Remote Context Options
HTML report generation can at times take a little more time than the default 30 second timeout. Or maybe you want to alter SSL settings (verify\_peer, for example) To alter the way c3 sends it’s service requests to your webserver (be it a local or a remote one), you can use the `remote_context_options` key in `coverage` settings.
```
coverage:
remote_context_options:
http:
timeout: 60
ssl:
verify_peer: false
```
Context stream options are [well documented at php.net](https://php.net/manual/en/context.php)
Conclusion
----------
It’s never been easier to setup local and remote code coverage. Just one config and one additional file to include! **With Codeception you can easily generate CodeCoverage reports for your Selenium tests** (or other acceptance or api tests). Mixing reports for `acceptance`, `functional`, and `unit` suites provides you with the most complete information on which parts of your applications are tested and which are not.
* **Next Chapter: [ContinuousIntegration >](12-continuousintegration)**
* **Previous Chapter: [< APITesting](10-apitesting)**
codeception Unit & Integration Tests Unit & Integration Tests
========================
Codeception uses PHPUnit as a backend for running its tests. Thus, any PHPUnit test can be added to a Codeception test suite and then executed. If you ever wrote a PHPUnit test then do it just as you did before. Codeception adds some nice helpers to simplify common tasks.
Creating a Test
---------------
Create a test using `generate:test` command with a suite and test names as parameters:
```
php vendor/bin/codecept generate:test unit Example
```
It creates a new `ExampleTest` file located in the `tests/unit` directory.
As always, you can run the newly created test with this command:
```
php vendor/bin/codecept run unit ExampleTest
```
Or simply run the whole set of unit tests with:
```
php vendor/bin/codecept run unit
```
A test created by the `generate:test` command will look like this:
```
<?php
class ExampleTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
protected function _before()
{
}
protected function _after()
{
}
// tests
public function testMe()
{
}
}
```
Inside a class:
* all public methods with `test` prefix are tests
* `_before` method is executed before each test (like `setUp` in PHPUnit)
* `_after` method is executed after each test (like `tearDown` in PHPUnit)
Unit Testing
------------
Unit tests are focused around a single component of an application. All external dependencies for components should be replaced with test doubles.
A typical unit test may look like this:
```
<?php
class UserTest extends \Codeception\Test\Unit
{
public function testValidation()
{
$user = new User();
$user->setName(null);
$this->assertFalse($user->validate(['username']));
$user->setName('toolooooongnaaaaaaameeee');
$this->assertFalse($user->validate(['username']));
$user->setName('davert');
$this->assertTrue($user->validate(['username']));
}
}
```
### Assertions
There are pretty many assertions you can use inside tests. The most common are:
* `$this->assertEquals()`
* `$this->assertContains()`
* `$this->assertFalse()`
* `$this->assertTrue()`
* `$this->assertNull()`
* `$this->assertEmpty()`
Assertion methods come from PHPUnit. [See the complete reference at phpunit.de](https://phpunit.de/manual/current/en/appendixes.assertions.html).
### Test Doubles
Codeception provides [Codeception\Stub library](https://github.com/Codeception/Stub) for building mocks and stubs for tests. Under the hood it used PHPUnit’s mock builder but with much simplified API.
Alternatively, [Mockery](https://github.com/Codeception/MockeryModule) can be used inside Codeception.
#### Stubs
Stubs can be created with a static methods of `Codeception\Stub`.
```
<?php
$user = \Codeception\Stub::make('User', ['getName' => 'john']);
$name = $user->getName(); // 'john'
```
[See complete reference](reference/mock)
Inside unit tests (`Codeception\Test\Unit`) it is recommended to use alternative API:
```
<?php
// create a stub with find method replaced
$userRepository = $this->make(UserRepository::class, ['find' => new User]);
$userRepository->find(1); // => User
// create a dummy
$userRepository = $this->makeEmpty(UserRepository::class);
// create a stub with all methods replaced except one
$user = $this->makeEmptyExcept(User::class, 'validate');
$user->validate($data);
// create a stub by calling constructor and replacing a method
$user = $this->construct(User::class, ['name' => 'davert'], ['save' => false]);
// create a stub by calling constructor with empty methods
$user = $this->constructEmpty(User::class, ['name' => 'davert']);
// create a stub by calling constructor with empty methods
$user = $this->constructEmptyExcept(User::class, 'getName', ['name' => 'davert']);
$user->getName(); // => davert
$user->setName('jane'); // => this method is empty
```
[See complete reference](reference/mock)
Stubs can also be created using static methods from `Codeception\Stub` class. In this
```
<?php
\Codeception\Stub::make(UserRepository::class, ['find' => new User]);
```
See a reference for [static Stub API](reference/stub)
#### Mocks
To declare expectations for mocks use `Codeception\Stub\Expected` class:
```
<?php
// create a mock where $user->getName() should never be called
$user = $this->make('User', [
'getName' => Expected::never(),
'someMethod' => function() {}
]);
$user->someMethod();
// create a mock where $user->getName() should be called at least once
$user = $this->make('User', [
'getName' => Expected::atLeastOnce('Davert')
]
);
$user->getName();
$userName = $user->getName();
$this->assertEquals('Davert', $userName);
```
[See complete reference](reference/mock)
Integration Tests
-----------------
Unlike unit tests integration tests doesn’t require the code to be executed in isolation. That allows us to use database and other components inside a tests. To improve the testing experience modules can be used as in functional testing.
### Using Modules
As in scenario-driven functional or acceptance tests you can access Actor class methods. If you write integration tests, it may be useful to include the `Db` module for database testing.
```
# Codeception Test Suite Configuration
# suite for unit (internal) tests.
actor: UnitTester
modules:
enabled:
- Asserts
- Db
- \Helper\Unit
```
To access UnitTester methods you can use the `UnitTester` property in a test.
### Testing Database
Let’s see how you can do some database testing:
```
<?php
function testSavingUser()
{
$user = new User();
$user->setName('Miles');
$user->setSurname('Davis');
$user->save();
$this->assertEquals('Miles Davis', $user->getFullName());
$this->tester->seeInDatabase('users', ['name' => 'Miles', 'surname' => 'Davis']);
}
```
To enable the database functionality in unit tests, make sure the `Db` module is included in the `unit.suite.yml` configuration file. The database will be cleaned and populated after each test, the same way it happens for acceptance and functional tests. If that’s not your required behavior, change the settings of the `Db` module for the current suite. See [Db Module](modules/db)
### Interacting with the Framework
You should probably not access your database directly if your project already uses ORM for database interactions. Why not use ORM directly inside your tests? Let’s try to write a test using Laravel’s ORM Eloquent. For this we need to configure the Laravel5 module. We won’t need its web interaction methods like `amOnPage` or `see`, so let’s enable only the ORM part of it:
```
actor: UnitTester
modules:
enabled:
- Asserts
- Laravel5:
part: ORM
- \Helper\Unit
```
We included the Laravel5 module the same way we did for functional testing. Let’s see how we can use it for integration tests:
```
<?php
function testUserNameCanBeChanged()
{
// create a user from framework, user will be deleted after the test
$id = $this->tester->haveRecord('users', ['name' => 'miles']);
// access model
$user = User::find($id);
$user->setName('bill');
$user->save();
$this->assertEquals('bill', $user->getName());
// verify data was saved using framework methods
$this->tester->seeRecord('users', ['name' => 'bill']);
$this->tester->dontSeeRecord('users', ['name' => 'miles']);
}
```
A very similar approach can be used for all frameworks that have an ORM implementing the ActiveRecord pattern. In Yii2 and Phalcon, the methods `haveRecord`, `seeRecord`, `dontSeeRecord` work in the same way. They also should be included by specifying `part: ORM` in order to not use the functional testing actions.
If you are using Symfony with Doctrine, you don’t need to enable Symfony itself but just Doctrine2:
```
actor: UnitTester
modules:
enabled:
- Asserts
- Doctrine2:
depends: Symfony
- \Helper\Unit
```
In this case you can use the methods from the Doctrine2 module, while Doctrine itself uses the Symfony module to establish connections to the database. In this case a test might look like:
```
<?php
function testUserNameCanBeChanged()
{
// create a user from framework, user will be deleted after the test
$id = $this->tester->haveInRepository(User::class, ['name' => 'miles']);
// get entity manager by accessing module
$em = $this->getModule('Doctrine2')->em;
// get real user
$user = $em->find(User::class, $id);
$user->setName('bill');
$em->persist($user);
$em->flush();
$this->assertEquals('bill', $user->getName());
// verify data was saved using framework methods
$this->tester->seeInRepository(User::class, ['name' => 'bill']);
$this->tester->dontSeeInRepository(User::class, ['name' => 'miles']);
}
```
In both examples you should not be worried about the data persistence between tests. The Doctrine2 and Laravel5 modules will clean up the created data at the end of a test. This is done by wrapping each test in a transaction and rolling it back afterwards.
### Accessing Module
Codeception allows you to access the properties and methods of all modules defined for this suite. Unlike using the UnitTester class for this purpose, using a module directly grants you access to all public properties of that module.
We have already demonstrated this in a previous example where we accessed the Entity Manager from a Doctrine2 module:
```
<?php
/** @var Doctrine\ORM\EntityManager */
$em = $this->getModule('Doctrine2')->em;
```
If you use the `Symfony` module, here is how you can access the Symfony container:
```
<?php
/** @var Symfony\Component\DependencyInjection\Container */
$container = $this->getModule('Symfony')->container;
```
The same can be done for all public properties of an enabled module. Accessible properties are listed in the module reference.
### Scenario Driven Testing
[Cest format](07-advancedusage#Cest-Classes) can also be used for integration testing. In some cases it makes tests cleaner as it simplifies module access by using common `$I->` syntax:
```
<?php
public function buildShouldHaveSequence(\UnitTester $I)
{
$build = $I->have(Build::class, ['project_id' => $this->project->id]);
$I->assertEquals(1, $build->sequence);
$build = $I->have(Build::class, ['project_id' => $this->project->id]);
$I->assertEquals(2, $build->sequence);
$this->project->refresh();
$I->assertEquals(3, $this->project->build_sequence);
}
```
This format can be recommended for testing domain and database interactions.
In Cest format you don’t have native support for test doubles so it’s recommended to include a trait `\Codeception\Test\Feature\Stub` to enable mocks inside a test. Alternatively, install and enable [Mockery module](https://github.com/Codeception/MockeryModule).
Advanced Tools
--------------
### Specify
When writing tests you should prepare them for constant changes in your application. Tests should be easy to read and maintain. If a specification of your application is changed, your tests should be updated as well. If you don’t have a convention inside your team for documenting tests, you will have issues figuring out what tests will be affected by the introduction of a new feature.
That’s why it’s pretty important not just to cover your application with unit tests, but make unit tests self-explanatory. We do this for scenario-driven acceptance and functional tests, and we should do this for unit and integration tests as well.
For this case we have a stand-alone project [Specify](https://github.com/Codeception/Specify) (which is included in the phar package) for writing specifications inside unit tests:
```
<?php
class UserTest extends \Codeception\Test\Unit
{
use \Codeception\Specify;
/** @specify */
private $user;
public function testValidation()
{
$this->user = User::create();
$this->specify("username is required", function() {
$this->user->username = null;
$this->assertFalse($this->user->validate(['username']));
});
$this->specify("username is too long", function() {
$this->user->username = 'toolooooongnaaaaaaameeee';
$this->assertFalse($this->user->validate(['username']));
});
$this->specify("username is ok", function() {
$this->user->username = 'davert';
$this->assertTrue($this->user->validate(['username']));
});
}
}
```
By using `specify` codeblocks, you can describe any piece of a test. This makes tests much cleaner and comprehensible for everyone in your team.
Code inside `specify` blocks is isolated. In the example above, any changes to `$this->user` will not be reflected in other code blocks as it is marked with `@specify` annotation.
Also, you may add [Codeception\Verify](https://github.com/Codeception/Verify) for BDD-style assertions. This tiny library adds more readable assertions, which is quite nice, if you are always confused about which argument in `assert` calls is expected and which one is actual:
```
<?php
verify($user->getName())->equals('john');
```
### Domain Assertions
The more complicated your domain is the more explicit your tests should be. With [DomainAssert](https://github.com/Codeception/DomainAssert) library you can easily create custom assertion methods for unit and integration tests.
It allows to reuse business rules inside assertion methods:
```
<?php
$user = new User;
// simple custom assertions below:
$this->assertUserIsValid($user);
$this->assertUserIsAdmin($user);
// use combined explicit assertion
// to tell what you expect to check
$this->assertUserCanPostToBlog($user, $blog);
// instead of just calling a bunch of assertions
$this->assertNotNull($user);
$this->assertNotNull($blog);
$this->assertContain($user, $blog->getOwners());
```
With custom assertion methods you can improve readability of your tests and keep them focused around the specification.
### AspectMock
[AspectMock](https://github.com/Codeception/AspectMock) is an advanced mocking framework which allows you to replace any methods of any class in a test. Static methods, class methods, date and time functions can be easily replaced with AspectMock. For instance, you can test singletons!
```
<?php
public function testSingleton()
{
$class = MySingleton::getInstance();
$this->assertInstanceOf('MySingleton', $class);
test::double('MySingleton', ['getInstance' => new DOMDocument]);
$this->assertInstanceOf('DOMDocument', $class);
}
```
* [AspectMock on GitHub](https://github.com/Codeception/AspectMock)
* [AspectMock in Action](https://codeception.com/07-31-2013/nothing-is-untestable-aspect-mock.html)
* [How it Works](https://codeception.com/09-13-2013/understanding-aspectmock.html)
Error Reporting
---------------
By default Codeception uses the `E_ALL & ~E_STRICT & ~E_DEPRECATED` error reporting level. In unit tests you might want to change this level depending on your framework’s error policy. The error reporting level can be set in the suite configuration file:
```
actor: UnitTester
...
error_level: E_ALL & ~E_STRICT & ~E_DEPRECATED
```
`error_level` can also be set globally in `codeception.yml` file. In order to do that, you need to specify `error_level` as a part of `settings`. For more information, see [Global Configuration](reference/configuration). Note that suite specific `error_level` value will override global value.
Conclusion
----------
PHPUnit tests are first-class citizens in test suites. Whenever you need to write and execute unit tests, you don’t need to install PHPUnit separately, but use Codeception directly to execute them. Some nice features can be added to common unit tests by integrating Codeception modules. For most unit and integration testing, PHPUnit tests are enough. They run fast, and are easy to maintain.
* **Next Chapter: [ModulesAndHelpers >](06-modulesandhelpers)**
* **Previous Chapter: [< FunctionalTests](04-functionaltests)**
| programming_docs |
codeception Reusing Test Code Reusing Test Code
=================
Codeception uses modularity to create a comfortable testing environment for every test suite you write. Modules allow you to choose the actions and assertions that can be performed in tests.
What are Actors
---------------
All actions and assertions that can be performed by the Actor object in a class are defined in modules. It might look like Codeception limits you in testing, but that’s not true. You can extend the testing suite with your own actions and assertions, by writing them into a custom module, called a Helper. We will get back to this later in this chapter, but for now let’s look at the following test:
```
<?php
$I->amOnPage('/');
$I->see('Hello');
$I->seeInDatabase('users', ['id' => 1]);
$I->seeFileFound('running.lock');
```
It can operate with different entities: the web page can be loaded with the PhpBrowser module, the database assertion uses the Db module, and the file state can be checked with the Filesystem module.
Modules are attached to Actor classes in the suite config. For example, in `tests/acceptance.suite.yml` we should see:
```
actor: AcceptanceTester
modules:
enabled:
- PhpBrowser:
url: http://localhost
- Db
- Filesystem
```
The AcceptanceTester class has its methods defined in modules. Let’s see what’s inside the `AcceptanceTester` class, which is located inside the `tests/_support` directory:
```
<?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method void haveFriend($name, $actorClass = null)
*
* @SuppressWarnings(PHPMD)
*/
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
/**
* Define custom actions here
*/
}
```
The most important part is the `_generated\AcceptanceTesterActions` trait, which is used as a proxy for enabled modules. It knows which module executes which action and passes parameters into it. This trait was created by running `codecept build` and is regenerated each time module or configuration changes.
> Use actor classes to set common actions which can be used accross a suite.
>
>
PageObjects
-----------
For acceptance and functional testing, we will not only need to have common actions being reused across different tests, we should have buttons, links and form fields being reused as well. For those cases we need to implement the [PageObject pattern](https://www.selenium.dev/documentation/en/guidelines_and_recommendations/page_object_models/), which is widely used by test automation engineers. The PageObject pattern represents a web page as a class and the DOM elements on that page as its properties, and some basic interactions as its methods. PageObjects are very important when you are developing a flexible architecture of your acceptance or functional tests. Do not hard-code complex CSS or XPath locators in your tests but rather move them into PageObject classes.
Codeception can generate a PageObject class for you with command:
```
php vendor/bin/codecept generate:pageobject acceptance Login
```
> It is recommended to use page objects for acceptance testing only
>
>
This will create a `Login` class in `tests/_support/Page/Acceptance`. The basic PageObject is nothing more than an empty class with a few stubs.
It is expected that you will populate it with the UI locators of a page it represents. Locators can be added as public properties:
```
<?php
namespace Page\Acceptance;
class Login
{
public static $URL = '/login';
public $usernameField = '#mainForm #username';
public $passwordField = '#mainForm input[name=password]';
public $loginButton = '#mainForm input[type=submit]';
// ...
}
```
But let’s move further. The PageObject concept specifies that the methods for the page interaction should also be stored in a PageObject class.
Let’s define a `login` method in this class:
```
<?php
namespace Page\Acceptance;
class Login
{
public static $URL = '/login';
public $usernameField = '#mainForm #username';
public $passwordField = '#mainForm input[name=password]';
public $loginButton = '#mainForm input[type=submit]';
/**
* @var AcceptanceTester
*/
protected $tester;
// we inject AcceptanceTester into our class
public function __construct(\AcceptanceTester $I)
{
$this->tester = $I;
}
public function login($name, $password)
{
$I = $this->tester;
$I->amOnPage(self::$URL);
$I->fillField($this->usernameField, $name);
$I->fillField($this->passwordField, $password);
$I->click($this->loginButton);
}
}
```
If you specify which object you need for a test, Codeception will try to create it using the dependency injection container. In the case of a PageObject you should declare a class as a parameter for a test method:
```
<?php
class UserCest
{
function showUserProfile(AcceptanceTester $I, \Page\Acceptance\Login $loginPage)
{
$loginPage->login('bill evans', 'debby');
$I->amOnPage('/profile');
$I->see('Bill Evans Profile', 'h1');
}
}
```
The dependency injection container can construct any object that requires any known class type. For instance, `Page\Login` required `AcceptanceTester`, and so it was injected into `Page\Login` constructor, and PageObject was created and passed into method arguments. You should explicitly specify the types of required objects for Codeception to know what objects should be created for a test. Dependency Injection will be described in the next chapter.
StepObjects
-----------
StepObjects are great if you need some common functionality for a group of tests. Let’s say you are going to test an admin area of a site. You probably won’t need the same actions from the admin area while testing the front end, so it’s a good idea to move these admin-specific tests into their own class. We call such a classes StepObjects.
Lets create an Admin StepObject with the generator:
```
php vendor/bin/codecept generate:stepobject acceptance Admin
```
You can supply optional action names. Enter one at a time, followed by a newline. End with an empty line to continue to StepObject creation.
```
php vendor/bin/codecept generate:stepobject acceptance Admin
Add action to StepObject class (ENTER to exit): loginAsAdmin
Add action to StepObject class (ENTER to exit):
StepObject was created in /tests/acceptance/_support/Step/Acceptance/Admin.php
```
This will generate a class in `/tests/_support/Step/Acceptance/Admin.php` similar to this:
```
<?php
namespace Step\Acceptance;
class Admin extends \AcceptanceTester
{
public function loginAsAdmin()
{
$I = $this;
}
}
```
As you see, this class is very simple. It extends the `AcceptanceTester` class, meaning it can access all the methods and properties of `AcceptanceTester`.
The `loginAsAdmin` method may be implemented like this:
```
<?php
namespace Step\Acceptance;
class Admin extends \AcceptanceTester
{
public function loginAsAdmin()
{
$I = $this;
$I->amOnPage('/admin');
$I->fillField('username', 'admin');
$I->fillField('password', '123456');
$I->click('Login');
}
}
```
StepObject can be instantiated automatically when used inside the Cest format:
```
<?php
class UserCest
{
function showUserProfile(\Step\Acceptance\Admin $I)
{
$I->loginAsAdmin();
$I->amOnPage('/admin/profile');
$I->see('Admin Profile', 'h1');
}
}
```
If you have a complex interaction scenario, you may use several step objects in one test. If you feel like adding too many actions into your Actor class (which is AcceptanceTester in this case) consider moving some of them into separate StepObjects.
> Use StepObjects when you have multiple areas of applications or multiple roles.
>
>
Conclusion
----------
There are lots of ways to create reusable and readable tests. Group common actions together and move them to an Actor class or StepObjects. Move CSS and XPath locators into PageObjects. Write your custom actions and assertions in Helpers. Scenario-driven tests should not contain anything more complex than `$I->doSomething` commands. Following this approach will allow you to keep your tests clean, readable, stable and make them easy to maintain.
* **Next Chapter: [AdvancedUsage >](07-advancedusage)**
* **Previous Chapter: [< ModulesAndHelpers](06-modulesandhelpers)**
codeception Modules and Helpers Modules and Helpers
===================
Codeception uses modularity to create a comfortable testing environment for every test suite you write.
All actions and assertions that can be performed by the Tester object in a class are defined in modules. You can extend the testing suite with your own actions and assertions by writing them into a custom module.
Let’s look at the following test:
```
<?php
$I = new FunctionalTester($scenario);
$I->amOnPage('/');
$I->see('Hello');
$I->seeInDatabase('users', array('id' => 1));
$I->seeFileFound('running.lock');
```
It can operate with different entities: the web page can be loaded with the PhpBrowser module, the database assertion uses the Db module, and file state can be checked with the Filesystem module.
Modules are attached to the Actor classes in the suite configuration. For example, in `tests/functional.suite.yml` we should see:
```
actor: FunctionalTester
modules:
enabled:
- PhpBrowser:
url: http://localhost
- Db:
dsn: "mysql:host=localhost;dbname=testdb"
- Filesystem
```
The FunctionalTester class has its methods defined in modules. Actually, it doesn’t contain any of them, but rather acts as a proxy. It knows which module executes this action and passes parameters into it. To make your IDE see all of the FunctionalTester methods, you should run the `codecept build` command. It generates method signatures from enabled modules and saves them into a trait which is included in an actor. In the current example, the `tests/support/_generated/FunctionalTesterActions.php` file will be generated. By default, Codeception automatically rebuilds the Actions trait on each change of the suite configuration.
Standard Modules
----------------
Codeception has many bundled modules which will help you run tests for different purposes and different environments. The idea of modules is to share common actions, so that developers and QA engineers can concentrate on testing and not on reinventing the wheel. Each module provides methods for testing its own part and by combining modules you can get a powerful setup to test an application at all levels.
There is the `WebDriver` module for acceptance testing, modules for all popular PHP frameworks, `PHPBrowser` to emulate browser execution, `REST` for testing APIs, and more. Modules are considered to be the most valuable part of Codeception. They are constantly improving to provide the best testing experience, and be flexible to satisfy everyone’s needs.
### Module Conflicts
Modules may conflict with one another. If a module implements `Codeception\Lib\Interfaces\ConflictsWithModule`, it might declare a conflict rule to be used with other modules. For instance, WebDriver conflicts with all modules implementing the `Codeception\Lib\Interfaces\Web` interface.
```
public function _conflicts()
{
return 'Codeception\Lib\Interfaces\Web';
}
```
This way if you try to use two modules sharing the same conflicted interface you will get an exception.
To avoid confusion, **Framework modules, PhpBrowser, and WebDriver** can’t be used together. For instance, the `amOnPage` method exists in all those modules, and you should not try to guess which module will actually execute it. If you are doing acceptance testing, set up either WebDriver or PHPBrowser but do not set both up at the same time. If you are doing functional testing, enable only one of the framework modules.
In case you need to use a module which depends on a conflicted one, specify it as a dependent module in the configuration. You may want to use `WebDriver` with the `REST` module which interacts with a server through `PhpBrowser`. In this case your config should look like this:
```
modules:
enabled:
- WebDriver:
browser: firefox
url: http://localhost
- REST:
url: http://localhost/api/v1
depends: PhpBrowser
```
This configuration will allow you to send GET/POST requests to the server’s APIs while working with a site through a browser.
If you only need some parts of a conflicted module to be loaded, refer to the next section.
### Module Parts
Modules with *Parts* section in their reference can be partially loaded. This way, the `$I` object will have actions belonging to only a specific part of that module. Partially loaded modules can be also used to avoid module conflicts.
For instance, the Laravel5 module has an ORM part which contains database actions. You can enable the PhpBrowser module for testing and Laravel + ORM for connecting to the database and checking the data.
```
modules:
enabled:
- PhpBrowser:
url: http://localhost
- Laravel5:
part: ORM
```
The modules won’t conflict as actions with the same names won’t be loaded.
The REST module has parts for `Xml` and `Json` in the same way. If you are testing a REST service with only JSON responses, you can enable just the JSON part of this module:
```
actor: ApiTester
modules:
enabled:
- REST:
url: http://serviceapp/api/v1/
depends: PhpBrowser
part: Json
```
Helpers
-------
Codeception doesn’t restrict you to only the modules from the main repository. Your project might need your own actions added to the test suite. By running the `bootstrap` command, Codeception generates three dummy modules for you, one for each of the newly created suites. These custom modules are called ‘Helpers’, and they can be found in the `tests/_support` directory.
```
<?php
namespace Helper;
// here you can define custom functions for FunctionalTester
class Functional extends \Codeception\Module
{
}
```
Actions are also quite simple. Every action you define is a public function. Write a public method, then run the `build` command, and you will see the new function added into the FunctionalTester class.
Public methods prefixed by `\_` are treated as hidden and won't be added to your Actor class. Assertions can be a bit tricky. First of all, it’s recommended to prefix all your assertion actions with `see` or `dontSee`.
Name your assertions like this:
```
<?php
$I->seePageReloaded();
$I->seeClassIsLoaded($classname);
$I->dontSeeUserExist($user);
```
And then use them in your tests:
```
<?php
$I->seePageReloaded();
$I->seeClassIsLoaded('FunctionalTester');
$I->dontSeeUserExist($user);
```
You can define assertions by using assertXXX methods in your modules.
```
<?php
function seeClassExist($class)
{
$this->assertTrue(class_exists($class));
}
```
In your helpers you can use these assertions:
```
<?php
function seeCanCheckEverything($thing)
{
$this->assertTrue(isset($thing), "this thing is set");
$this->assertFalse(empty($any), "this thing is not empty");
$this->assertNotNull($thing, "this thing is not null");
$this->assertContains("world", $thing, "this thing contains 'world'");
$this->assertNotContains("bye", $thing, "this thing doesn't contain 'bye'");
$this->assertEquals("hello world", $thing, "this thing is 'Hello world'!");
// ...
}
```
### Accessing Other Modules
It’s possible that you will need to access internal data or functions from other modules. For example, for your module you might need to access the responses or internal actions of other modules.
Modules can interact with each other through the `getModule` method. Please note that this method will throw an exception if the required module was not loaded.
Let’s imagine that we are writing a module that reconnects to a database. It’s supposed to use the dbh connection value from the Db module.
```
<?php
function reconnectToDatabase()
{
$dbh = $this->getModule('Db')->dbh;
$dbh->close();
$dbh->open();
}
```
By using the `getModule` function, you get access to all of the public methods and properties of the requested module. The `dbh` property was defined as public specifically to be available to other modules.
Modules may also contain methods that are exposed for use in helper classes. Those methods start with a `_` prefix and are not available in Actor classes, so can be accessed only from modules and extensions.
You should use them to write your own actions using module internals.
```
<?php
function seeNumResults($num)
{
// retrieving webdriver session
/**@var $table \Facebook\WebDriver\WebDriverElement */
$elements = $this->getModule('WebDriver')->_findElements('#result');
$this->assertNotEmpty($elements);
$table = reset($elements);
$this->assertEquals('table', $table->getTagName());
$results = $table->findElements('tr');
// asserting that table contains exactly $num rows
$this->assertEquals($num, count($results));
}
```
In this example we use the API of the [facebook/php-webdriver](https://github.com/facebook/php-webdriver) library, a Selenium WebDriver client the module is build on. You can also access the `webDriver` property of a module to get access to the `Facebook\WebDriver\RemoteWebDriver` instance for direct Selenium interaction.
### Extending a Module
If accessing modules doesn’t provide enough flexibility, you can extend a module inside a Helper class:
```
<?php
namespace Helper;
class MyExtendedSelenium extends \Codeception\Module\WebDriver
{
}
```
In this helper you can replace the parent’s methods with your own implementation. You can also replace the `_before` and `_after` hooks, which might be an option when you need to customize starting and stopping of a testing session.
### Hooks
Each module can handle events from the running test. A module can be executed before the test starts, or after the test is finished. This can be useful for bootstrap/cleanup actions. You can also define special behavior for when the test fails. This may help you in debugging the issue. For example, the PhpBrowser module saves the current webpage to the `tests/_output` directory when a test fails.
All hooks are defined in [Codeception\Module](reference/module) and are listed here. You are free to redefine them in your module.
```
<?php
// HOOK: used after configuration is loaded
public function _initialize()
{
}
// HOOK: before each suite
public function _beforeSuite($settings = array())
{
}
// HOOK: after suite
public function _afterSuite()
{
}
// HOOK: before each step
public function _beforeStep(\Codeception\Step $step)
{
}
// HOOK: after each step
public function _afterStep(\Codeception\Step $step)
{
}
// HOOK: before test
public function _before(\Codeception\TestInterface $test)
{
}
// HOOK: after test
public function _after(\Codeception\TestInterface $test)
{
}
// HOOK: on fail
public function _failed(\Codeception\TestInterface $test, $fail)
{
}
```
Please note that methods with a `_` prefix are not added to the Actor class. This allows them to be defined as public but used only for internal purposes.
### Debug
As we mentioned, the `_failed` hook can help in debugging a failed test. You have the opportunity to save the current test’s state and show it to the user, but you are not limited to this.
Each module can output internal values that may be useful during debug. For example, the PhpBrowser module prints the response code and current URL every time it moves to a new page. Thus, modules are not black boxes. They are trying to show you what is happening during the test. This makes debugging your tests less painful.
To display additional information, use the `debug` and `debugSection` methods of the module. Here is an example of how it works for PhpBrowser:
```
<?php
$this->debugSection('Request', $params);
$this->client->request($method, $uri, $params);
$this->debug('Response Code: ' . $this->client->getStatusCode());
```
This test, running with the PhpBrowser module in debug mode, will print something like this:
```
I click "All pages"
* Request (GET) http://localhost/pages {}
* Response code: 200
```
Configuration
-------------
Modules and Helpers can be configured from the suite configuration file, or globally from `codeception.yml`.
Mandatory parameters should be defined in the `$requiredFields` property of the class. Here is how it is done in the Db module:
```
<?php
class Db extends \Codeception\Module
{
protected $requiredFields = ['dsn', 'user', 'password'];
// ...
}
```
The next time you start the suite without setting one of these values, an exception will be thrown.
For optional parameters, you should set default values. The `$config` property is used to define optional parameters as well as their values. In the WebDriver module we use the default Selenium Server address and port.
```
<?php
class WebDriver extends \Codeception\Module
{
protected $requiredFields = ['browser', 'url'];
protected $config = ['host' => '127.0.0.1', 'port' => '4444'];
// ...
}
```
The host and port parameter can be redefined in the suite configuration. Values are set in the `modules:config` section of the configuration file.
```
modules:
enabled:
- WebDriver:
url: 'http://mysite.com/'
browser: 'firefox'
- Db:
cleanup: false
repopulate: false
```
Optional and mandatory parameters can be accessed through the `$config` property. Use `$this->config['parameter']` to get its value.
### Dynamic Configuration With Parameters
Modules can be dynamically configured from environment variables. Parameter storage should be specified in the global `codeception.yml` configuration inside the `params` section. Parameters can be loaded from environment vars, from yaml (Symfony format), .env (Laravel format), ini, or php files.
Use the `params` section of the global configuration file `codeception.yml` to specify how to load them. You can specify several sources for parameters to be loaded from.
Example: load parameters from the environment:
```
params:
- env # load params from environment vars
```
Example: load parameters from YAML file (Symfony):
```
params:
- app/config/parameters.yml
```
Example: load parameters from php file (Yii)
```
params:
- config/params.php
```
Example: load parameters from .env files (Laravel):
```
params:
- .env
- .env.testing
```
Once loaded, parameter variables can be used as module configuration values. Use a variable name wrapped with `%` as a placeholder and it will be replaced by its value.
Let’s say we want to specify credentials for a cloud testing service. We have loaded `SAUCE_USER` and `SAUCE_KEY` variables from environment, and now we are passing their values into config of `WebDriver`:
```
modules:
enabled:
- WebDriver:
url: http://mysite.com
host: '%SAUCE_USER%:%SAUCE_KEY%@ondemand.saucelabs.com'
```
Parameters are also useful to provide connection credentials for the `Db` module (taken from Laravel’s .env files):
```
modules:
enabled:
- Db:
dsn: "mysql:host=%DB_HOST%;dbname=%DB_DATABASE%"
user: "%DB_USERNAME%"
password: "%DB_PASSWORD%"
```
### Runtime Configuration
If you want to reconfigure a module at runtime, you need to call a [helper](#Helpers) that uses the `_reconfigure` method of the module.
In this example we change the root URL for PhpBrowser, so that `amOnPage('/')` will open `/admin/`.
```
<?php
$this->getModule('PhpBrowser')->_reconfigure(['url' => 'http://localhost/admin']);
```
Usually, these configuration changes are effective immediately. However, in WebDriver configuration changes can’t be applied that easily. For instance, if you change the browser you need to close the current browser session and start a new one. For that, WebDriver module provides a `_restart` method which takes a config array and restarts the browser:
```
<?php
// start chrome
$this->getModule('WebDriver')->_restart(['browser' => 'chrome']);
// or just restart browser
$this->getModule('WebDriver')->_restart();
```
At the end of a test all configuration changes will be rolled back to the original configuration values.
### Runtime Configuration of a Test
Sometimes it is needed to set custom configuration for a specific test only. For [Cest](07-advancedusage#Cest-Classes) and [Test\Unit](05-unittests) formats you can use `@prepare` annotation which can execute the code before other hooks are executed. This allows `@prepare` to change the module configuration in runtime. `@prepare` uses [dependency injection](07-advancedusage#Dependency-Injection) to automatically inject required modules into a method.
To run a specific test only in Chrome browser, you can call `_reconfigure` from WebDriver module for a test itself using `@prepare`.
```
<?php
/**
* @prepare useChrome
*/
public function chromeSpecificTest()
{
// ...
}
protected function useChrome(\Codeception\Module\WebDriver $webdriver)
{
// WebDriver was injected by the class name
$webdriver->_reconfigure(['browser' => 'chrome']);
}
```
Prepare methods can invoke all methods of a module, as well as hidden API methods (starting with `_`). Use them to customize the module setup for a specific test.
To change module configuration for a specific group of tests use [GroupObjects](08-customization#Group-Objects).
Conclusion
----------
Modules are the real power of Codeception. They are used to emulate multiple inheritances for Actor classes (UnitTester, FunctionalTester, AcceptanceTester, etc). Codeception provides modules to emulate web requests, access data, interact with popular PHP libraries, etc. If the bundled modules are not enough for you that’s OK, you are free to write your own! Use Helpers (custom modules) for everything that Codeception can’t do out of the box. Helpers also can be used to extend the functionality of the original modules.
* **Next Chapter: [ReusingTestCode >](06-reusingtestcode)**
* **Previous Chapter: [< UnitTests](05-unittests)**
| programming_docs |
codeception API Testing API Testing
===========
The same way we tested a web site, Codeception allows you to test web services. They are very hard to test manually, so it’s a really good idea to automate web service testing. We have SOAP and REST as standards, which are represented in corresponding modules, which we will cover in this chapter.
You should start by creating a new test suite, (which was not provided by the `bootstrap` command). We recommend calling it **api** and using the `ApiTester` class for it.
```
php vendor/bin/codecept generate:suite api
```
We will put all the api tests there.
REST API
--------
> **NOTE:** REST API testing requires the `codeception/module-rest` package to be installed.
>
>
The REST web service is accessed via HTTP with standard methods: `GET`, `POST`, `PUT`, `DELETE`. They allow users to receive and manipulate entities from the service. Accessing a WebService requires an HTTP client, so for using it you need the module `PhpBrowser` or one of framework modules set up. For example, we can use the `Symfony` module for Symfony2 applications in order to ignore web server and test web service internally.
Configure modules in `api.suite.yml`:
```
actor: ApiTester
modules:
enabled:
- REST:
url: http://serviceapp/api/v1/
depends: PhpBrowser
```
The REST module will connect to `PhpBrowser` according to this configuration. Depending on the web service we may deal with XML or JSON responses. Codeception handles both data formats well, however If you don’t need one of them, you can explicitly specify that the JSON or XML parts of the module will be used:
```
actor: ApiTester
modules:
enabled:
- REST:
url: http://serviceapp/api/v1/
depends: PhpBrowser
part: Json
```
API tests can be functional and be executed using Symfony, Laravel5, Zend, or any other framework module. You will need slightly update configuration for it:
```
actor: ApiTester
modules:
enabled:
- REST:
url: /api/v1/
depends: Laravel5
```
Once we have configured our new testing suite, we can create the first sample test:
```
php vendor/bin/codecept generate:cest api CreateUser
```
It will be called `CreateUserCest.php`. We need to implement a public method for each test. Let’s make `createUserViaAPI` to test creation of a user via the REST API.
```
<?php
class CreateUserCest
{
// tests
public function createUserViaAPI(\ApiTester $I)
{
$I->amHttpAuthenticated('service_user', '123456');
$I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');
$I->sendPost('/users', [
'name' => 'davert',
'email' => '[email protected]'
]);
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
$I->seeResponseIsJson();
$I->seeResponseContains('{"result":"ok"}');
}
}
```
We can use HTTP code constants from `Codeception\Util\HttpCode` instead of numeric values to check response code in `seeResponseCodeIs` and `dontSeeResponseCodeIs` methods.
Let’s see what the test consist of.
### Authorization
To authorize requests to external resources, usually provider requires you to authorize using headers. Additional headers can be set before request using `haveHttpHeader` command:
```
<?php
$I->haveHttpHeader('api_key', 'special-key');
```
For common authorization patterns use one of the following methods:
* `amAWSAuthenticated`
* `amBearerAuthenticated`
* `amDigestAuthenticated`
* `amHttpAuthenticated`
* `amNTLMAuthenticated`
### Sending Requests
The real action in a test happens only when a request is sent. Before a request you may provide additional http headers which will be used in a next request to set authorization or expected content format.
```
<?php
$I->haveHttpHeader('accept', 'application/json');
$I->haveHttpHeader('content-type', 'application/json');
```
When headers are set, you can send a request. To obtain data use `sendGet`:
```
<?php
// pass in query params in second argument
$I->sendGet('/posts', [ 'status' => 'pending' ]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
```
> `sendGet` won’t return any value. However, you can access data from a response and perform assertions using other available methods of REST module.
>
>
To create or update data you can use other common methods:
* `sendPost`
* `sendPut`
* `sendDelete`
* `sendPatch`
### JSON Structure Validation
If we expect a JSON response to be received we can check its structure with [JSONPath](http://goessner.net/articles/JsonPath/). It looks and sounds like XPath but is designed to work with JSON data, however we can convert JSON into XML and use XPath to validate the structure. Both approaches are valid and can be used in the REST module:
```
<?php
$I->sendGet('/users');
$I->seeResponseCodeIs(HttpCode::OK); // 200
$I->seeResponseIsJson();
$I->seeResponseJsonMatchesJsonPath('$[0].user.login');
$I->seeResponseJsonMatchesXpath('//user/login');
```
More detailed check can be applied if you need to validate the type of fields in a response. You can do that by using with a [seeResponseMatchesJsonType](modules/rest#seeResponseMatchesJsonType) action in which you define the structure of JSON response.
```
<?php
$I->sendGet('/users/1');
$I->seeResponseCodeIs(HttpCode::OK); // 200
$I->seeResponseIsJson();
$I->seeResponseMatchesJsonType([
'id' => 'integer',
'name' => 'string',
'email' => 'string:email',
'homepage' => 'string:url|null',
'created_at' => 'string:date',
'is_active' => 'boolean'
]);
```
Codeception uses this simple and lightweight definitions format which can be [easily learned and extended](modules/rest#seeResponseMatchesJsonType).
### Taking Data From Responses
When you need to obtain a value from a response and use it in next requests you can use `grab*` methods. For instance, use `grabDataFromResponseByJsonPath` allows to query JSON for a value.
```
<?php
list($id) = $I->grabDataFromResponseByJsonPath('$.id');
$I->sendGet('/pet/' . $id);
```
### Validating Data JSON Responses
The last line of the previous example verified that the response contained the provided string. However we shouldn’t rely on it, as depending on content formatting we can receive different results with the same data. What we actually need is to check that the response can be parsed and it contains some of the values we expect. In the case of JSON we can use the `seeResponseContainsJson` method
```
<?php
// matches {"result":"ok"}'
$I->seeResponseContainsJson(['result' => 'ok']);
// it can match tree-like structures as well
$I->seeResponseContainsJson([
'user' => [
'name' => 'davert',
'email' => '[email protected]',
'status' => 'inactive'
]
]);
```
You may want to perform even more complex assertions on a response. This can be done by writing your own methods in the [Helper](06-reusingtestcode#Modules-and-Helpers) classes. To access the latest JSON response you will need to get the `response` property of the `REST` module. Let’s demonstrate it with the `seeResponseIsHtml` method:
```
<?php
namespace Helper;
class Api extends \Codeception\Module
{
public function seeResponseIsHtml()
{
$response = $this->getModule('REST')->response;
$this->assertRegExp('~^<!DOCTYPE HTML(.*?)<html>.*?<\/html>~m', $response);
}
}
```
The same way you can receive request parameters and headers.
### Testing XML Responses
In case your REST API works with XML format you can use similar methods to test its data and structure. There is `seeXmlResponseIncludes` method to match inclusion of XML parts in response, and `seeXmlResponseMatchesXpath` to validate its structure.
```
<?php
$I->sendGet('/users.xml');
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
$I->seeResponseIsXml();
$I->seeXmlResponseMatchesXpath('//user/login');
$I->seeXmlResponseIncludes(\Codeception\Util\Xml::toXml([
'user' => [
'name' => 'davert',
'email' => '[email protected]',
'status' => 'inactive'
]
]));
```
We are using `Codeception\Util\Xml` class which allows us to build XML structures in a clean manner. The `toXml` method may accept a string or array and returns \DOMDocument instance. If your XML contains attributes and so can’t be represented as a PHP array you can create XML using the [XmlBuilder](reference/xmlbuilder) class. We will take a look at it a bit more in next section.
> Use `\Codeception\Util\Xml::build()` to create XmlBuilder instance.
>
>
SOAP API
--------
SOAP web services are usually more complex. You will need PHP [configured with SOAP support](https://php.net/manual/en/soap.installation.php). Good knowledge of XML is required too. `SOAP` module uses specially formatted POST request to connect to WSDL web services. Codeception uses `PhpBrowser` or one of framework modules to perform interactions. If you choose using a framework module, SOAP will automatically connect to the underlying framework. That may improve the speed of a test execution and will provide you with more detailed stack traces.
Let’s configure `SOAP` module to be used with `PhpBrowser`:
```
actor: ApiTester
modules:
enabled:
- SOAP:
depends: PhpBrowser
endpoint: http://serviceapp/api/v1/
```
SOAP request may contain application specific information, like authentication or payment. This information is provided with SOAP header inside the `<soap:Header>` element of XML request. In case you need to submit such header, you can use `haveSoapHeader` action. For example, next line of code
```
<?php
$I->haveSoapHeader('Auth', ['username' => 'Miles', 'password' => '123456']);
```
will produce this XML header
```
<soap:Header>
<Auth>
<username>Miles</username>
<password>123456</password>
</Auth>
</soap:Header>
```
Use `sendSoapRequest` method to define the body of your request.
```
<?php
$I->sendSoapRequest('CreateUser', '<name>Miles Davis</name><email>[email protected]</email>');
```
This call will be translated to XML:
```
<soap:Body>
<ns:CreateUser>
<name>Miles Davis</name>
<email>[email protected]</email>
</ns:CreateUser>
</soap:Body>
```
And here is the list of sample assertions that can be used with SOAP.
```
<?php
$I->seeSoapResponseEquals('<?xml version="1.0"<error>500</error>');
$I->seeSoapResponseIncludes('<result>1</result>');
$I->seeSoapResponseContainsStructure('<user><name></name><email></email>');
$I->seeSoapResponseContainsXPath('//result/user/name[@id=1]');
```
In case you don’t want to write long XML strings, consider using [XmlBuilder](reference/xmlbuilder) class. It will help you to build complex XMLs in jQuery-like style. In the next example we will use `XmlBuilder` instead of regular XML.
```
<?php
$I->haveSoapHeader('Session', array('token' => '123456'));
$I->sendSoapRequest('CreateUser', Xml::build()
->user->email->val('[email protected]'));
$I->seeSoapResponseIncludes(\Codeception\Util\Xml::build()
->result->val('Ok')
->user->attr('id', 1)
);
```
It’s up to you to decide whether to use `XmlBuilder` or plain XML. `XmlBuilder` will return XML string as well.
You may extend current functionality by using `SOAP` module in your helper class. To access the SOAP response as `\DOMDocument` you can use `response` property of `SOAP` module.
```
<?php
namespace Helper;
class Api extends \Codeception\Module {
public function seeResponseIsValidOnSchema($schema)
{
$response = $this->getModule('SOAP')->response;
$this->assertTrue($response->schemaValidate($schema));
}
}
```
Conclusion
----------
Codeception has two modules that will help you to test various web services. They need a new `api` suite to be created. Remember, you are not limited to test only response body. By including `Db` module you may check if a user has been created after the `CreateUser` call. You can improve testing scenarios by using REST or SOAP responses in your helper methods.
* **Next Chapter: [Codecoverage >](11-codecoverage)**
* **Previous Chapter: [< Data](09-data)**
codeception Getting Started Getting Started
===============
Let’s take a look at Codeception’s architecture. We’ll assume that you have already [installed](https://codeception.com/install) it and bootstrapped your first test suites. Codeception has generated three of them: unit, functional, and acceptance. They are well described in the [previous chapter](01-introduction). Inside your **/tests** folder you will have three `.yml` config files and three directories with names corresponding to these suites: `unit`, `functional`, `acceptance`. Suites are independent groups of tests with a common purpose.
The Codeception Syntax
----------------------
Codeception follows simple naming rules to make it easy to remember (as well as easy to understand) its method names.
* **Actions** start with a plain english verb, like “click” or “fill”. Examples:
```
<?php
$I->click('Login');
$I->fillField('#input-username', 'John Dough');
$I->pressKey('#input-remarks', 'foo');
```
* **Assertions** always start with “see” or “dontSee”. Examples:
```
<?php
$I->see('Welcome');
$I->seeInTitle('My Company');
$I->seeElement('nav');
$I->dontSeeElement('#error-message');
$I->dontSeeInPageSource('<section class="foo">');
```
* **Grabbers** take information. The return value of those are meant to be saved as variables and used later. Example:
```
<?php
$method = $I->grabAttributeFrom('#login-form', 'method');
$I->assertEquals('post', $method);
```
Actors
------
One of the main concepts of Codeception is representation of tests as actions of a person. We have a UnitTester, who executes functions and tests the code. We also have a FunctionalTester, a qualified tester, who tests the application as a whole, with knowledge of its internals. Lastly we have an AcceptanceTester, a user who works with our application through an interface that we provide.
Methods of actor classes are generally taken from [Codeception Modules](06-modulesandhelpers). Each module provides predefined actions for different testing purposes, and they can be combined to fit the testing environment. Codeception tries to solve 90% of possible testing issues in its modules, so you don’t have to reinvent the wheel. We think that you can spend more time on writing tests and less on writing support code to make those tests run. By default, AcceptanceTester relies on PhpBrowser module, which is set in the `tests/acceptance.suite.yml` configuration file:
```
actor: AcceptanceTester
modules:
enabled:
- PhpBrowser:
url: http://localhost/myapp/
- \Helper\Acceptance
```
In this configuration file you can enable/disable and reconfigure modules for your needs. When you change the configuration, the actor classes are rebuilt automatically. If the actor classes are not created or updated as you expect, try to generate them manually with the `build` command:
```
php vendor/bin/codecept build
```
Writing a Sample Test
---------------------
Codeception has its own testing format called Cest (Codecept + Test). To start writing a test we need to create a new Cest file. We can do that by running the following command:
```
php vendor/bin/codecept generate:cest acceptance Signin
```
This will generate `SigninCest.php` file inside `tests/acceptance` directory. Let’s open it:
```
<?php
class SigninCest
{
function _before(AcceptanceTester $I)
{
}
public function _after(AcceptanceTester $I)
{
}
public function tryToTest(AcceptanceTester $I)
{
// todo: write test
}
}
```
We have `_before` and `_after` methods to run some common actions before and after a test. And we have a placeholder action `tryToTest` which we need to implement. If we try to test a signin process it’s a good start to test a successful signin. Let’s rename this method to `signInSuccessfully`.
We’ll assume that we have a ‘login’ page where we get authenticated by providing a username and password. Then we are sent to a user page, where we see the text `Hello, %username%`. Let’s look at how this scenario is written in Codeception:
```
<?php
class SigninCest
{
public function signInSuccessfully(AcceptanceTester $I)
{
$I->amOnPage('/login');
$I->fillField('Username','davert');
$I->fillField('Password','qwerty');
$I->click('Login');
$I->see('Hello, davert');
}
}
```
This scenario can probably be read by non-technical people. If you just remove all special chars like braces, arrows and `$`, this test transforms into plain English text:
```
I amOnPage '/login'
I fillField 'Username','davert'
I fillField 'Password','qwerty'
I click 'Login'
I see 'Hello, davert'
```
Codeception generates this text representation from PHP code by executing:
```
php vendor/bin/codecept generate:scenarios
```
These generated scenarios will be stored in your `_data` directory in text files.
Before we execute this test, we should make sure that the website is running on a local web server. Let’s open the `tests/acceptance.suite.yml` file and replace the URL with the URL of your web application:
```
actor: AcceptanceTester
modules:
enabled:
- PhpBrowser:
url: 'http://myappurl.local'
- \Helper\Acceptance
```
After configuring the URL we can run this test with the `run` command:
```
php vendor/bin/codecept run
```
This is the output we should see:
```
Acceptance Tests (1) -------------------------------
✔ SigninCest: sign in successfully
----------------------------------------------------
Time: 1 second, Memory: 21.00Mb
OK (1 test, 1 assertions)
```
Let’s get some detailed output:
```
php vendor/bin/codecept run acceptance --steps
```
We should see a step-by-step report on the performed actions:
```
Acceptance Tests (1) -------------------------------
SigninCest: Login to website
Signature: SigninCest.php:signInSuccessfully
Test: tests/acceptance/SigninCest.php:signInSuccessfully
Scenario --
I am on page "/login"
I fill field "Username" "davert"
I fill field "Password" "qwerty"
I click "Login"
I see "Hello, davert"
OK
----------------------------------------------------
Time: 0 seconds, Memory: 21.00Mb
OK (1 test, 1 assertions)
```
This simple test can be extended to a complete scenario of site usage, therefore, by emulating the user’s actions, you can test any of your websites.
To run more tests create a public method for each of them. Include `AcceptanceTester` object as `$I` as a method parameter and use the same `$I->` API you’ve seen before. If your tests share common setup actions put them into `_before` method.
For instance, to test CRUD we want 4 methods to be implemented and all next tests should start at `/task` page:
```
<?php
class TaskCrudCest
{
function _before(AcceptanceTester $I)
{
// will be executed at the beginning of each test
$I->amOnPage('/task');
}
function createTask(AcceptanceTester $I)
{
// todo: write test
}
function viewTask(AcceptanceTester $I)
{
// todo: write test
}
function updateTask(AcceptanceTester $I)
{
// todo: write test
}
function deleteTask(AcceptanceTester $I)
{
// todo: write test
}
}
```
Learn more about the [Cest format](07-advancedusage#Cest-Classes) in the Advanced Testing section.
Interactive Pause
-----------------
It’s hard to write a complete test at once. You will need to try different commands with different arguments before you find a correct path.
Since Codeception 3.0 you can pause the execution at any point and enter an interactive shell where you will be able to try different commands in action. All you need to do is **call `$I->pause()`** somewhere in your test, then run the test in [debug mode](#Debugging).
Interactive Pause requires [`hoa/console`](https://hoa-project.net/) which is not installed by default. To install it, run:
```
php composer.phar require --dev hoa/console
```
```
<?php
// use pause inside a test:
$I->pause();
```
The execution of the test is stopped at this point, and a console is shown where you can try all available commands “live”. This can be very useful when you write functional, acceptance, or api test.

Inside Interactive Pause you can use the entire power of the PHP interpreter: variables, functions, etc. You can access the result of the last executed command in a variable called `$result`.
In acceptance or functional test you can save page screenshot or html snapshot.
```
<?php
// inside PhpBrowser, WebDriver, frameworks
// saves current HTML and prints a path to created file
$I->makeHtmlSnapshot();
// inside WebDriver
// saves screenshot and prints a path to created file
$I->makeScreenshot();
```
To try commands without running a single test you can launch interactive console:
```
$ php vendor/bin/codecept console suitename
```
Now you can execute all the commands of a corresponding Actor class and see the results immediately.
BDD
---
Codeception allows execution of user stories in Gherkin format in a similar manner as is done in Cucumber or Behat. Please refer to [the BDD chapter](07-bdd) to learn more.
Configuration
-------------
Codeception has a global configuration in `codeception.yml` and a config for each suite. We also support `.dist` configuration files. If you have several developers in a project, put shared settings into `codeception.dist.yml` and personal settings into `codeception.yml`. The same goes for suite configs. For example, the `unit.suite.yml` will be merged with `unit.suite.dist.yml`.
Running Tests
-------------
Tests can be started with the `run` command:
```
php vendor/bin/codecept run
```
With the first argument you can run all tests from one suite:
```
php vendor/bin/codecept run acceptance
```
To limit tests run to a single class, add a second argument. Provide a local path to the test class, from the suite directory:
```
php vendor/bin/codecept run acceptance SigninCest.php
```
Alternatively you can provide the full path to test file:
```
php vendor/bin/codecept run tests/acceptance/SigninCest.php
```
You can further filter which tests are run by appending a method name to the class, separated by a colon (for Cest or Test formats):
```
php vendor/bin/codecept run tests/acceptance/SigninCest.php:^anonymousLogin$
```
You can provide a directory path as well. This will execute all acceptance tests from the `backend` dir:
```
php vendor/bin/codecept run tests/acceptance/backend
```
Using regular expressions, you can even run many different test methods from the same directory or class. For example, this will execute all acceptance tests from the `backend` dir beginning with the word “login”:
```
php vendor/bin/codecept run tests/acceptance/backend:^login
```
To execute a group of tests that are not stored in the same directory, you can organize them in [groups](07-advancedusage#Groups).
### Reports
To generate JUnit XML output, you can provide the `--xml` option, and `--html` for HTML report.
```
php vendor/bin/codecept run --steps --xml --html
```
This command will run all tests for all suites, displaying the steps, and building HTML and XML reports. Reports will be stored in the `tests/_output/` directory.
To see all the available options, run the following command:
```
php vendor/bin/codecept help run
```
Debugging
---------
To receive detailed output, tests can be executed with the `--debug` option. You may print any information inside a test using the `codecept_debug` function.
### Generators
There are plenty of useful Codeception commands:
* `generate:cest` *suite* *filename* - Generates a sample Cest test
* `generate:test` *suite* *filename* - Generates a sample PHPUnit Test with Codeception hooks
* `generate:feature` *suite* *filename* - Generates Gherkin feature file
* `generate:suite` *suite* *actor* - Generates a new suite with the given Actor class name
* `generate:scenarios` *suite* - Generates text files containing scenarios from tests
* `generate:helper` *filename* - Generates a sample Helper File
* `generate:pageobject` *suite* *filename* - Generates a sample Page object
* `generate:stepobject` *suite* *filename* - Generates a sample Step object
* `generate:environment` *env* - Generates a sample Environment configuration
* `generate:groupobject` *group* - Generates a sample Group Extension
Conclusion
----------
We have taken a look into the Codeception structure. Most of the things you need were already generated by the `bootstrap` command. After you have reviewed the basic concepts and configurations, you can start writing your first scenario.
* **Next Chapter: [AcceptanceTests >](03-acceptancetests)**
* **Previous Chapter: [< Introduction](01-introduction)**
| programming_docs |
codeception Working with Data Working with Data
=================
Tests should not affect each other. That’s a rule of thumb. When tests interact with a database, they may change the data inside it, which would eventually lead to data inconsistency. A test may try to insert a record that has already been inserted, or retrieve a deleted record. To avoid test failures, the database should be brought back to its initial state before each test. Codeception has different methods and approaches to get your data cleaned.
This chapter summarizes all of the notices on clean-ups from the previous chapters and suggests the best strategies of how to choose data storage backends.
When we decide to clean up a database, we should make this cleaning as fast as possible. Tests should always run fast. Rebuilding the database from scratch is not the best way, but might be the only one. In any case, you should use a special test database for testing. **Do not ever run tests on development or production databases!**
Db
--
Codeception has a `Db` module, which takes on most of the tasks of database interaction.
```
modules:
config:
Db:
dsn: 'PDO DSN HERE'
user: 'root'
password:
```
Use [module parameters](06-modulesandhelpers#Dynamic-Configuration-With-Params) to set the database credentials from environment variables or from application configuration files. Db module can cleanup database between tests by loading a database dump. This can be done by parsing SQL file and executing its commands using current connection
```
modules:
config:
Db:
dsn: 'PDO DSN HERE'
user: 'root'
password:
dump: tests/_data/your-dump-name.sql
cleanup: true # reload dump between tests
populate: true # load dump before all tests
```
Alternatively an external tool (like mysql client, or pg\_restore) can be used. This approach is faster and won’t produce parsing errors while loading a dump. Use `populator` config option to specify the command. For MySQL it can look like this:
```
modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
cleanup: true # run populator before each test
populate: true # run populator before all test
populator: 'mysql -u $user $dbname < tests/_data/dump.sql'
```
See the [Db module reference](modules/db#SQL-data-dump) for more examples.
To ensure database dump is loaded before all tests add `populate: true`. To clean current database and reload dump between tests use `cleanup: true`.
A full database clean-up can be painfully slow if you use large database dumps. It is recommended to do more data testing on the functional and integration levels, this way you can get performance bonuses from using ORM. In acceptance tests, your tests are interacting with the application through a web server. This means that the test and the application work with the same database. You should provide the same credentials in the Db module that your application uses, then you can access the database for assertions (`seeInDatabase` actions) and to perform automatic clean-ups.
The Db module provides actions to create and verify data inside a database.
If you want to create a special database record for one test, you can use [`haveInDatabase`](modules/db#haveInDatabase) method of `Db` module:
```
<?php
$I->haveInDatabase('posts', [
'title' => 'Top 10 Testing Frameworks',
'body' => '1. Codeception'
]);
$I->amOnPage('/posts');
$I->see('Top 10 Testing Frameworks');
```
`haveInDatabase` inserts a row with the provided values into the database. All added records will be deleted at the end of the test.
If you want to check that a table record was created use [`seeInDatabase`](modules/db#haveInDatabase) method:
```
<?php
$I->amOnPage('/posts/1');
$I->fillField('comment', 'This is nice!');
$I->click('Submit');
$I->seeInDatabase('comments', ['body' => 'This is nice!']);
```
See the module [reference](modules/db) for other methods you can use for database testing.
There are also modules for [MongoDb](modules/mongodb), [Redis](modules/redis), and [Memcache](modules/memcache) which behave in a similar manner.
### Sequence
If the database clean-up takes too long, you can follow a different strategy: create new data for each test. This way, the only problem you might face is duplication of data records. [Sequence](modules/sequence) was created to solve this. It provides the `sq()` function which generates unique suffixes for creating data in tests.
ORM modules
-----------
Your application is most likely using object-relational mapping (ORM) to work with the database. In this case, Codeception allows you to use the ORM methods to work with the database, instead of accessing the database directly. This way you can work with models and entities of a domain, and not on tables and rows.
By using ORM in functional and integration tests, you can also improve performance of your tests. Instead of cleaning up the database after each test, the ORM module will wrap all the database actions into transactions and roll it back at the end. This way, no actual data will be written to the database. This clean-up strategy is enabled by default, you can disable it by setting `cleanup: false` in the configuration of any ORM module.
### ActiveRecord
Popular frameworks like Laravel, Yii, and Phalcon include an ActiveRecord data layer by default. Because of this tight integration, you just need to enable the framework module, and use its configuration for database access.
Corresponding framework modules provide similar methods for ORM access:
* `haveRecord`
* `seeRecord`
* `dontSeeRecord`
* `grabRecord`
They allow you to create and check data by model name and field names in the model. Here is the example in Laravel:
```
<?php
// create record and get its id
$id = $I->haveRecord('posts', ['body' => 'My first blogpost', 'user_id' => 1]);
$I->amOnPage('/posts/'.$id);
$I->see('My first blogpost', 'article');
// check record exists
$I->seeRecord('posts', ['id' => $id]);
$I->click('Delete');
// record was deleted
$I->dontSeeRecord('posts', ['id' => $id]);
```
Laravel5 module provides the method `have` which uses the [factory](https://laravel.com/docs/5.8/database-testing#generating-factories) method to generate models with fake data.
If you want to use ORM for integration testing only, you should enable the framework module with only the `ORM` part enabled:
```
modules:
enabled:
- Laravel5:
- part: ORM
```
```
modules:
enabled:
- Yii2:
- part: ORM
```
This way no web actions will be added to `$I` object.
If you want to use ORM to work with data inside acceptance tests, you should also include only the ORM part of a module. Please note that inside acceptance tests, web applications work inside a webserver, so any test data can’t be cleaned up by rolling back transactions. You will need to disable cleaning up, and use the `Db` module to clean the database up between tests. Here is a sample config:
```
modules:
enabled:
- WebDriver:
url: http://localhost
browser: firefox
- Laravel5:
cleanup: false
- Db
```
### Doctrine
Doctrine is also a popular ORM, unlike some others it implements the DataMapper pattern and is not bound to any framework. The [Doctrine2](modules/doctrine2) module requires an `EntityManager` instance to work with. It can be obtained from a Symfony framework or Zend Framework (configured with Doctrine):
```
modules:
enabled:
- Symfony
- Doctrine2:
depends: Symfony
```
```
modules:
enabled:
- ZF2
- Doctrine2:
depends: ZF2
```
If no framework is used with Doctrine you should provide the `connection_callback` option with a valid callback to a function which returns an `EntityManager` instance.
Doctrine2 also provides methods to create and check data:
* `haveInRepository`
* `grabFromRepository`
* `grabEntitiesFromRepository`
* `seeInRepository`
* `dontSeeInRepository`
### DataFactory
Preparing data for testing is a very creative, although boring, task. If you create a record, you need to fill in all the fields of the model. It is much easier to use [Faker](https://github.com/fzaninotto/Faker) for this task, which is more effective to set up data generation rules for models. Such a set of rules is called *factories* and are provided by the [DataFactory](modules/datafactory) module.
Once configured, it can create records with ease:
```
<?php
// creates a new user
$user_id = $I->have('App\Model\User');
// creates 3 posts
$I->haveMultiple('App\Model\Post', 3);
```
Created records will be deleted at the end of a test. The DataFactory module only works with ORM, so it requires one of the ORM modules to be enabled:
```
modules:
enabled:
- Yii2:
configFile: path/to/config.php
- DataFactory:
depends: Yii2
```
```
modules:
enabled:
- Symfony
- Doctrine2:
depends: Symfony
- DataFactory:
depends: Doctrine2
```
DataFactory provides a powerful solution for managing data in integration/functional/acceptance tests. Read the [full reference](modules/datafactory) to learn how to set this module up.
Testing Dynamic Data with Snapshots
-----------------------------------
What if you deal with data which you don’t own? For instance, the page look depends on number of categories in database, and categories are set by admin user. How would you test that the page is still valid?
There is a way to get it tested as well. Codeception allows you take a snapshot of a data on first run and compare with on next executions. This principle is so general that it can work for testing APIs, items on a web page, etc.
Let’s check that list of categories on a page is the same it was before.
Create a snapshot class:
```
vendor/bin/codecept g:snapshot Categories
```
Inject an actor class via constructor and implement `fetchData` method which should return a data set from a test.
```
<?php
namespace Snapshot;
class Categories extends \Codeception\Snapshot
{
/** @var \AcceptanceTester */
protected $i;
public function __construct(\AcceptanceTester $I)
{
$this->i = $I;
}
protected function fetchData()
{
// fetch texts from all 'a.category' elements on a page
return $this->i->grabMultiple('a.category');
}
}
```
Inside a test you can inject the snapshot class and call `assert` method on it:
```
<?php
public function testCategoriesAreTheSame(\AcceptanceTester $I, \Snapshot\Categories $snapshot)
{
$I->amOnPage('/categories');
// if previously saved array of users does not match current set, test will fail
// to update data in snapshot run test with --debug flag
$snapshot->assert();
}
```
On the first run, data will be obtained via `fetchData` method and saved to `tests/_data` directory in json format. On next execution the obtained data will be compared with previously saved snapshot.
> To update a snapshot with a new data run tests in `--debug` mode.
>
>
By default Snapshot uses `assertEquals` assertion, however this can be customized by overriding `assertData` method.
### Failed assertion output
The assertion performed by `assertData` will not display the typical diff output from `assertEquals` or any customized failed assertion. To have the diff displayed when running tests, you can call the snapshot method `shouldShowDiffOnFail`:
```
<?php
public function testCategoriesAreTheSame(\AcceptanceTester $I, \Snapshot\Categories $snapshot)
{
$I->amOnPage('/categories');
// I want to see the diff in case the snapshot data changes
$snapshot->shouldShowDiffOnFail();
$snapshot->assert();
}
```
If ever needed, the diff output can also be omitted by calling `shouldShowDiffOnFail(false)`.
### Working with different data formats
By default, all snapshot files are stored in json format, so if you have to work with different formats, neither the diff output or the snapshot file data will be helpful. To fix this, you can call the snapshot method `shouldSaveAsJson(false)` and set the file extension by calling `setSnapshotFileExtension()`:
```
<?php
public function testCategoriesAreTheSame(\AcceptanceTester $I, \Snapshot\Categories $snapshot)
{
// I fetch an HTML page
$I->amOnPage('/categories.html');
// I want to see the diff in case the snapshot data changes
$snapshot->shouldSaveAsJson(false);
$snapshot->setSnapshotFileExtension('html');
$snapshot->assert();
}
```
The snapshot file will be stored without encoding it to json format, and with the `.html` extension.
> Beware that this option will not perform any changes in the data returned by `fetchData`, and store it as it is.
>
>
Conclusion
----------
Codeception also assists the developer when dealing with data. Tools for database population and cleaning up are bundled within the `Db` module. If you use ORM, you can use one of the provided framework modules to operate with database through a data abstraction layer, and use the DataFactory module to generate new records with ease.
* **Next Chapter: [APITesting >](10-apitesting)**
* **Previous Chapter: [< Customization](08-customization)**
codeception Advanced Usage Advanced Usage
==============
In this chapter we will cover some techniques and options that you can use to improve your testing experience and keep your project better organized.
Cest Classes
------------
If you want to get a class-like structure for your Cepts, you can use the Cest format instead of plain PHP. It is very simple and is fully compatible with Cept scenarios. It means that if you feel that your test is long enough and you want to split it, you can easily move it into classes.
You can create a Cest file by running the command:
```
php vendor/bin/codecept generate:cest suitename CestName
```
The generated file will look like this:
```
<?php
class BasicCest
{
public function _before(\AcceptanceTester $I)
{
}
public function _after(\AcceptanceTester $I)
{
}
// tests
public function tryToTest(\AcceptanceTester $I)
{
}
}
```
**Each public method of Cest (except those starting with `_`) will be executed as a test** and will receive an instance of the Actor class as the first parameter and the `$scenario` variable as the second one.
In `_before` and `_after` methods you can use common setups and teardowns for the tests in the class.
As you see, we are passing the Actor object into `tryToTest` method. This allows us to write scenarios the way we did before:
```
<?php
class BasicCest
{
// test
public function tryToTest(\AcceptanceTester $I)
{
$I->amOnPage('/');
$I->click('Login');
$I->fillField('username', 'john');
$I->fillField('password', 'coltrane');
$I->click('Enter');
$I->see('Hello, John');
$I->seeInCurrentUrl('/account');
}
}
```
As you see, Cest classes have no parents. This is done intentionally. It allows you to extend your classes with common behaviors and workarounds that may be used in child classes. But don’t forget to make these methods `protected` so they won’t be executed as tests.
Cest format also can contain hooks based on test results:
* `_failed` will be executed on failed test
* `_passed` will be executed on passed test
```
<?php
public function _failed(\AcceptanceTester $I)
{
// will be executed on test failure
}
public function _passed(\AcceptanceTester $I)
{
// will be executed when test is successful
}
```
Dependency Injection
--------------------
Codeception supports simple dependency injection for Cest and \Codeception\TestCase\Test classes. It means that you can specify which classes you need as parameters of the special `_inject()` method, and Codeception will automatically create the respective objects and invoke this method, passing all dependencies as arguments. This may be useful when working with Helpers. Here’s an example for Cest:
```
<?php
class SignUpCest
{
/**
* @var Helper\SignUp
*/
protected $signUp;
/**
* @var Helper\NavBarHelper
*/
protected $navBar;
protected function _inject(\Helper\SignUp $signUp, \Helper\NavBar $navBar)
{
$this->signUp = $signUp;
$this->navBar = $navBar;
}
public function signUp(\AcceptanceTester $I)
{
$this->navBar->click('Sign up');
$this->signUp->register([
'first_name' => 'Joe',
'last_name' => 'Jones',
'email' => '[email protected]',
'password' => '1234',
'password_confirmation' => '1234'
]);
}
}
```
And for Test classes:
```
<?php
class MathTest extends \Codeception\TestCase\Test
{
/**
* @var \UnitTester
*/
protected $tester;
/**
* @var Helper\Math
*/
protected $math;
protected function _inject(\Helper\Math $math)
{
$this->math = $math;
}
public function testAll()
{
$this->assertEquals(3, $this->math->add(1, 2));
$this->assertEquals(1, $this->math->subtract(3, 2));
}
}
```
However, Dependency Injection is not limited to this. It allows you to **inject any class**, which can be constructed with arguments known to Codeception.
In order to make auto-wiring work, you will need to implement the `_inject()` method with the list of desired arguments. It is important to specify the type of arguments, so Codeception can guess which objects are expected to be received. The `_inject()` will only be invoked once, just after creation of the TestCase object (either Cest or Test). Dependency Injection will also work in a similar manner for Helper and Actor classes.
Each test of a Cest class can declare its own dependencies and receive them from method arguments:
```
<?php
class UserCest
{
function updateUser(\Helper\User $u, \AcceptanceTester $I, \Page\User $userPage)
{
$user = $u->createDummyUser();
$userPage->login($user->getName(), $user->getPassword());
$userPage->updateProfile(['name' => 'Bill']);
$I->see('Profile was saved');
$I->see('Profile of Bill','h1');
}
}
```
Moreover, Codeception can resolve dependencies recursively (when `A` depends on `B`, and `B` depends on `C` etc.) and handle parameters of primitive types with default values (like `$param = 'default'`). Of course, you are not allowed to have *cyclic dependencies*.
Example Annotation
------------------
What if you want to execute the same test scenario with different data? In this case you can inject examples as `\Codeception\Example` instances. Data is defined via the `@example` annotation, using JSON or Doctrine-style notation (limited to a single line). Doctrine-style:
```
<?php
class EndpointCest
{
/**
* @example ["/api/", 200]
* @example ["/api/protected", 401]
* @example ["/api/not-found-url", 404]
* @example ["/api/faulty", 500]
*/
public function checkEndpoints(ApiTester $I, \Codeception\Example $example)
{
$I->sendGet($example[0]);
$I->seeResponseCodeIs($example[1]);
}
}
```
JSON:
```
<?php
class PageCest
{
/**
* @example { "url": "/", "title": "Welcome" }
* @example { "url": "/info", "title": "Info" }
* @example { "url": "/about", "title": "About Us" }
* @example { "url": "/contact", "title": "Contact Us" }
*/
public function staticPages(AcceptanceTester $I, \Codeception\Example $example)
{
$I->amOnPage($example['url']);
$I->see($example['title'], 'h1');
$I->seeInTitle($example['title']);
}
}
```
If you use JSON notation please keep in mind that all string keys and values should be enclosed in double quotes (`"`) according to JSON standard. Key-value data in Doctrine-style annotation syntax:
```
<?php
class PageCest
{
/**
* @example(url="/", title="Welcome")
* @example(url="/info", title="Info")
* @example(url="/about", title="About Us")
* @example(url="/contact", title="Contact Us")
*/
public function staticPages(AcceptanceTester $I, \Codeception\Example $example)
{
$I->amOnPage($example['url']);
$I->see($example['title'], 'h1');
$I->seeInTitle($example['title']);
}
}
```
DataProvider Annotations
------------------------
You can also use the `@dataProvider` annotation for creating dynamic examples for [Cest classes](#Cest-Classes), using a **protected method** for providing example data:
```
<?php
class PageCest
{
/**
* @dataProvider pageProvider
*/
public function staticPages(AcceptanceTester $I, \Codeception\Example $example)
{
$I->amOnPage($example['url']);
$I->see($example['title'], 'h1');
$I->seeInTitle($example['title']);
}
/**
* @return array
*/
protected function pageProvider() // alternatively, if you want the function to be public, be sure to prefix it with `_`
{
return [
['url'=>"/", 'title'=>"Welcome"],
['url'=>"/info", 'title'=>"Info"],
['url'=>"/about", 'title'=>"About Us"],
['url'=>"/contact", 'title'=>"Contact Us"]
];
}
}
```
`@dataprovider` annotation is also available for [unit tests](05-unittests), in this case the data provider **method must be public**. For more details about how to use data provider for unit tests, please refer to [PHPUnit documentation](https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers).
Before/After Annotations
------------------------
You can control execution flow with `@before` and `@after` annotations. You may move common actions into protected (non-test) methods and invoke them before or after the test method by putting them into annotations. It is possible to invoke several methods by using more than one `@before` or `@after` annotation. Methods are invoked in order from top to bottom.
```
<?php
class ModeratorCest {
protected function login(AcceptanceTester $I)
{
$I->amOnPage('/login');
$I->fillField('Username', 'miles');
$I->fillField('Password', 'davis');
$I->click('Login');
}
/**
* @before login
*/
public function banUser(AcceptanceTester $I)
{
$I->amOnPage('/users/charlie-parker');
$I->see('Ban', '.button');
$I->click('Ban');
}
/**
* @before login
* @before cleanup
* @after logout
* @after close
*/
public function addUser(AcceptanceTester $I)
{
$I->amOnPage('/users/charlie-parker');
$I->see('Ban', '.button');
$I->click('Ban');
}
}
```
Environments
------------
For cases where you need to run tests with different configurations you can define different config environments. The most typical use cases are running acceptance tests in different browsers, or running database tests using different database engines.
Let’s demonstrate the usage of environments for the browsers case.
We need to add some new lines to `acceptance.suite.yml`:
```
actor: AcceptanceTester
modules:
enabled:
- WebDriver
- \Helper\Acceptance
config:
WebDriver:
url: 'http://127.0.0.1:8000/'
browser: 'firefox'
env:
chrome:
modules:
config:
WebDriver:
browser: 'chrome'
firefox:
# nothing changed
```
Basically you can define different environments inside the `env` root, name them (`chrome`, `firefox` etc.), and then redefine any configuration parameters that were set before.
You can also define environments in separate configuration files placed in the directory specified by the `envs` option in the `paths` configuration:
```
paths:
envs: tests/_envs
```
The names of these files are used as environments names (e.g. `chrome.yml` or `chrome.dist.yml` for an environment named `chrome`). You can generate a new file with this environment configuration by using the `generate:environment` command:
```
$ php vendor/bin/codecept g:env chrome
```
In that file you can specify just the options you wish to override:
```
modules:
config:
WebDriver:
browser: 'chrome'
```
The environment configuration files are merged into the main configuration before the suite configuration is merged.
You can easily switch between those configs by running tests with `--env` option. To run the tests only for Firefox you just need to pass `--env firefox` as an option:
```
$ php vendor/bin/codecept run acceptance --env firefox
```
To run the tests in all browsers, list all the environments:
```
$ php vendor/bin/codecept run acceptance --env chrome --env firefox
```
The tests will be executed 3 times, each time in a different browser.
It’s also possible to merge multiple environments into a single configuration by separating them with a comma:
```
$ php vendor/bin/codecept run acceptance --env dev,firefox --env dev,chrome --env dev,firefox
```
The configuration is merged in the order given. This way you can easily create multiple combinations of your environment configurations.
Depending on the environment, you may choose which tests are to be executed. For example, you might need some tests to be executed in Firefox only, and some tests in Chrome only.
The desired environments can be specified with the `@env` annotation for tests in Test and Cest formats:
```
<?php
class UserCest
{
/**
* This test will be executed only in 'firefox' and 'chrome' environments
*
* @env firefox
* @env chrome
*/
public function webkitOnlyTest(AcceptanceTester $I)
{
// I do something
}
}
```
This way you can easily control which tests will be executed for each environment.
Get Scenario Metadata
---------------------
Sometimes you may need to change the test behavior in real time. For instance, the behavior of the same test may differ in Firefox and in Chrome. In runtime we can retrieve the current environment name, test name, or list of enabled modules by calling the `$scenario->current()` method.
```
<?php
// retrieve current environment
$scenario->current('env');
// list of all enabled modules
$scenario->current('modules');
// test name
$scenario->current('name');
// browser name (if WebDriver module enabled)
$scenario->current('browser');
// capabilities (if WebDriver module enabled)
$scenario->current('capabilities');
```
You can inject `\Codeception\Scenario` like this:
```
<?php
public function myTest(\AcceptanceTester $I, \Codeception\Scenario $scenario)
{
if ($scenario->current('browser') == 'chrome') {
// ...
}
}
```
`Codeception\Scenario` is also available in Actor classes and StepObjects. You can access it with `$this->getScenario()`.
Shuffle
-------
By default Codeception runs tests in alphabetic order. To ensure that tests are not depending on each other (unless explicitly declared via `@depends`) you can enable `shuffle` option.
```
# inside codeception.yml
settings:
shuffle: true
```
Alternatively, you may run tests in shuffle without changing the config:
```
codecept run -o "settings: shuffle: true"
```
Tests will be randomly reordered on each run. When tests executed in shuffle mode a seed value will be printed. Copy this seed value from output to be able to rerun tests in the same order.
```
$ codecept run
Codeception PHP Testing Framework v2.4.5
Powered by PHPUnit 5.7.27 by Sebastian Bergmann and contributors.
[Seed] 1872290562
```
Pass the copied seed into `--seed` option:
```
codecept run --seed 1872290562
```
### Dependencies
With the `@depends` annotation you can specify a test that should be passed before the current one. If that test fails, the current test will be skipped. You should pass the method name of the test you are relying on.
```
<?php
class ModeratorCest {
public function login(AcceptanceTester $I)
{
// logs moderator in
}
/**
* @depends login
*/
public function banUser(AcceptanceTester $I)
{
// bans user
}
}
```
`@depends` applies to the `Cest` and `Codeception\Test\Unit` formats. Dependencies can be set across different classes. To specify a dependent test from another file you should provide a *test signature*. Normally, the test signature matches the `className:methodName` format. But to get the exact test signature just run the test with the `--steps` option to see it:
```
Signature: ModeratorCest:login`
```
Codeception reorders tests so dependent tests will always be executed before the tests that rely on them.
Running from different folders
------------------------------
If you have several projects with Codeception tests, you can use a single `codecept` file to run all of your tests. You can pass the `-c` option to any Codeception command (except `bootstrap`), to execute Codeception in another directory:
```
$ php vendor/bin/codecept run -c ~/projects/ecommerce/
$ php vendor/bin/codecept run -c ~/projects/drupal/
$ php vendor/bin/codecept generate:cest acceptance CreateArticle -c ~/projects/drupal/
```
To create a project in directory different from the current one, just provide its path as a parameter:
```
$ php vendor/bin/codecept bootstrap ~/projects/drupal/
```
Also, the `-c` option allows you to specify another config file to be used. Thus, you can have several `codeception.yml` files for your test suite (e.g. to to specify different environments and settings). Just pass the `.yml` filename as the `-c` parameter to execute tests with specific config settings.
Groups
------
There are several ways to execute a bunch of tests. You can run tests from a specific directory:
```
$ php vendor/bin/codecept run tests/acceptance/admin
```
You can execute one (or several) specific groups of tests:
```
$ php vendor/bin/codecept run -g admin -g editor
```
The concept of groups was taken from PHPUnit and behave in the same way.
For Test and Cest files you can use the `@group` annotation to add a test to a group.
```
<?php
/**
* @group admin
*/
public function testAdminUser()
{
}
```
For `.feature`-files (Gherkin) use tags:
```
@admin @editor
Feature: Admin area
```
### Group Files
Groups can be defined in global or suite configuration files. Tests for groups can be specified as an array of file names or directories containing them:
```
groups:
# add 2 tests to db group
db: [tests/unit/PersistTest.php, tests/unit/DataTest.php]
# add all tests from a directory to api group
api: [tests/functional/api]
```
A list of tests for the group can be passed from a Group file. It should be defined in plain text with test names on separate lines:
```
tests/unit/DbTest.php
tests/unit/UserTest.php:create
tests/unit/UserTest.php:update
```
A group file can be included by its relative filename:
```
groups:
# requiring a group file
slow: tests/_data/slow.txt
```
You can create group files manually or generate them from third party applications. For example, you can write a script that updates the slow group by taking the slowest tests from xml report.
You can even specify patterns for loading multiple group files with a single definition:
```
groups:
p*: tests/_data/p*
```
This will load all found `p*` files in `tests/_data` as groups. Group names will be as follows p1,p2,…,pN.
Formats
-------
In addition to the standard test formats (Cest, Unit, Gherkin) you can implement your own format classes to customise your test execution. Specify these in your suite configuration:
```
formats:
- \My\Namespace\MyFormat
```
Then define a class which implements the LoaderInterface
```
namespace My\Namespace;
class MyFormat implements \Codeception\Test\Loader\LoaderInterface
{
protected $tests;
protected $settings;
public function __construct($settings = [])
{
//These are the suite settings
$this->settings = $settings;
}
public function loadTests($filename)
{
//Load file and create tests
}
public function getTests()
{
return $this->tests;
}
public function getPattern()
{
return '~Myformat\.php$~';
}
}
```
Shell auto-completion
---------------------
For bash and zsh shells, you can use auto-completion for your Codeception projects by executing the following in your shell (or add it to your .bashrc/.zshrc):
```
# BASH ~4.x, ZSH
source <([codecept location] _completion --generate-hook --program codecept --use-vendor-bin)
# BASH ~3.x, ZSH
[codecept location] _completion --generate-hook --program codecept --use-vendor-bin | source /dev/stdin
# BASH (any version)
eval $([codecept location] _completion --generate-hook --program codecept --use-vendor-bin)
```
### Explanation
By using the above code in your shell, Codeception will try to autocomplete the following:
* Commands
* Suites
* Test paths
Usage of `-use-vendor-bin` is optional. This option will work for most Codeception projects, where Codeception is located in your `vendor/bin` folder. But in case you are using a global Codeception installation for example, you wouldn’t use this option.
Note that with the `-use-vendor-bin` option, your commands will be completed using the Codeception binary located in your project’s root. Without the option, it will use whatever Codeception binary you originally used to generate the completion script (‘codecept location’ in the above examples)
Conclusion
----------
Codeception is a framework which may look simple at first glance but it allows you to build powerful tests with a single API, refactor them, and write them faster using the interactive console. Codeception tests can be easily organized in groups or Cest classes.
* **Next Chapter: [BDD >](07-bdd)**
* **Previous Chapter: [< ReusingTestCode](06-reusingtestcode)**
| programming_docs |
codeception Acceptance Testing Acceptance Testing
==================
Acceptance testing can be performed by a non-technical person. That person can be your tester, manager or even client. If you are developing a web-application (and you probably are) the tester needs nothing more than a web browser to check that your site works correctly. You can reproduce an acceptance tester’s actions in scenarios and run them automatically. Codeception keeps tests clean and simple as if they were recorded from the words of an actual acceptance tester.
It makes no difference what (if any) CMS or framework is used on the site. You can even test sites created with different languages, like Java, .NET, etc. It’s always a good idea to add tests to your website. At least you will be sure that site features work after the latest changes were made.
Sample Scenario
---------------
Let’s say the first test you would want to run, would be signing in. In order to write such a test, we still require basic knowledge of PHP and HTML:
```
<?php
$I->amOnPage('/login');
$I->fillField('username', 'davert');
$I->fillField('password', 'qwerty');
$I->click('LOGIN');
$I->see('Welcome, Davert!');
```
**This scenario can be performed either by PhpBrowser or by a “real” browser through WebDriver**.
| | PhpBrowser | WebDriver |
| --- | --- | --- |
| Browser Engine | Guzzle + Symfony BrowserKit | Chrome or Firefox |
| JavaScript | No | Yes |
| `see`/`seeElement` checks if… | …text is present in the HTML source | …text is actually visible to the user |
| Access to HTTP response headers and status codes | Yes | No |
| System requirements | PHP with [ext-curl](https://php.net/manual/book.curl.php) | Chrome or Firefox; optionally with Selenium Standalone Server |
| Speed | Fast | Slow |
We will start writing our first acceptance tests with PhpBrowser.
PhpBrowser
----------
This is the fastest way to run acceptance tests since it doesn’t require running an actual browser. We use a PHP web scraper, which acts like a browser: It sends a request, then receives and parses the response. Codeception uses [Guzzle](http://guzzlephp.org) and [Symfony BrowserKit](https://symfony.com/doc/current/components/browser_kit.html) to interact with HTML web pages.
Common PhpBrowser drawbacks:
* You can only click on links with valid URLs or form submit buttons
* You can’t fill in fields that are not inside a form
We need to specify the `url` parameter in the acceptance suite config:
```
# acceptance.suite.yml
actor: AcceptanceTester
modules:
enabled:
- PhpBrowser:
url: http://www.example.com/
- \Helper\Acceptance
```
We should start by creating a test with the next command:
```
vendor/bin/codecept g:cest acceptance Signin
```
It will be placed into `tests/acceptance` directory.
```
<?php
class SigninCest
{
public function tryToTest(AcceptanceTester $I)
{
}
}
```
The `$I` object is used to write all interactions. The methods of the `$I` object are taken from the [PhpBrowser Module](modules/phpbrowser). We will briefly describe them here:
```
<?php
$I->amOnPage('/login');
```
We will assume that all actions starting with `am` and `have` describe the initial environment. The `amOnPage` action sets the starting point of a test to the `/login` page.
With the `PhpBrowser` you can click the links and fill in the forms. That will probably be the majority of your actions.
#### Click
Emulates a click on valid anchors. The URL referenced in the `href` attribute will be opened. As a parameter, you can specify the link name or a valid CSS or XPath selector.
```
<?php
$I->click('Log in');
// CSS selector applied
$I->click('#login a');
// XPath
$I->click('//a[@id=login]');
// Using context as second argument
$I->click('Login', '.nav');
```
Codeception tries to locate an element by its text, name, CSS or XPath. You can specify the locator type manually by passing an array as a parameter. We call this a **strict locator**. Available strict locator types are:
* id
* name
* css
* xpath
* link
* class
```
<?php
// By specifying locator type
$I->click(['link' => 'Login']);
$I->click(['class' => 'btn']);
```
There is a special class [`Codeception\Util\Locator`](reference/locator) which may help you to generate complex XPath locators. For instance, it can easily allow you to click an element on the last row of a table:
```
$I->click('Edit' , \Codeception\Util\Locator::elementAt('//table/tr', -1));
```
#### Forms
Clicking links is probably not what takes the most time during the testing of a website. The most routine waste of time goes into the testing of forms. Codeception provides several ways of testing forms.
Let’s submit this sample form inside the Codeception test:
```
<form method="post" action="/update" id="update_form">
<label for="user_name">Name</label>
<input type="text" name="user[name]" id="user_name" />
<label for="user_email">Email</label>
<input type="text" name="user[email]" id="user_email" />
<label for="user_gender">Gender</label>
<select id="user_gender" name="user[gender]">
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<input type="submit" name="submitButton" value="Update" />
</form>
```
From a user’s perspective, a form consists of fields which should be filled in, and then a submit button clicked:
```
<?php
// we are using label to match user_name field
$I->fillField('Name', 'Miles');
// we can use input name or id
$I->fillField('user[email]','[email protected]');
$I->selectOption('Gender','Male');
$I->click('Update');
```
To match fields by their labels, you should write a `for` attribute in the `label` tag.
From the developer’s perspective, submitting a form is just sending a valid POST request to the server. Sometimes it’s easier to fill in all of the fields at once and send the form without clicking a ‘Submit’ button. A similar scenario can be rewritten with only one command:
```
<?php
$I->submitForm('#update_form', array('user' => array(
'name' => 'Miles',
'email' => 'Davis',
'gender' => 'm'
)));
```
The `submitForm` is not emulating a user’s actions, but it’s quite useful in situations when the form is not formatted properly, for example, to discover that labels aren’t set or that fields have unclean names or badly written IDs, or the form is sent by a JavaScript call.
By default, `submitForm` doesn’t send values for buttons. The last parameter allows specifying what button values should be sent, or button values can be explicitly specified in the second parameter:
```
<?php
$I->submitForm('#update_form', array('user' => array(
'name' => 'Miles',
'email' => 'Davis',
'gender' => 'm'
)), 'submitButton');
// this would have the same effect, but the value has to be explicitly specified
$I->submitForm('#update_form', array('user' => array(
'name' => 'Miles',
'email' => 'Davis',
'gender' => 'm',
'submitButton' => 'Update'
)));
```
##### Hiding Sensitive Data
If you need to fill in sensitive data (like passwords) and hide it in logs, you can pass instance `\Codeception\Step\Argument\PasswordArgument` with the data which needs to be hidden.
```
<?php
use \Codeception\Step\Argument\PasswordArgument;
$I->amOnPage('/form/password_argument');
$I->fillField('password', new PasswordArgument('thisissecret'));
```
`thisissecret` will be filled into a form but it won’t be shown in output and logs.
#### Assertions
In the `PhpBrowser` you can test the page contents. In most cases, you just need to check that the required text or element is on the page.
The most useful method for this is `see()`:
```
<?php
// We check that 'Thank you, Miles' is on the page.
$I->see('Thank you, Miles');
// We check that 'Thank you, Miles' is inside an element with 'notice' class.
$I->see('Thank you, Miles', '.notice');
// Or using XPath locators
$I->see('Thank you, Miles', "//table/tr[2]");
// We check this message is *not* on the page.
$I->dontSee('Form is filled incorrectly');
```
You can check that a specific HTML element exists (or doesn’t) on a page:
```
<?php
$I->seeElement('.notice');
$I->dontSeeElement('.error');
```
We also have other useful commands to perform checks. Please note that they all start with the `see` prefix:
```
<?php
$I->seeInCurrentUrl('/user/miles');
$I->seeCheckboxIsChecked('#agree');
$I->seeInField('user[name]', 'Miles');
$I->seeLink('Login');
```
#### Conditional Assertions
Usually, as soon as any assertion fails, further assertions of this test will be skipped. Sometimes you don’t want this - maybe you have a long-running test and you want it to run to the end. In this case, you can use conditional assertions. Each `see` method has a corresponding `canSee` method, and `dontSee` has a `cantSee` method:
```
<?php
$I->canSeeInCurrentUrl('/user/miles');
$I->canSeeCheckboxIsChecked('#agree');
$I->cantSeeInField('user[name]', 'Miles');
```
Each failed assertion will be shown in the test results, but it won’t stop the test.
Conditional assertions are disabled in bootstrap setup. To enable them you should add corresponding step decorators to suite config:
> If you started project as `codecept init acceptance` they should be already enabled in config
>
>
```
# in acceptance.suite.yml
# or in codeception.yml inside suites section
step_decorators:
- \Codeception\Step\ConditionalAssertion
```
Then rebuild actors with `codecept build` command.
#### Comments
Within a long scenario, you should describe what actions you are going to perform and what results should be achieved. Comment methods like `amGoingTo`, `expect`, `expectTo` help you in making tests more descriptive:
```
<?php
$I->amGoingTo('submit user form with invalid values');
$I->fillField('user[email]', 'miles');
$I->click('Update');
$I->expect('the form is not submitted');
$I->see('Form is filled incorrectly');
```
#### Grabbers
These commands retrieve data that can be used in the test. Imagine your site generates a password for every user and you want to check that the user can log into the site using this password:
```
<?php
$I->fillField('email', '[email protected]');
$I->click('Generate Password');
$password = $I->grabTextFrom('#password');
$I->click('Login');
$I->fillField('email', '[email protected]');
$I->fillField('password', $password);
$I->click('Log in!');
```
Grabbers allow you to get a single value from the current page with commands:
```
<?php
$token = $I->grabTextFrom('.token');
$password = $I->grabTextFrom("descendant::input/descendant::*[@id = 'password']");
$api_key = $I->grabValueFrom('input[name=api]');
```
#### Cookies, URLs, Title, etc
Actions for cookies:
```
<?php
$I->setCookie('auth', '123345');
$I->grabCookie('auth');
$I->seeCookie('auth');
```
Actions for checking the page title:
```
<?php
$I->seeInTitle('Login');
$I->dontSeeInTitle('Register');
```
Actions for URLs:
```
<?php
$I->seeCurrentUrlEquals('/login');
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
$I->seeInCurrentUrl('user/1');
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
```
WebDriver
---------
A nice feature of Codeception is that most scenarios are similar, no matter of how they are executed. `PhpBrowser` was emulating browser requests but how to execute such test in a real browser like Chrome or Firefox? Selenium WebDriver can drive them so in our acceptance tests we can automate scenarios we used to test manually. In such tests, we should concentrate more on **testing the UI** than on testing functionality.
“[WebDriver](https://www.w3.org/TR/webdriver/)” is the name of a protocol (specified by W3C) to drive browsers automatically. This specification is implemented for all modern desktop and mobile browsers. Codeception uses [php-webdriver/php-webdriver](https://github.com/php-webdriver/php-webdriver) as a PHP implementation of the WebDriver protocol.
To control the browsers you need to use a program or a service to start/stop browser sessions. In the next section, we will overview the most popular solutions.
### Local Setup
### Selenium Server
[Selenium](https://www.selenium.dev) is required to launch and control browsers from Codeception. Selenium Server is required to be installed and started before running tests.
The fastest way of getting Selenium is using [selenium-standalone](https://www.npmjs.com/package/selenium-standalone) NodeJS Package. It automatically installs Selenium and all required dependencies and starts server. It requires **NodeJS and Java** to be installed.
`npm install selenium-standalone -g
selenium-standalone install` Launch this command in a separate terminal:
`selenium-standalone start` 
Now, you are ready to run WebDriver tests using Codeception.
> Alternatively, Selenium Server can be installed manually. [Download it](https://www.selenium.dev/downloads/) from the official site and launch a server with Java: `java -jar selenium-server-....jar`. In this case ChromeDriver and GeckoDriver must be installed separately.
>
>
* For more information refer to [Installation Instructions](modules/webdriver#Selenium)
* Enable [RunProcess](https://codeception.com/extensions#RunProcess) extension to start/stop Selenium automatically *(optional)*.
### Configuration
To execute a test in a browser you need to change the suite configuration to use **WebDriver** module.
Modify your `acceptance.suite.yml` file:
```
actor: AcceptanceTester
modules:
enabled:
- WebDriver:
url:
browser: chrome
- \Helper\Acceptance
```
See [WebDriver Module](modules/webdriver) for details.
Please note that actions executed in a browser will behave differently. For instance, `seeElement` won’t just check that the element exists on a page, but it will also check that element is actually visible to the user:
```
<?php
$I->seeElement('#modal');
```
While WebDriver duplicates the functionality of PhpBrowser, it has its limitations: It can’t check headers since browsers don’t provide APIs for that. WebDriver also adds browser-specific functionality:
#### Wait
While testing web application, you may need to wait for JavaScript events to occur. Due to its asynchronous nature, complex JavaScript interactions are hard to test. That’s why you may need to use waiters, actions with `wait` prefix. They can be used to specify what event you expect to occur on a page, before continuing the test.
For example:
```
<?php
$I->waitForElement('#agree_button', 30); // secs
$I->click('#agree_button');
```
In this case, we are waiting for the ‘agree’ button to appear and then click it. If it didn’t appear after 30 seconds, the test will fail. There are other `wait` methods you may use, like [waitForText](modules/webdriver#waitForText), [waitForElementVisible](modules/webdriver#waitForElementVisible) and others.
If you don’t know what exact element you need to wait for, you can simply pause execution with using `$I->wait()`
```
<?php
$I->wait(3); // wait for 3 secs
```
#### SmartWait
It is possible to wait for elements pragmatically. If a test uses element which is not on a page yet, Codeception will wait for few extra seconds before failing. This feature is based on [Implicit Wait](http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp#implicit-waits) of Selenium. Codeception enables implicit wait only when searching for a specific element and disables in all other cases. Thus, the performance of a test is not affected.
SmartWait can be enabled by setting `wait` option in WebDriver config. It expects the number of seconds to wait. Example:
```
wait: 5
```
With this config we have the following test:
```
<?php
// we use wait: 5 instead of
// $I->waitForElement(['css' => '#click-me'], 5);
// to wait for element on page
$I->click(['css' => '#click-me']);
```
It is important to understand that SmartWait works only with a specific locators:
* `#locator` - CSS ID locator, works
* `//locator` - general XPath locator, works
* `['css' => 'button'']` - strict locator, works
But it won’t be executed for all other locator types. See the example:
```
<?php
$I->click('Login'); // DISABLED, not a specific locator
$I->fillField('user', 'davert'); // DISABLED, not a specific locator
$I->fillField(['name' => 'password'], '123456'); // ENABLED, strict locator
$I->click('#login'); // ENABLED, locator is CSS ID
$I->see('Hello, Davert'); // DISABLED, Not a locator
$I->seeElement('#userbar'); // ENABLED
$I->dontSeeElement('#login'); // DISABLED, can't wait for element to hide
$I->seeNumberOfElements(['css' => 'button.link'], 5); // DISABLED, can wait only for one element
```
#### Retry
When it’s hard to define condition to wait for, we can retry a command few times until it succeeds. For instance, if you try to click while it’s animating you can try to do it few times until it freezes. Since Codeception 3.0 each action and assertion have an alias prefixed with `retry` which allows to retry a flaky command.
```
<?php
$I->retryClick('flaky element');
$I->retrySee('Something changed');
```
Retry can be configured via `$I->retry()` command, where you can set number of retries and initial interval: interval will be doubled on each unsuccessful execution.
```
<?php
// Retry up to 6 sec: 4 times, for 400ms initial interval => 400ms + 800ms + 1600ms + 3200ms = 6000ms
$I->retry(4, 400);
```
`$I->retry` takes 2 parameters:
* number of retries (1 by default)
* initial interval (200ms by default)
Retries are disabled by default. To enable them you should add retry step decorators to suite config:
> If you started project as `codecept init acceptance` they should be already enabled in config
>
>
```
# in acceptance.suite.yml
# or in codeception.yml inside suites section
step_decorators:
- \Codeception\Step\Retry
```
Then add `\Codeception\Lib\Actor\Shared\Retry` trait into `AcceptanceTester` class:
```
<?php
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
use \Codeception\Lib\Actor\Shared\Retry;
}
```
Run `codecept build` to recreate actions. New `retry*` actions are available for tests. Keep in mind, that you can change retry policy dynamically for each test.
#### Wait and Act
To combine `waitForElement` with actions inside that element you can use the [performOn](modules/webdriver#performOn) method. Let’s see how you can perform some actions inside an HTML popup:
```
<?php
$I->performOn('.confirm', \Codeception\Util\ActionSequence::build()
->see('Warning')
->see('Are you sure you want to delete this?')
->click('Yes')
);
```
Alternatively, this can be executed using a callback, in this case the `WebDriver` instance is passed as argument
```
<?php
$I->performOn('.confirm', function(\Codeception\Module\WebDriver $I) {
$I->see('Warning');
$I->see('Are you sure you want to delete this?');
$I->click('Yes');
});
```
For more options see [`performOn()` reference](modules/webdriver#performOn).
#### A/B Testing
When a web site acts unpredictably you may need to react on that change. This happens if site configured for A/B testing, or shows different popups, based on environment.
Since Codeception 3.0 you can have some actions to fail silently, if they are errored. Let’s say, you open a page and some times there is a popup which should be closed. We may try to hit the “close” button but if this action fails (no popup on page) we just continue the test.
This is how it can be implemented:
```
<?php
$I->amOnPage('/');
$I->tryToClick('x', '.alert');
// continue execution
```
You can also use `tryTo` as condition for your tests:
```
<?php
if ($I->tryToSeeElement('.alert')) {
$I->waitForText('Do you accept cookies?');
$I->click('Yes');
}
```
A/B testing is disabled by default. To enable it you should add corresponding step decorators to suite config:
> If you started project as `codecept init acceptance` in Codeception >= 3.0 they should be already enabled in config
>
>
```
# in acceptance.suite.yml
# or in codeception.yml inside suites section
step_decorators:
- \Codeception\Step\TryTo
```
Then rebuild actors with `codecept build` command.
### Multi Session Testing
Codeception allows you to execute actions in concurrent sessions. The most obvious case for this is testing realtime messaging between users on a site. In order to do it, you will need to launch two browser windows at the same time for the same test. Codeception has a very smart concept for doing this. It is called **Friends**:
```
<?php
$I->amOnPage('/messages');
$nick = $I->haveFriend('nick');
$nick->does(function(AcceptanceTester $I) {
$I->amOnPage('/messages/new');
$I->fillField('body', 'Hello all!');
$I->click('Send');
$I->see('Hello all!', '.message');
});
$I->wait(3);
$I->see('Hello all!', '.message');
```
In this case, we performed, or ‘did’, some actions in the second window with the `does` method on a friend object.
Sometimes you may want to close a webpage before the end of the test. For such cases, you may use `leave()`. You can also specify roles for a friend:
```
<?php
$nickAdmin = $I->haveFriend('nickAdmin', adminStep::class);
$nickAdmin->does(function(adminStep $I) {
// Admin does ...
});
$nickAdmin->leave();
```
Multi session testing is disabled by default. To enable it, add `\Codeception\Lib\Actor\Shared\Friend` into `AcceptanceTester`.
```
<?php
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
use \Codeception\Lib\Actor\Shared\Friend;
}
```
### Cloud Testing
Some environments are hard to be reproduced manually, testing Internet Explorer 6-8 on Windows XP may be a hard thing, especially if you don’t have Windows XP installed. This is where Cloud Testing services come to help you. Services such as [SauceLabs](https://saucelabs.com), [BrowserStack](https://www.browserstack.com/) and [others](modules/webdriver#Cloud-Testing) can create virtual machines on demand and set up Selenium Server and the desired browser. Tests are executed on a remote machine in a cloud, to access local files cloud testing services provide a special application called **Tunnel**. Tunnel operates on a secured protocol and allows browsers executed in a cloud to connect to a local web server.
Cloud Testing services work with the standard WebDriver protocol. This makes setting up cloud testing really easy. You just need to set the [WebDriver configuration](modules/webdriver#Cloud-Testing) to:
* specify the host to connect to (depends on the cloud provider)
* authentication details (to use your account)
* browser
* OS
We recommend using [params](06-modulesandhelpers#Dynamic-Configuration-With-Params) to provide authorization credentials.
It should be mentioned that Cloud Testing services are not free. You should investigate their pricing models and choose one that fits your needs. They also may work painfully slowly if ping times between the local server and the cloud is too high. This may lead to random failures in acceptance tests.
### Debugging
Codeception modules can print valuable information while running. Just execute tests with the `--debug` option to see running details. For any custom output use the `codecept_debug` function:
```
<?php
codecept_debug($I->grabTextFrom('#name'));
```
On each failure, the snapshot of the last shown page will be stored in the `tests/_output` directory. PhpBrowser will store the HTML code and WebDriver will save a screenshot of the page.
Additional debugging features by Codeception:
* [Interactive Pause](02-gettingstarted#Interactive-Pause) is a REPL that allows to type and check commands for instant feedback.
* [Recorder Extension](https://codeception.com/addons#CodeceptionExtensionRecorder) allows to record tests step-by-steps and show them in slideshow
### Common Cases
Let’s see how common problems of acceptance testing can be solved with Codeception.
#### Login
It is recommended to put widely used actions inside an Actor class. A good example is the `login` action which would probably be actively involved in acceptance or functional testing:
```
<?php
class AcceptanceTester extends \Codeception\Actor
{
// do not ever remove this line!
use _generated\AcceptanceTesterActions;
public function login($name, $password)
{
$I = $this;
$I->amOnPage('/login');
$I->submitForm('#loginForm', [
'login' => $name,
'password' => $password
]);
$I->see($name, '.navbar');
}
}
```
Now you can use the `login` method inside your tests:
```
<?php
// $I is AcceptanceTester
$I->login('miles', '123456');
```
However, implementing all actions for reuse in a single actor class may lead to breaking the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle).
#### Single Login
If you need to authorize a user for each test, you can do so by submitting the login form at the beginning of every test. Running those steps takes time, and in the case of Selenium tests (which are slow by themselves) that time loss can become significant.
Codeception allows you to share cookies between tests, so a test user can stay logged in for other tests.
Let’s improve the code of our `login` method, executing the form submission only once and restoring the session from cookies for each subsequent login function call:
```
<?php
public function login($name, $password)
{
$I = $this;
// if snapshot exists - skipping login
if ($I->loadSessionSnapshot('login')) {
return;
}
// logging in
$I->amOnPage('/login');
$I->submitForm('#loginForm', [
'login' => $name,
'password' => $password
]);
$I->see($name, '.navbar');
// saving snapshot
$I->saveSessionSnapshot('login');
}
```
Note that session restoration only works for `WebDriver` modules (modules implementing `Codeception\Lib\Interfaces\SessionSnapshot`).
### Custom Browser Sessions
By default, WebDriver module is configured to automatically start browser before the test and stop afterward. However, this can be switched off with `start: false` module configuration. To start a browser you will need to write corresponding methods in Acceptance [Helper](06-modulesandhelpers#Helpers).
WebDriver module provides advanced methods for the browser session, however, they can only be used from Helpers.
* [\_initializeSession](modules/webdriver#_initializeSession) - starts a new browser session
* [\_closeSession](modules/webdriver#_closeSession) - stops the browser session
* [\_restart](modules/webdriver#_restart) - updates configuration and restarts browser
* [\_capabilities](modules/webdriver#_capabilities) - set [desired capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities) programmatically.
Those methods can be used to create custom commands like `$I->startBrowser()` or used in [before/after](06-modulesandhelpers#Hooks) hooks.
Error Reporting
---------------
By default Codeception uses the `E_ALL & ~E_STRICT & ~E_DEPRECATED` error reporting level. In acceptance tests you might want to change this level depending on your framework’s error policy. The error reporting level can be set in the suite configuration file:
```
actor: AcceptanceTester
...
error_level: E_ALL & ~E_STRICT & ~E_DEPRECATED
```
`error_level` can also be set globally in `codeception.yml` file. In order to do that, you need to specify `error_level` as a part of `settings`. For more information, see [Global Configuration](reference/configuration). Note that suite specific `error_level` value will override global value.
Conclusion
----------
Writing acceptance tests with Codeception and PhpBrowser is a good start. You can easily test your Joomla, Drupal, WordPress sites, as well as those made with frameworks. Writing acceptance tests is like describing a tester’s actions in PHP. They are quite readable and very easy to write. If you need to access the database, you can use the [Db Module](modules/db).
* **Next Chapter: [FunctionalTests >](04-functionaltests)**
* **Previous Chapter: [< GettingStarted](02-gettingstarted)**
| programming_docs |
codeception Behavior Driven Development Behavior Driven Development
===========================
Behavior Driven Development (BDD) is a popular software development methodology. BDD is considered an extension of TDD, and is greatly inspired by [Agile](http://agilemanifesto.org/) practices. The primary reason to choose BDD as your development process is to break down communication barriers between business and technical teams. BDD encourages the use of automated testing to verify all documented features of a project from the very beginning. This is why it is common to talk about BDD in the context of test frameworks (like Codeception). The BDD approach, however, is about much more than testing - it is a common language for all team members to use during the development process.
What is Behavior Driven Development
-----------------------------------
BDD was introduced by [Dan North](https://dannorth.net/introducing-bdd/). He described it as:
> outside-in, pull-based, multiple-stakeholder, multiple-scale, high-automation, agile methodology. It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters.
>
>
BDD has its own evolution from the days it was born, started by replacing “test” to “should” in unit tests, and moving towards powerful tools like Cucumber and Behat, which made user stories (human readable text) to be executed as an acceptance test.
The idea of story BDD can be narrowed to:
* describe features in a scenario with a formal text
* use examples to make abstract things concrete
* implement each step of a scenario for testing
* write actual code implementing the feature
By writing every feature in User Story format that is automatically executable as a test we ensure that: business, developers, QAs and managers are in the same boat.
BDD encourages exploration and debate in order to formalize the requirements and the features that needs to be implemented by requesting to write the User Stories in a way that everyone can understand.
By making tests to be a part of User Story, BDD allows non-technical personnel to write (or edit) Acceptance tests.
With this procedure we also ensure that everyone in a team knows what has been developed, what has not, what has been tested and what has not.
### Ubiquitous Language
The ubiquitous language is always referred as *common* language. That is it’s main benefit. It is not a couple of our business specification’s words, and not a couple of developer’s technical terms. It is a common words and terms that can be understood by people for whom we are building the software and should be understood by developers. Establishing correct communication between this two groups people is vital for building successful project that will fit the domain and fulfill all business needs.
Each feature of a product should be born from a talk between
* business (analysts, product owner)
* developers
* QAs
which are known in BDD as “three amigos”.
Such talks should produce written stories. There should be an actor that doing some things, the feature that should be fulfilled within the story and the result achieved.
We can try to write such simple story:
```
As a customer I want to buy several products
I put first product with $600 price to my cart
And then another one with $1000 price
When I go to checkout process
I should see that total number of products I want to buy is 2
And my order amount is $1600
```
As we can see this simple story highlights core concepts that are called *contracts*. We should fulfill those contracts to model software correctly. But how we can verify that those contracts are being satisfied? [Cucumber](https://cucumber.io) introduced a special language for such stories called **Gherkin**. Same story transformed to Gherkin will look like this:
```
Feature: checkout process
In order to buy products
As a customer
I want to be able to buy several products
Scenario:
Given I have product with $600 price in my cart
And I have product with $1000 price
When I go to checkout process
Then I should see that total number of products is 2
And my order amount is $1600
```
Cucumber, Behat, and sure, **Codeception** can execute this scenario step by step as an automated test. Every step in this scenario requires a code which defines it.
Gherkin
-------
Let’s learn some more about Gherkin format and then we will see how to execute it with Codeception:
### Features
Whenever you start writing a story you are describing a specific feature of an application, with a set of scenarios and examples describing this feature.
Feature file is written in Gherkin format. Codeception can generate a feature file for you. We will assume that we will use scenarios in feature files for acceptance tests, so feature files to be placed in `acceptance` suite directory:
```
php vendor/bin/codecept g:feature acceptance checkout
```
Generated template will look like this:
```
Feature: checkout
In order to ...
As a ...
I need to ...
Scenario: try checkout
```
This template can be fulfilled by setting actor and goals:
```
Feature: checkout
In order to buy product
As a customer
I need to be able to checkout the selected products
```
Next, we will describe this feature by writing examples for it
#### Scenarios
Scenarios are live examples of feature usage. Inside a feature file it should be written inside a *Feature* block. Each scenario should contain its title:
```
Feature: checkout
In order to buy product
As a customer
I need to be able to checkout the selected products
Scenario: order several products
```
Scenarios are written in step-by-step manner using Given-When-Then approach. At start, scenario should describe its context with **Given** keyword:
```
Given I have product with $600 price in my cart
And I have product with $1000 price in my cart
```
Here we also use word **And** to extend the Given and not to repeat it in each line.
This is how we described the initial conditions. Next, we perform some action. We use **When** keyword for it:
```
When I go to checkout process
```
And in the end we are verifying our expectation using **Then** keyword. The action changed the initial given state, and produced some results. Let’s check that those results are what we actually expect.
```
Then I should see that total number of products is 2
And my order amount is $1600
```
We can test this scenario by executing it in dry-run mode. In this mode test won’t be executed (actually, we didn’t define any step for it, so it won’t be executed in any case).
```
$ codecept dry-run acceptance checkout.feature
```
```
checkout: order several products
Signature: checkout:order several products
Test: tests/acceptance/checkout.feature:order several products
Scenario --
In order to buy product
As a customer
I need to be able to checkout the selected products
Given i have product with $600 price in my cart
And i have product with $1000 price in my cart
When i go to checkout process
Then i should see that total number of products is 2
And my order amount is $1600
INCOMPLETE
Step definition for `I have product with $600 price in my cart` not found in contexts
Step definition for `I have product with $1000 price` not found in contexts
Step definition for `I go to checkout process` not found in contexts
Step definition for `I should see that total number of products is 2` not found in contexts
Step definition for `my order amount is $1600` not found in contexts
Run gherkin:snippets to define missing steps
```
Besides the scenario steps listed we got the notification that our steps are not defined yet. We can define them easily by executing `gherkin:snippets` command for the given suite:
```
codecept gherkin:snippets acceptance
```
This will produce code templates for all undefined steps in all feature files of this suite. Our next step will be to define those steps and transforming feature-file into valid test.
### Step Definitions
To match steps from a feature file to PHP code we use annotation which are added to class methods. By default Codeception expects that all methods marked with `@Given`, `@When`, `@Then` annotation. Each annotation should contain a step string.
```
/** @Given I am logged as admin */
```
Steps can also be matched with regex expressions. This way we can make more flexible steps
```
/** @Given /I am (logged|authorized) as admin/ */
```
Please note that regular expressions should start and end with `/` char. Regex is also used to match parameters and pass them as arguments into methods.
```
<?php
/**
* @Given /I am (?:logged|authorized) as "(\w+)"/
*/
function amAuthorized($role)
{
// logged or authorized does not matter to us
// so we added ?: for this capture group
}
```
Parameters can be also passed in non-regex strings using “:” params placeholder.
```
/** @Given I am logged in as :role */
```
This will match any word (passed in double quotes) or a number passed:
```
Given I am logged in as "admin"
Given I am logged in as 1
```
Steps are defined in Context files. Default context is an actor class, i.e. for acceptance testing suite default context is `AcceptanceTester` class. However, you can define steps in any classes and include them as contexts. It is useful to define steps in StepObject and PageObject classes.
To list all defined steps run `gherkin:steps` command:
```
codecept gherkin:steps
```
Testing Behavior
----------------
As it was mentioned, feature files is not just a user story. By writing features in formal language called Gherkin we can execute those scenarios as automated tests. There is no restrictions in the way how those scenarios are supposed to be tested. Tests can be executed at functional, acceptance, or domain level. However, we will concentrate on acceptance or UI tests in current guide.
### Acceptance Testing
As we generated snippets for missing steps with `gherkin:snippets` command, we will define them in `AcceptanceTester` file.
```
<?php
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
/**
* @Given I have product with :num1 price in my cart
*/
public function iHaveProductWithPriceInMyCart($num1)
{
throw new \PHPUnit\Framework\IncompleteTestError("Step `I have product with :num1 price in my cart` is not defined");
}
/**
* @When I go to checkout process
*/
public function iGoToCheckoutProcess()
{
throw new \PHPUnit\Framework\IncompleteTestError("Step `I go to checkout process` is not defined");
}
/**
* @Then I should see that total number of products is :num1
*/
public function iShouldSeeThatTotalNumberOfProductsIs($num1)
{
throw new \PHPUnit\Framework\IncompleteTestError("Step `I should see that total number of products is :num1` is not defined");
}
/**
* @Then my order amount is :num1
*/
public function myOrderAmountIs($num1)
{
throw new \PHPUnit\Framework\IncompleteTestError("Step `my order amount is :num1` is not defined");
}
}
```
Please note that `:num1` placeholder can be used for strings and numbers (may contain currency sign). In current case `:num1` matches `$600` and `$num1` is assigned to be 600. If you need to receive exact string, wrap the value into quotes: `"600$"`
By default they throw Incomplete exceptions to ensure test with missing steps won’t be accidentally marked as successful. We will need to implement those steps. As we are in acceptance suite we are probably using [PHPBrowser](modules/phpbrowser) or [WebDriver](modules/webdriver) modules. This means that we can use their methods inside Tester file, as we do with writing tests using `$I->`. You can use `amOnPage`, `click`, `see` methods inside a step definitions, so each Gherkin scenario step to be extended with basic Codeception steps. Let’s show how it can be implemented in our case:
```
<?php
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
/**
* @Given I have product with :num1 price in my cart
*/
public function iHaveProductWithPriceInMyCart($num1)
{
// haveRecord method is available in Laravel, Phalcon, Yii modules
$productId = $this->haveRecord('Product', ['name' => 'randomProduct'.uniqid(), 'price' => $num1]);
$this->amOnPage("/item/$productId");
$this->click('Order');
}
/**
* @When I go to checkout process
*/
public function iGoToCheckoutProcess()
{
$this->amOnPage('/checkout');
}
/**
* @Then I should see that total number of products is :num1
*/
public function iShouldSeeThatTotalNumberOfProductsIs($num1)
{
$this->see($num1, '.products-count');
}
/**
* @Then my order amount is :num1
*/
public function myOrderAmountIs($num1)
{
$this->see($num1, '.total');
}
}
```
To make testing more effective we assumed that we are using one of the ActiveRecord frameworks like Laravel, Yii, or Phalcon so we are able to dynamically create records in database with `haveRecord` method. After that we are opening browser and testing our web pages to see that after selecting those products we really see the price was calculated correctly.
We can dry-run (or run) our feature file to see that Given/When/Then are expanded with substeps:
```
Given i have product with $600 price in my cart
I have record 'Product',{"name":"randomProduct571fad4f88a04","price":"600"}
I am on page "/item/1"
I click "Order"
And i have product with $1000 price in my cart
I have record 'Product',{"name":"randomProduct571fad4f88b14","price":"1000"}
I am on page "/item/2"
I click "Order"
When i go to checkout process
I am on page "/checkout"
Then i should see that total number of products is 2
I see "2",".products-count"
And my order amount is $1600
I see "1600",".total"
```
This way feature file runs just the same as any other Codeception test. Substeps give us detailed information of how the scenario is being executed.
One of the criticism for testing with Gherkin was that only technical team were aware of how the test scenario is executed. This could have lead to false-positive tests. Developers could have used empty steps for scenarios (or irrelevant ones) and produced invalid tests for valid scenarios. Codeception brings communication to a next level, everyone in a team can understand what happens on a lower (technical) level. Scenario expanding to substeps shows the actual test execution process. Anyone in a team can read the output, and invest their efforts into improving the test suite.
Advanced Gherkin
----------------
Let’s improve our BDD suite by using the advanced features of Gherkin language.
### Background
If a group of scenarios have the same initial steps, let’s that for dashboard we always need to be logged in as administrator. We can use *Background* section to do the required preparations and not to repeat same steps across scenarios.
```
Feature: Dashboard
In order to view current state of business
As an owner
I need to be able to see reports on dashboard
Background:
Given I am logged in as administrator
And I open dashboard page
```
Steps in background are defined the same way as in scenarios.
### Tables
Scenarios can become more descriptive when you represent repeating data as tables. Instead of writing several steps “I have product with :num1 $ price in my cart” we can have one step with multiple values in it.
```
Given i have products in my cart
| name | category | price |
| Harry Potter | Books | 5 |
| iPhone 5 | Smartphones | 1200 |
| Nuclear Bomb | Weapons | 100000 |
```
Tables is a recommended ways to pass arrays into test scenarios. Inside a step definition data is stored in argument passed as `\Behat\Gherkin\Node\TableNode` instance.
```
<?php
/**
* @Given i have products in my cart
*/
public function iHaveProductsInCart(\Behat\Gherkin\Node\TableNode $products)
{
// iterate over all rows
foreach ($node->getRows() as $index => $row) {
if ($index === 0) { // first row to define fields
$keys = $row;
continue;
}
$this->haveRecord('Product', array_combine($keys, $row));
}
}
```
### Examples
In case scenarios represent the same logic but differ on data, we can use *Scenario Outline* to provide different examples for the same behavior. Scenario outline is just like a basic scenario with some values replaced with placeholders, which are filled from a table. Each set of values is executed as a different test.
```
Scenario Outline: order discount
Given I have product with price <price>$ in my cart
And discount for orders greater than $20 is 10 %
When I go to checkout
Then I should see overall price is "<total>" $
Examples:
| price | total |
| 10 | 10 |
| 20 | 20 |
| 21 | 18.9 |
| 30 | 27 |
| 50 | 45 |
```
### Long Strings
Text values inside a scenarios can be set inside a `"""` block:
```
Then i see in file "codeception.yml"
"""
paths:
tests: tests
log: tests/_output
data: tests/_data
helpers: tests/_support
envs: tests/_envs
"""
```
This string is passed as a standard PHP string parameter
```
<?php
/**
* @Then i see in file :filename
*/
public function seeInFile($fileName, $fileContents)
{
// note: module "Asserts" is enabled in this suite
if (!file_exists($fileName)) {
$this->fail("File $fileName not found");
}
$this->assertEquals(file_get_contents($fileName), $fileContents);
}
```
### Tags
Gherkin scenarios and features can contain tags marked with `@`. Tags are equal to groups in Codeception. This way if you define a feature with `@important` tag, you can execute it inside `important` group by running:
```
codecept run -g important
```
Tag should be placed before *Scenario:* or before *Feature:* keyword. In the last case all scenarios of that feature will be added to corresponding group.
Configuration
-------------
As we mentioned earlier, steps should be defined inside context classes. By default all the steps are defined inside an Actor class, for instance, `AcceptanceTester`. However, you can include more contexts. This can be configured inside global `codeception.yml` or suite configuration file:
```
gherkin:
contexts:
default:
- AcceptanceTester
- AdditionalSteps
```
`AdditionalSteps` file should be accessible by autoloader and can be created by `Codeception\Lib\Di`. This means that practically any class can be a context. If a class receives an actor class in constructor or in `_inject` method, DI can inject it into it.
```
<?php
class AdditionalSteps
{
protected $I;
function __construct(AcceptanceTester $I)
{
$this->I = $I;
}
/**
* @When I do something
*/
function additionalActions()
{
}
}
```
This way PageObjects, Helpers and StepObjects can become contexts as well. But more preferable to include context classes by their tags or roles.
If you have `Step\Admin` class which defines only admin steps, it is a good idea to use it as context for all features containing with “As an admin”. In this case “admin” is a role and we can configure it to use additional context.
```
gherkin:
contexts:
role:
admin:
- "Step\Admin"
```
Contexts can be attached to tags as well. This may be useful if you want to redefine steps for some scenarios. Let’s say we want to bypass login steps for some scenarios loading already defined session. In this case we can create `Step\FastLogin` class with redefined step “I am logged in as”.
```
gherkin:
contexts:
tag:
fastlogin:
- "Step\FastLogin"
```
Contexts can be autoloaded as well:
```
gherkin:
contexts:
path: tests/_support/Steps
namespace_prefix: Steps
default:
- AcceptanceTester
```
This will load all context from the given path and prefix it with the given namespace.
Migrating From Behat
--------------------
While Behat is a great tool for Behavior Driven Development, you still may prefer to use Codeception as your primary testing framework. In case you want to unify all your tests (unit/functional/acceptance), and make them be executed with one runner, Codeception is a good choice. Also Codeception provides rich set of well-maintained modules for various testing backends like Selenium Webdriver, Symfony, Laravel, etc.
If you decided to run your features with Codeception, we recommend to start with symlinking your `features` directory into one of the test suites:
```
ln -s $PWD/features tests/acceptance
```
Then you will need to implement all step definitions. Run `gherkin:snippets` to generate stubs for them. By default it is recommended to place step definitions into actor class (Tester) and use its methods for steps implementation.
Tests vs Features
-----------------
It is common to think that BDD scenario is equal to test. But it’s actually not. Not every test should be described as a feature. Not every test is written to test real business value. For instance, regression tests or negative scenario tests are not bringing any value to business. Business analysts don’t care about scenario reproducing bug #13, or what error message is displayed when user tries to enter wrong password on login screen. Writing all the tests inside a feature files creates informational overflow.
In Codeception you can combine tests written in Gherkin format with tests written in Cept/Cest/Test formats. This way you can keep your feature files compact with minimal set of scenarios, and write regular tests to cover all cases.
Corresponding features and tests can be attached to the same group. And what is more interesting, you can make tests to depend on feature scenarios. Let’s say we have `login.feature` file with “Log regular user” scenario in it. In this case you can specify that every test which requires login to pass to depend on “Log regular user” scenario:
```
@depends login:Log regular user
```
Inside `@depends` block you should use test signature. Execute your feature with `dry-run` to see signatures for all scenarios in it. By marking tests with `@depends` you ensure that this test won’t be executed before the test it depends on.
Conclusions
-----------
If you like the concept of Behavior Driven Development or prefer to keep test scenarios in human readable format, Codeception allows you to write and execute scenarios in Gherkin. Feature files is just another test format inside Codeception, so it can be combined with Cept and Cest files inside the same suite. Steps definitions of your scenarios can use all the power of Codeception modules, PageObjects, and StepObjects.
* **Next Chapter: [Customization >](08-customization)**
* **Previous Chapter: [< AdvancedUsage](07-advancedusage)**
| programming_docs |
codeception Filesystem Filesystem
==========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-filesystem
```
Alternatively, you can enable `Filesystem` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Module for testing local filesystem. Fork it to extend the module for FTP, Amazon S3, others.
Status
------
* Maintainer: **davert**
* Stability: **stable**
* Contact: [email protected]
Module was developed to test Codeception itself.
Actions
-------
### amInPath
Enters a directory In local filesystem. Project root directory is used by default
* `param string` $path
### cleanDir
Erases directory contents
```
<?php
$I->cleanDir('logs');
?>
```
* `param string` $dirname
### copyDir
Copies directory with all contents
```
<?php
$I->copyDir('vendor','old_vendor');
?>
```
* `param string` $src
* `param string` $dst
### deleteDir
Deletes directory with all subdirectories
```
<?php
$I->deleteDir('vendor');
?>
```
* `param string` $dirname
### deleteFile
Deletes a file
```
<?php
$I->deleteFile('composer.lock');
?>
```
* `param string` $filename
### deleteThisFile
Deletes a file
### dontSeeFileFound
Checks if file does not exist in path
* `param string` $filename
* `param string` $path
### dontSeeInThisFile
Checks If opened file doesn’t contain `text` in it
```
<?php
$I->openFile('composer.json');
$I->dontSeeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### openFile
Opens a file and stores it’s content.
Usage:
```
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param string` $filename
### seeFileContentsEqual
Checks the strict matching of file contents. Unlike `seeInThisFile` will fail if file has something more than expected lines. Better to use with HEREDOC strings. Matching is done after removing “\r” chars from file content.
```
<?php
$I->openFile('process.pid');
$I->seeFileContentsEqual('3192');
?>
```
* `param string` $text
### seeFileFound
Checks if file exists in path. Opens a file when it’s exists
```
<?php
$I->seeFileFound('UserModel.php','app/models');
?>
```
* `param string` $filename
* `param string` $path
### seeInThisFile
Checks If opened file has `text` in it.
Usage:
```
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### seeNumberNewLines
Checks If opened file has the `number` of new lines.
Usage:
```
<?php
$I->openFile('composer.json');
$I->seeNumberNewLines(5);
?>
```
* `param int` $number New lines
### seeThisFileMatches
Checks that contents of currently opened file matches $regex
* `param string` $regex
### writeToFile
Saves contents to file
* `param string` $filename
* `param string` $contents
codeception Sequence Sequence
========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-sequence
```
Alternatively, you can enable `Sequence` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Sequence solves data cleanup issue in alternative way. Instead cleaning up the database between tests, you can use generated unique names, that should not conflict. When you create article on a site, for instance, you can assign it a unique name and then check it.
This module has no actions, but introduces a function `sq` for generating unique sequences within test and `sqs` for generating unique sequences across suite.
### Usage
Function `sq` generates sequence, the only parameter it takes, is id. You can get back to previously generated sequence using that id:
```
<?php
sq('post1'); // post1_521fbc63021eb
sq('post2'); // post2_521fbc6302266
sq('post1'); // post1_521fbc63021eb
```
Example:
```
<?php
$I->wantTo('create article');
$I->click('New Article');
$I->fillField('Title', sq('Article'));
$I->fillField('Body', 'Demo article with Lorem Ipsum');
$I->click('save');
$I->see(sq('Article') ,'#articles')
```
Populating Database:
```
<?php
for ($i = 0; $i<10; $i++) {
$I->haveInDatabase('users', array('login' => sq("user$i"), 'email' => sq("user$i").'@email.com');
}
?>
```
Cest Suite tests:
```
<?php
class UserTest
{
public function createUser(AcceptanceTester $I)
{
$I->createUser(sqs('user') . '@mailserver.com', sqs('login'), sqs('pwd'));
}
public function checkEmail(AcceptanceTester $I)
{
$I->seeInEmailTo(sqs('user') . '@mailserver.com', sqs('login'));
}
public function removeUser(AcceptanceTester $I)
{
$I->removeUser(sqs('user') . '@mailserver.com');
}
}
?>
```
### Config
By default produces unique string with param as a prefix:
```
sq('user') => 'user_876asd8as87a'
```
This behavior can be configured using `prefix` config param.
Old style sequences:
```
Sequence:
prefix: '_'
```
Using id param inside prefix:
```
Sequence:
prefix: '{id}.'
```
Actions
-------
codeception Phalcon4 Phalcon4
========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-phalcon4
```
Alternatively, you can enable `Phalcon4` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module provides integration with [Phalcon framework](http://www.phalcon.io/) (4.x). Please try it and leave your feedback.
Status
------
* Maintainer: **Ruud Boon**
* Stability: **stable**
* Contact: [email protected]
Config
------
The following configurations are required for this module:
* bootstrap: `string`, default `app/config/bootstrap.php` - relative path to app.php config file
* cleanup: `boolean`, default `true` - all database queries will be run in a transaction, which will be rolled back at the end of each test
* savepoints: `boolean`, default `true` - use savepoints to emulate nested transactions
The application bootstrap file must return Application object but not call its handle() method.
API
---
* di - `Phalcon\Di\Injectable` instance
* client - `BrowserKit` client
Parts
-----
By default all available methods are loaded, but you can specify parts to select only needed actions and avoid conflicts.
* `orm` - include only `haveRecord/grabRecord/seeRecord/dontSeeRecord` actions.
* `services` - allows to use `grabServiceFromContainer` and `addServiceToContainer`.
See [WebDriver module](webdriver#Loading-Parts-from-other-Modules) for general information on how to load parts of a framework module.
Usage example:
Sample bootstrap (`app/config/bootstrap.php`):
```
<?php
$di = new \Phalcon\DI\FactoryDefault();
return new \Phalcon\Mvc\Application($di);
?>
```
```
actor: AcceptanceTester
modules:
enabled:
- Phalcon4:
part: services
bootstrap: 'app/config/bootstrap.php'
cleanup: true
savepoints: true
- WebDriver:
url: http://your-url.com
browser: phantomjs
```
Actions
-------
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('Phalcon4')->_findElements('.items');
$els = $this->getModule('Phalcon4')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('Phalcon4')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getResponseContent
*hidden API method, expected to be used from Helper classes*
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
```
<?php
// in Helper class
public function seeResponseContains($text)
{
$this->assertStringContainsString($text, $this->getModule('Phalcon4')->_getResponseContent(), "response contains");
}
```
* `return string` @throws ModuleException
### \_loadPage
*hidden API method, expected to be used from Helper classes*
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
```
<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
$this->getModule('Phalcon4')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
```
* `param string` $method
* `param string` $uri
* `param string` $content
### \_request
*hidden API method, expected to be used from Helper classes*
Send custom request to a backend using method, uri, parameters, etc. Use it in Helpers to create special request actions, like accessing API Returns a string with response body.
```
<?php
// in Helper class
public function createUserByApi($name) {
$userData = $this->getModule('Phalcon4')->_request('POST', '/api/v1/users', ['name' => $name]);
$user = json_decode($userData);
return $user->id;
}
```
Does not load the response into the module so you can’t interact with response page (click, fill forms). To load arbitrary page for interaction, use `_loadPage` method.
* `param string` $method
* `param string` $uri
* `param string` $content
* `return string` @throws ExternalUrlException @see `_loadPage`
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves page source of to a file
```
$this->getModule('Phalcon4')->_savePageSource(codecept_output_dir().'page.html');
```
* `param` $filename
### addServiceToContainer
Registers a service in the services container and resolve it. This record will be erased after the test. Recommended to use for unit testing.
```
<?php
$filter = $I->addServiceToContainer('filter', ['className' => '\Phalcon\Filter']);
$filter = $I->addServiceToContainer('answer', function () {
return rand(0, 1) ? 'Yes' : 'No';
}, true);
```
* `param string` $name
* `param mixed` $definition
* `param boolean` $shared
* `return mixed|null`
* `[Part]` services
### amHttpAuthenticated
Authenticates user for HTTP\_AUTH
* `param string` $username
* `param string` $password
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnRoute
Opens web page using route name and parameters.
```
<?php
$I->amOnRoute('posts.create');
```
* `param string` $routeName
* `param array` $params
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### deleteHeader
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
```
* `param string` $name the name of the header to delete.
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### dontSeeRecord
Checks that record does not exist in database.
```
<?php
$I->dontSeeRecord('App\Models\Categories', ['name' => 'Testing']);
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### dontSeeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->dontSeeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### followRedirect
Follow pending redirect if there is one.
```
<?php
$I->followRedirect();
```
### getApplication
Provides access the Phalcon application object.
@see \Codeception\Lib\Connector\Phalcon::getApplication
* `return \Phalcon\Application|\Phalcon\Mvc\Micro`
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabRecord
Retrieves record from database
```
<?php
$category = $I->grabRecord('App\Models\Categories', ['name' => 'Testing']);
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### grabServiceFromContainer
Resolves the service based on its configuration from Phalcon’s DI container Recommended to use for unit testing.
* `param string` $service Service name
* `param array` $parameters Parameters [Optional]
* `[Part]` services
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
* `param` $field
* `return array|mixed|null|string`
### haveHttpHeader
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
```
To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - ‘Client\_Id’ should be represented as - ‘Client\_Id’ or ‘Client\_Id’
```
<?php
$I->haveHttpHeader('Client_Id', 'Codeception');
```
* `param string` $name the name of the request header
* `param string` $value the value to set it to for subsequent requests
### haveInSession
Sets value to session. Use for authorization.
* `param string` $key
* `param mixed` $val
### haveRecord
Inserts record into the database.
```
<?php
$user_id = $I->haveRecord('App\Models\Users', ['name' => 'Phalcon']);
$I->haveRecord('App\Models\Categories', ['name' => 'Testing']');
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
* `param string` $name
* `param string` $value
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### moveBack
Moves back in history.
* `param int` $numberOfSteps (default value 1)
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentRouteIs
Checks that current url matches route
```
<?php
$I->seeCurrentRouteIs('posts.index');
```
* `param string` $routeName
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInSession
Checks that session contains value. If value is `null` checks that session has key.
```
<?php
$I->seeInSession('key');
$I->seeInSession('key', 'value');
```
* `param string` $key
* `param mixed` $value
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeNumberOfRecords
Checks that number of records exists in database.
```
<?php
$I->seeNumberOfRecords('App\Models\Categories', 3, ['name' => 'Testing']);
```
* `param string` $model Model name
* `param int` $number int number of records
* `param array` $attributes Model attributes
* `[Part]` orm
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### seePageNotFound
Asserts that current page has 404 response status code.
### seeRecord
Checks that record exists in database.
```
<?php
$I->seeRecord('App\Models\Categories', ['name' => 'Testing']);
```
* `param string` $model Model name
* `param array` $attributes Model attributes
* `[Part]` orm
### seeResponseCodeIs
Checks that response code is equal to value provided.
```
<?php
$I->seeResponseCodeIs(200);
// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `param int` $code
### seeResponseCodeIsBetween
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
* `param int` $from
* `param int` $to
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code 2xx
### seeSessionHasValues
Assert that the session has a given list of values.
```
<?php
$I->seeSessionHasValues(['key1', 'key2']);
$I->seeSessionHasValues(['key1' => 'value1', 'key2' => 'value2']);
```
* `param` array $bindings
* `return void`
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### sendAjaxGetRequest
Sends an ajax GET request with the passed parameters. See `sendAjaxPostRequest()`
* `param` $uri
* `param` $params
### sendAjaxPostRequest
Sends an ajax POST request with the passed parameters. The appropriate HTTP header is added automatically: `X-Requested-With: XMLHttpRequest` Example:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);
```
Some frameworks (e.g. Symfony) create field names in the form of an “array”: `<input type="text" name="form[task]">` In this case you need to pass the fields like this:
```
<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param string` $uri
* `param array` $params
### sendAjaxRequest
Sends an ajax request, using the passed HTTP method. See `sendAjaxPostRequest()` Example:
```
<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
```
* `param` $method
* `param` $uri
* `param array` $params
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### setMaxRedirects
Sets the maximum number of redirects that the Client can follow.
```
<?php
$I->setMaxRedirects(2);
```
* `param int` $maxRedirects
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client.
```
<?php
$I->startFollowingRedirects();
```
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client.
```
<?php
$I->stopFollowingRedirects();
```
### submitForm
Submits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of `fillField()`, `selectOption()`, `click()` etc. it has some important differences:
* Only field *names* may be used, not CSS/XPath selectors nor field labels
* If a field is sent to this function that does *not* exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will *not* get an exception like you would if you called `fillField()` or `selectOption()` with a missing field.
Fields that are not provided will be filled by their values from the page, or from any previous calls to `fillField()`, `selectOption()` etc. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify which button’s value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form id="userForm">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Subscribe to our newsletter?
<input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
To uncheck the pre-checked checkbox “newsletter”, call `$I->uncheckOption(['name' => 'user[newsletter]']);` *before*, then submit the form as shown here (i.e. without the “newsletter” field in the `$params` array).
You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.
```
<?php
$I->submitForm(
'#userForm',
[
'user' => [
'login' => 'Davert',
'password' => '123456',
'agree' => true
]
]
);
```
This function works well when paired with `seeInFormFields()` for quickly testing CRUD interfaces and form validation logic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);
```
Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean `true`/`false` which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false
],
'multiselect' => [
'first option value',
'second option value'
]
]);
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in `[]` must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
<?php
// This way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
* `param` $selector
* `param` $params
* `param` $button
### switchToIframe
Switch to iframe or frame on the page.
Example:
```
<iframe name="another_frame" src="http://example.com">
```
```
<?php
# switch to iframe
$I->switchToIframe("another_frame");
```
* `param string` $name
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
| programming_docs |
codeception FTP FTP
===
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-ftp
```
Alternatively, you can enable `FTP` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Works with SFTP/FTP servers.
In order to test the contents of a specific file stored on any remote FTP/SFTP system this module downloads a temporary file to the local system. The temporary directory is defined by default as
```
tests/_data
```
to specify a different directory set the tmp config option to your chosen path.
Don’t forget to create the folder and ensure its writable.
Supported and tested FTP types are:
* FTP
* SFTP
Connection uses php build in FTP client for FTP, connection to SFTP uses [phpseclib](http://phpseclib.sourceforge.net/) pulled in using composer.
For SFTP, add [phpseclib](http://phpseclib.sourceforge.net/) to require list.
```
"require": {
"phpseclib/phpseclib": "^2.0.14"
}
```
Status
------
* Stability:
+ FTP: **stable**
+ SFTP: **stable**
Config
------
* type: ftp - type of connection ftp/sftp (defaults to ftp).
* host *required* - hostname/ip address of the ftp server.
* port: 21 - port number for the ftp server
* timeout: 90 - timeout settings for connecting the ftp server.
* user: anonymous - user to access ftp server, defaults to anonymous authentication.
* password - password, defaults to empty for anonymous.
* key - path to RSA key for sftp.
* tmp - path to local directory for storing tmp files.
* passive: true - Turns on or off passive mode (FTP only)
* cleanup: true - remove tmp files from local directory on completion.
### Example
##### Example (FTP)
`modules:
enabled: [FTP]
config:
FTP:
type: ftp
host: '127.0.0.1'
port: 21
timeout: 120
user: 'root'
password: 'root'
key: ~/.ssh/id_rsa
tmp: 'tests/_data/ftp'
passive: true
cleanup: false` ##### Example (SFTP)
`modules:
enabled: [FTP]
config:
FTP:
type: sftp
host: '127.0.0.1'
port: 22
timeout: 120
user: 'root'
password: 'root'
key: ''
tmp: 'tests/_data/ftp'
cleanup: false` This module extends the Filesystem module, file contents methods are inherited from this module.
Actions
-------
### amInPath
Enters a directory on the ftp system - FTP root directory is used by default
* `param` $path
### cleanDir
Erases directory contents on the FTP/SFTP server
```
<?php
$I->cleanDir('logs');
?>
```
* `param` $dirname
### copyDir
Currently not supported in this module, overwrite inherited method
* `param` $src
* `param` $dst
### deleteDir
Deletes directory with all subdirectories on the remote FTP/SFTP server
```
<?php
$I->deleteDir('vendor');
?>
```
* `param` $dirname
### deleteFile
Deletes a file on the remote FTP/SFTP system
```
<?php
$I->deleteFile('composer.lock');
?>
```
* `param` $filename
### deleteThisFile
Deletes a file
### dontSeeFileFound
Checks if file does not exist in path on the remote FTP/SFTP system
* `param` $filename
* `param string` $path
### dontSeeFileFoundMatches
Checks if file does not exist in path on the remote FTP/SFTP system, using regular expression as filename. DOES NOT OPEN the file when it’s exists
* `param` $regex
* `param string` $path
### dontSeeInThisFile
Checks If opened file doesn’t contain `text` in it
```
<?php
$I->openFile('composer.json');
$I->dontSeeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### grabDirectory
Grabber method to return current working directory
```
<?php
$pwd = $I->grabDirectory();
?>
```
* `return string`
### grabFileCount
Grabber method for returning file/folders count in directory
```
<?php
$count = $I->grabFileCount();
$count = $I->grabFileCount('TEST', false); // Include . .. .thumbs.db
?>
```
* `param string` $path
* `param bool` $ignore - suppress ‘.’, ‘..’ and ‘.thumbs.db’
* `return int`
### grabFileList
Grabber method for returning file/folders listing in an array
```
<?php
$files = $I->grabFileList();
$count = $I->grabFileList('TEST', false); // Include . .. .thumbs.db
?>
```
* `param string` $path
* `param bool` $ignore - suppress ‘.’, ‘..’ and ‘.thumbs.db’
* `return array`
### grabFileModified
Grabber method to return last modified timestamp
```
<?php
$time = $I->grabFileModified('test.txt');
?>
```
* `param` $filename
* `return bool`
### grabFileSize
Grabber method to return file size
```
<?php
$size = $I->grabFileSize('test.txt');
?>
```
* `param` $filename
* `return bool`
### loginAs
Change the logged in user mid-way through your test, this closes the current connection to the server and initialises and new connection.
On initiation of this modules you are automatically logged into the server using the specified config options or defaulted to anonymous user if not provided.
```
<?php
$I->loginAs('user','password');
?>
```
* `param String` $user
* `param String` $password
### makeDir
Create a directory on the server
```
<?php
$I->makeDir('vendor');
?>
```
* `param` $dirname
### openFile
Opens a file (downloads from the remote FTP/SFTP system to a tmp directory for processing) and stores it’s content.
Usage:
```
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param` $filename
### renameDir
Rename/Move directory on the FTP/SFTP server
```
<?php
$I->renameDir('vendor', 'vendor_old');
?>
```
* `param` $dirname
* `param` $rename
### renameFile
Rename/Move file on the FTP/SFTP server
```
<?php
$I->renameFile('composer.lock', 'composer_old.lock');
?>
```
* `param` $filename
* `param` $rename
### seeFileContentsEqual
Checks the strict matching of file contents. Unlike `seeInThisFile` will fail if file has something more than expected lines. Better to use with HEREDOC strings. Matching is done after removing “\r” chars from file content.
```
<?php
$I->openFile('process.pid');
$I->seeFileContentsEqual('3192');
?>
```
* `param string` $text
### seeFileFound
Checks if file exists in path on the remote FTP/SFTP system. DOES NOT OPEN the file when it’s exists
```
<?php
$I->seeFileFound('UserModel.php','app/models');
?>
```
* `param` $filename
* `param string` $path
### seeFileFoundMatches
Checks if file exists in path on the remote FTP/SFTP system, using regular expression as filename. DOES NOT OPEN the file when it’s exists
```
<?php
$I->seeFileFoundMatches('/^UserModel_([0-9]{6}).php$/','app/models');
?>
```
* `param` $regex
* `param string` $path
### seeInThisFile
Checks If opened file has `text` in it.
Usage:
```
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### seeNumberNewLines
Checks If opened file has the `number` of new lines.
Usage:
```
<?php
$I->openFile('composer.json');
$I->seeNumberNewLines(5);
?>
```
* `param int` $number New lines
### seeThisFileMatches
Checks that contents of currently opened file matches $regex
* `param string` $regex
### writeToFile
Saves contents to tmp file and uploads the FTP/SFTP system. Overwrites current file on server if exists.
```
<?php
$I->writeToFile('composer.json', 'some data here');
?>
```
* `param` $filename
* `param` $contents
codeception REST REST
====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-rest
```
Alternatively, you can enable `REST` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Module for testing REST WebService.
This module requires either [PhpBrowser](phpbrowser) or a framework module (e.g. [Symfony](symfony), [Laravel](laravel5)) to send the actual HTTP request.
Configuration
-------------
* `url` *optional* - the url of api
* `shortDebugResponse` *optional* - number of chars to limit the API response length
### Example
```
modules:
enabled:
- REST:
depends: PhpBrowser
url: 'https://example.com/api/v1/'
shortDebugResponse: 300 # only the first 300 characters of the response
```
In case you need to configure low-level HTTP headers, that’s done on the PhpBrowser level like so:
```
modules:
enabled:
- REST:
depends: PhpBrowser
url: &url 'https://example.com/api/v1/'
config:
PhpBrowser:
url: *url
headers:
Content-Type: application/json
```
JSONPath
--------
[JSONPath](http://goessner.net/articles/JsonPath/) is the equivalent to XPath, for querying JSON data structures. Here’s an [Online JSONPath Expressions Tester](http://jsonpath.curiousconcept.com/)
Public Properties
-----------------
* headers - array of headers going to be sent.
* params - array of sent data
* response - last response (string)
Parts
-----
* Json - actions for validating Json responses (no Xml responses)
* Xml - actions for validating XML responses (no Json responses)
Conflicts
---------
Conflicts with SOAP module
Actions
-------
### amAWSAuthenticated
Allows to send REST request using AWS Authorization
Only works with PhpBrowser Example Config:
```
yml
modules:
enabled:
- REST:
aws:
key: accessKey
secret: accessSecret
service: awsService
region: awsRegion
```
Code:
```
<?php
$I->amAWSAuthenticated();
?>
```
* `param array` $additionalAWSConfig @throws ConfigurationException
### amBearerAuthenticated
Adds Bearer authentication via access token.
* `param` $accessToken
* `[Part]` json
* `[Part]` xml
### amDigestAuthenticated
Adds Digest authentication via username/password.
* `param` $username
* `param` $password
* `[Part]` json
* `[Part]` xml
### amHttpAuthenticated
Adds HTTP authentication via username/password.
* `param` $username
* `param` $password
* `[Part]` json
* `[Part]` xml
### amNTLMAuthenticated
Adds NTLM authentication via username/password. Requires client to be Guzzle >=6.3.0 Out of scope for functional modules.
Example:
```
<?php
$I->amNTLMAuthenticated('jon_snow', 'targaryen');
?>
```
* `param` $username
* `param` $password @throws ModuleException
* `[Part]` json
* `[Part]` xml
### deleteHeader
Deletes a HTTP header (that was originally added by [haveHttpHeader()](#haveHttpHeader)), so that subsequent requests will not send it anymore.
Example:
```
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->sendGet('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->sendPost('some-other-page.php');
?>
```
* `param string` $name the name of the header to delete.
* `[Part]` json
* `[Part]` xml
### dontSeeBinaryResponseEquals
Checks if the hash of a binary response is not the same as provided.
```
<?php
$I->dontSeeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
?>
```
Opposite to `seeBinaryResponseEquals`
* `param string` $hash the hashed data response expected
* `param string` $algo the hash algorithm to use. Default md5.
* `[Part]` json
* `[Part]` xml
### dontSeeHttpHeader
Checks over the given HTTP header and (optionally) its value, asserting that are not there
* `param` $name
* `param` $value
* `[Part]` json
* `[Part]` xml
### dontSeeResponseCodeIs
Checks that response code is not equal to provided value.
```
<?php
$I->dontSeeResponseCodeIs(200);
// preferred to use \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `[Part]` json
* `[Part]` xml
* `param` $code
### dontSeeResponseContains
Checks whether last response do not contain text.
* `param` $text
* `[Part]` json
* `[Part]` xml
### dontSeeResponseContainsJson
Opposite to seeResponseContainsJson
* `[Part]` json
* `param array` $json
### dontSeeResponseJsonMatchesJsonPath
See <#jsonpath> for general info on JSONPath. Opposite to [`seeResponseJsonMatchesJsonPath()`](#seeResponseJsonMatchesJsonPath)
* `param string` $jsonPath
* `[Part]` json
### dontSeeResponseJsonMatchesXpath
Opposite to seeResponseJsonMatchesXpath
* `param string` $xpath
* `[Part]` json
### dontSeeResponseMatchesJsonType
Opposite to `seeResponseMatchesJsonType`.
* `[Part]` json
* `param array` $jsonType JsonType structure
* `param string` $jsonPath @see seeResponseMatchesJsonType
### dontSeeXmlResponseEquals
Checks XML response does not equal to provided XML. Comparison is done by canonicalizing both xml`s.
Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
* `[Part]` xml
### dontSeeXmlResponseIncludes
Checks XML response does not include provided XML. Comparison is done by canonicalizing both xml`s. Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
* `[Part]` xml
### dontSeeXmlResponseMatchesXpath
Checks whether XML response does not match XPath
```
<?php
$I->dontSeeXmlResponseMatchesXpath('//root/user[@id=1]');
```
* `[Part]` xml
* `param` $xpath
### grabAttributeFromXmlElement
Finds and returns attribute of element. Element is matched by either CSS or XPath
* `param` $cssOrXPath
* `param` $attribute
* `return string`
* `[Part]` xml
### grabDataFromResponseByJsonPath
See <#jsonpath> for general info on JSONPath. Even for a single value an array is returned. Example:
```
<?php
// match the first `user.id` in json
$firstUserId = $I->grabDataFromResponseByJsonPath('$..users[0].id');
$I->sendPut('/user', array('id' => $firstUserId[0], 'name' => 'davert'));
?>
```
* `param string` $jsonPath
* `return array` Array of matching items @throws \Exception
* `[Part]` json
### grabHttpHeader
Returns the value of the specified header name
* `param` $name
* `param Boolean` $first Whether to return the first value or all header values
* `return string|array The first header value if` $first is true, an array of values otherwise
* `[Part]` json
* `[Part]` xml
### grabResponse
Returns current response so that it can be used in next scenario steps.
Example:
```
<?php
$user_id = $I->grabResponse();
$I->sendPut('/user', array('id' => $user_id, 'name' => 'davert'));
?>
```
* `return string`
* `[Part]` json
* `[Part]` xml
### grabTextContentFromXmlElement
Finds and returns text contents of element. Element is matched by either CSS or XPath
* `param` $cssOrXPath
* `return string`
* `[Part]` xml
### haveHttpHeader
Sets a HTTP header to be used for all subsequent requests. Use [`deleteHeader`](#deleteHeader) to unset it.
```
<?php
$I->haveHttpHeader('Content-Type', 'application/json');
// all next requests will contain this header
?>
```
* `param` $name
* `param` $value
* `[Part]` json
* `[Part]` xml
### haveServerParameter
Sets SERVER parameter valid for all next requests.
```
$I->haveServerParameter('name', 'value');
```
### seeBinaryResponseEquals
Checks if the hash of a binary response is exactly the same as provided. Parameter can be passed as any hash string supported by hash(), with an optional second parameter to specify the hash type, which defaults to md5.
Example: Using md5 hash key
```
<?php
$I->seeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
?>
```
Example: Using md5 for a file contents
```
<?php
$fileData = file_get_contents("test_file.jpg");
$I->seeBinaryResponseEquals(md5($fileData));
?>
```
Example: Using sha256 hash
```
<?php
$fileData = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k='; // very small jpeg
$I->seeBinaryResponseEquals(hash("sha256", base64_decode($fileData)), 'sha256');
?>
```
* `param string` $hash the hashed data response expected
* `param string` $algo the hash algorithm to use. Default md5.
* `[Part]` json
* `[Part]` xml
### seeHttpHeader
Checks over the given HTTP header and (optionally) its value, asserting that are there
* `param` $name
* `param` $value
* `[Part]` json
* `[Part]` xml
### seeHttpHeaderOnce
Checks that http response header is received only once. HTTP RFC2616 allows multiple response headers with the same name. You can check that you didn’t accidentally sent the same header twice.
```
<?php
$I->seeHttpHeaderOnce('Cache-Control');
?>>
```
* `param` $name
* `[Part]` json
* `[Part]` xml
### seeResponseCodeIs
Checks response code equals to provided value.
```
<?php
$I->seeResponseCodeIs(200);
// preferred to use \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `[Part]` json
* `[Part]` xml
* `param` $code
### seeResponseCodeIsClientError
Checks that the response code is 4xx
* `[Part]` json
* `[Part]` xml
### seeResponseCodeIsRedirection
Checks that the response code 3xx
* `[Part]` json
* `[Part]` xml
### seeResponseCodeIsServerError
Checks that the response code is 5xx
* `[Part]` json
* `[Part]` xml
### seeResponseCodeIsSuccessful
Checks that the response code is 2xx
* `[Part]` json
* `[Part]` xml
### seeResponseContains
Checks whether the last response contains text.
* `param` $text
* `[Part]` json
* `[Part]` xml
### seeResponseContainsJson
Checks whether the last JSON response contains provided array. The response is converted to array with json\_decode($response, true) Thus, JSON is represented by associative array. This method matches that response array contains provided array.
Examples:
```
<?php
// response: {name: john, email: [email protected]}
$I->seeResponseContainsJson(array('name' => 'john'));
// response {user: john, profile: { email: [email protected] }}
$I->seeResponseContainsJson(array('email' => '[email protected]'));
?>
```
This method recursively checks if one array can be found inside of another.
* `param array` $json
* `[Part]` json
### seeResponseEquals
Checks if response is exactly the same as provided.
* `[Part]` json
* `[Part]` xml
* `param` $response
### seeResponseIsJson
Checks whether last response was valid JSON. This is done with json\_last\_error function.
* `[Part]` json
### seeResponseIsValidOnJsonSchema
Checks whether last response matches the supplied json schema (https://json-schema.org/) Supply schema as relative file path in your project directory or an absolute path
@see codecept\_absolute\_path()
* `param string` $schemaFilename
* `[Part]` json
### seeResponseIsValidOnJsonSchemaString
Checks whether last response matches the supplied json schema (https://json-schema.org/) Supply schema as json string.
Examples:
```
<?php
// response: {"name": "john", "age": 20}
$I->seeResponseIsValidOnJsonSchemaString('{"type": "object"}');
// response {"name": "john", "age": 20}
$schema = [
"properties" => [
"age" => [
"type" => "integer",
"minimum" => 18
]
]
];
$I->seeResponseIsValidOnJsonSchemaString(json_encode($schema));
?>
```
* `param string` $schema
* `[Part]` json
### seeResponseIsXml
Checks whether last response was valid XML. This is done with libxml\_get\_last\_error function.
* `[Part]` xml
### seeResponseJsonMatchesJsonPath
See <#jsonpath> for general info on JSONPath. Checks if JSON structure in response matches JSONPath.
```
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
```
```
<?php
// at least one book in store has author
$I->seeResponseJsonMatchesJsonPath('$.store.book[*].author');
// first book in store has author
$I->seeResponseJsonMatchesJsonPath('$.store.book[0].author');
// at least one item in store has price
$I->seeResponseJsonMatchesJsonPath('$.store..price');
?>
```
* `param string` $jsonPath
* `[Part]` json
### seeResponseJsonMatchesXpath
Checks if json structure in response matches the xpath provided. JSON is not supposed to be checked against XPath, yet it can be converted to xml and used with XPath. This assertion allows you to check the structure of response json. \*
```
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
```
```
<?php
// at least one book in store has author
$I->seeResponseJsonMatchesXpath('//store/book/author');
// first book in store has author
$I->seeResponseJsonMatchesXpath('//store/book[1]/author');
// at least one item in store has price
$I->seeResponseJsonMatchesXpath('/store//price');
?>
```
* `param string` $xpath
* `[Part]` json
### seeResponseMatchesJsonType
Checks that JSON matches provided types. In case you don’t know the actual values of JSON data returned you can match them by type. It starts the check with a root element. If JSON data is an array it will check all elements of it. You can specify the path in the json which should be checked with JsonPath
Basic example:
```
<?php
// {'user_id': 1, 'name': 'davert', 'is_active': false}
$I->seeResponseMatchesJsonType([
'user_id' => 'integer',
'name' => 'string|null',
'is_active' => 'boolean'
]);
// narrow down matching with JsonPath:
// {"users": [{ "name": "davert"}, {"id": 1}]}
$I->seeResponseMatchesJsonType(['name' => 'string'], '$.users[0]');
?>
```
You can check if the record contains fields with the data types you expect. The list of possible data types:
* string
* integer
* float
* array (json object is array as well)
* boolean
* null
You can also use nested data type structures, and define multiple types for the same field:
```
<?php
// {'user_id': 1, 'name': 'davert', 'company': {'name': 'Codegyre'}}
$I->seeResponseMatchesJsonType([
'user_id' => 'integer|string', // multiple types
'company' => ['name' => 'string']
]);
?>
```
You can also apply filters to check values. Filter can be applied with a `:` char after the type declaration, or after another filter if you need more than one.
Here is the list of possible filters:
* `integer:>{val}` - checks that integer is greater than {val} (works with float and string types too).
* `integer:<{val}` - checks that integer is lower than {val} (works with float and string types too).
* `string:url` - checks that value is valid url.
* `string:date` - checks that value is date in JavaScript format: https://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates
* `string:email` - checks that value is a valid email according to http://emailregex.com/
* `string:regex({val})` - checks that string matches a regex provided with {val}
This is how filters can be used:
```
<?php
// {'user_id': 1, 'email' => '[email protected]'}
$I->seeResponseMatchesJsonType([
'user_id' => 'string:>0:<1000', // multiple filters can be used
'email' => 'string:regex(~\@~)' // we just check that @ char is included
]);
// {'user_id': '1'}
$I->seeResponseMatchesJsonType([
'user_id' => 'string:>0', // works with strings as well
]);
?>
```
You can also add custom filters by using `{@link JsonType::addCustomFilter()}`. See [JsonType reference](../reference/jsontype).
* `[Part]` json
* `param array` $jsonType
* `param string` $jsonPath @see JsonType
### seeXmlResponseEquals
Checks XML response equals provided XML. Comparison is done by canonicalizing both xml`s.
Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
* `[Part]` xml
### seeXmlResponseIncludes
Checks XML response includes provided XML. Comparison is done by canonicalizing both xml`s. Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
Example:
```
<?php
$I->seeXmlResponseIncludes("<result>1</result>");
?>
```
* `param` $xml
* `[Part]` xml
### seeXmlResponseMatchesXpath
Checks whether XML response matches XPath
```
<?php
$I->seeXmlResponseMatchesXpath('//root/user[@id=1]');
```
* `[Part]` xml
* `param` $xpath
### send
Sends a HTTP request.
* `param` $method
* `param` $url
* `param array|string|\JsonSerializable` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendDelete
Sends DELETE request to given uri.
* `param` $url
* `param array` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendGet
Sends a GET request to given uri.
* `param` $url
* `param array` $params
* `[Part]` json
* `[Part]` xml
### sendHead
Sends a HEAD request to given uri.
* `param` $url
* `param array` $params
* `[Part]` json
* `[Part]` xml
### sendLink
Sends LINK request to given uri.
* `param` $url
* `param array` $linkEntries (entry is array with keys “uri” and “link-param”)
@link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
@author [email protected]
* `[Part]` json
* `[Part]` xml
### sendOptions
Sends an OPTIONS request to given uri.
* `param` $url
* `param array` $params
* `[Part]` json
* `[Part]` xml
### sendPatch
Sends PATCH request to given uri.
* `param` $url
* `param array|string|\JsonSerializable` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendPost
Sends a POST request to given uri. Parameters and files can be provided separately.
Example:
```
<?php
//simple POST call
$I->sendPost('/message', ['subject' => 'Read this!', 'to' => '[email protected]']);
//simple upload method
$I->sendPost('/message/24', ['inline' => 0], ['attachmentFile' => codecept_data_dir('sample_file.pdf')]);
//uploading a file with a custom name and mime-type. This is also useful to simulate upload errors.
$I->sendPost('/message/24', ['inline' => 0], [
'attachmentFile' => [
'name' => 'document.pdf',
'type' => 'application/pdf',
'error' => UPLOAD_ERR_OK,
'size' => filesize(codecept_data_dir('sample_file.pdf')),
'tmp_name' => codecept_data_dir('sample_file.pdf')
]
]);
// If your field names contain square brackets (e.g. `<input type="text" name="form[task]">`),
// PHP parses them into an array. In this case you need to pass the fields like this:
$I->sendPost('/add-task', ['form' => [
'task' => 'lorem ipsum',
'category' => 'miscellaneous',
]]);
```
* `param` $url
* `param array|string|\JsonSerializable` $params
* `param array` $files A list of filenames or “mocks” of $\_FILES (each entry being an array with the following keys: name, type, error, size, tmp\_name (pointing to the real file path). Each key works as the “name” attribute of a file input field.
@see http://php.net/manual/en/features.file-upload.post-method.php @see codecept\_data\_dir()
* `[Part]` json
* `[Part]` xml
### sendPut
Sends PUT request to given uri.
* `param` $url
* `param array|string|\JsonSerializable` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendUnlink
Sends UNLINK request to given uri.
* `param` $url
* `param array` $linkEntries (entry is array with keys “uri” and “link-param”) @link http://tools.ietf.org/html/rfc2068#section-19.6.2.4 @author [email protected]
* `[Part]` json
* `[Part]` xml
### setServerParameters
Sets SERVER parameters valid for all next requests. this will remove old ones.
```
$I->setServerParameters([]);
```
### startFollowingRedirects
Enables automatic redirects to be followed by the client
```
<?php
$I->startFollowingRedirects();
```
* `[Part]` xml
* `[Part]` json
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client
```
<?php
$I->stopFollowingRedirects();
```
* `[Part]` xml
* `[Part]` json
| programming_docs |
codeception Redis Redis
=====
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-redis
```
Alternatively, you can enable `Redis` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
This module uses the [Predis](https://github.com/nrk/predis) library to interact with a Redis server.
Status
------
* Stability: **beta**
Configuration
-------------
* **`host`** (`string`, default `'127.0.0.1'`) - The Redis host
* **`port`** (`int`, default `6379`) - The Redis port
* **`database`** (`int`, no default) - The Redis database. Needs to be specified.
* **`username`** (`string`, no default) - When ACLs are enabled on Redis >= 6.0, both username and password are required for user authentication.
* **`password`** (`string`, no default) - The Redis password/secret.
* **`cleanupBefore`**: (`string`, default `'never'`) - Whether/when to flush the database:
+ `suite`: at the beginning of every suite
+ `test`: at the beginning of every test
+ Any other value: never
Note: The full configuration list can be found on Predis’ github.
### Example (`unit.suite.yml`)
```
modules:
- Redis:
host: '127.0.0.1'
port: 6379
database: 0
cleanupBefore: 'never'
```
Public Properties
-----------------
* **driver** - Contains the Predis client/driver
@author Marc Verney [[email protected]](https://codeception.com/cdn-cgi/l/email-protection#7d101c0f1e3d101c0f1e0b180f13180453131809)
Actions
-------
### cleanup
Delete all the keys in the Redis database
@throws ModuleException
### dontSeeInRedis
Asserts that a key does not exist or, optionally, that it doesn’t have the provided $value
Examples:
```
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInRedis('example:string');
// Checks a String does not exist or its value is not the one provided
$I->dontSeeInRedis('example:string', 'life');
// Checks a List does not exist or its value is not the one provided (order of elements is compared).
$I->dontSeeInRedis('example:list', ['riri', 'fifi', 'loulou']);
// Checks a Set does not exist or its value is not the one provided (order of members is ignored).
$I->dontSeeInRedis('example:set', ['riri', 'fifi', 'loulou']);
// Checks a ZSet does not exist or its value is not the one provided (scores are required, order of members is compared)
$I->dontSeeInRedis('example:zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Checks a Hash does not exist or its value is not the one provided (order of members is ignored).
$I->dontSeeInRedis('example:hash', ['riri' => true, 'fifi' => 'Dewey', 'loulou' => 2]);
```
* `param string` $key The key name
* `param mixed` $value Optional. If specified, also checks the key has this value. Booleans will be converted to 1 and 0 (even inside arrays)
### dontSeeRedisKeyContains
Asserts that a given key does not contain a given item
Examples:
```
<?php
// Strings: performs a substring search
$I->dontSeeRedisKeyContains('string', 'bar');
// Lists
$I->dontSeeRedisKeyContains('example:list', 'poney');
// Sets
$I->dontSeeRedisKeyContains('example:set', 'cat');
// ZSets: check whether the zset has this member
$I->dontSeeRedisKeyContains('example:zset', 'jordan');
// ZSets: check whether the zset has this member with this score
$I->dontSeeRedisKeyContains('example:zset', 'jordan', 23);
// Hashes: check whether the hash has this field
$I->dontSeeRedisKeyContains('example:hash', 'magic');
// Hashes: check whether the hash has this field with this value
$I->dontSeeRedisKeyContains('example:hash', 'magic', 32);
```
* `param string` $key The key
* `param mixed` $item The item
* `param null` $itemValue Optional and only used for zsets and hashes. If specified, the method will also check that the $item has this value/score
### grabFromRedis
Returns the value of a given key
Examples:
```
<?php
// Strings
$I->grabFromRedis('string');
// Lists: get all members
$I->grabFromRedis('example:list');
// Lists: get a specific member
$I->grabFromRedis('example:list', 2);
// Lists: get a range of elements
$I->grabFromRedis('example:list', 2, 4);
// Sets: get all members
$I->grabFromRedis('example:set');
// ZSets: get all members
$I->grabFromRedis('example:zset');
// ZSets: get a range of members
$I->grabFromRedis('example:zset', 3, 12);
// Hashes: get all fields of a key
$I->grabFromRedis('example:hash');
// Hashes: get a specific field of a key
$I->grabFromRedis('example:hash', 'foo');
```
* `param string` $key The key name
* `return array|string|null`
@throws ModuleException if the key does not exist
### haveInRedis
Creates or modifies keys
If $key already exists:
* Strings: its value will be overwritten with $value
* Other types: $value items will be appended to its value
Examples:
```
<?php
// Strings: $value must be a scalar
$I->haveInRedis('string', 'Obladi Oblada');
// Lists: $value can be a scalar or an array
$I->haveInRedis('list', ['riri', 'fifi', 'loulou']);
// Sets: $value can be a scalar or an array
$I->haveInRedis('set', ['riri', 'fifi', 'loulou']);
// ZSets: $value must be an associative array with scores
$I->haveInRedis('zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Hashes: $value must be an associative array
$I->haveInRedis('hash', ['obladi' => 'oblada']);
```
* `param string` $type The type of the key
* `param string` $key The key name
* `param mixed` $value The value
@throws ModuleException
### seeInRedis
Asserts that a key exists, and optionally that it has the provided $value
Examples:
```
<?php
// With only one argument, only checks the key exists
$I->seeInRedis('example:string');
// Checks a String exists and has the value "life"
$I->seeInRedis('example:string', 'life');
// Checks the value of a List. Order of elements is compared.
$I->seeInRedis('example:list', ['riri', 'fifi', 'loulou']);
// Checks the value of a Set. Order of members is ignored.
$I->seeInRedis('example:set', ['riri', 'fifi', 'loulou']);
// Checks the value of a ZSet. Scores are required. Order of members is compared.
$I->seeInRedis('example:zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Checks the value of a Hash. Order of members is ignored.
$I->seeInRedis('example:hash', ['riri' => true, 'fifi' => 'Dewey', 'loulou' => 2]);
```
* `param string` $key The key name
* `param mixed` $value Optional. If specified, also checks the key has this value. Booleans will be converted to 1 and 0 (even inside arrays)
### seeRedisKeyContains
Asserts that a given key contains a given item
Examples:
```
<?php
// Strings: performs a substring search
$I->seeRedisKeyContains('example:string', 'bar');
// Lists
$I->seeRedisKeyContains('example:list', 'poney');
// Sets
$I->seeRedisKeyContains('example:set', 'cat');
// ZSets: check whether the zset has this member
$I->seeRedisKeyContains('example:zset', 'jordan');
// ZSets: check whether the zset has this member with this score
$I->seeRedisKeyContains('example:zset', 'jordan', 23);
// Hashes: check whether the hash has this field
$I->seeRedisKeyContains('example:hash', 'magic');
// Hashes: check whether the hash has this field with this value
$I->seeRedisKeyContains('example:hash', 'magic', 32);
```
* `param string` $key The key
* `param mixed` $item The item
* `param null` $itemValue Optional and only used for zsets and hashes. If specified, the method will also check that the $item has this value/score
### sendCommandToRedis
Sends a command directly to the Redis driver. See documentation at https://github.com/nrk/predis Every argument that follows the $command name will be passed to it.
Examples:
```
<?php
$I->sendCommandToRedis('incr', 'example:string');
$I->sendCommandToRedis('strLen', 'example:string');
$I->sendCommandToRedis('lPop', 'example:list');
$I->sendCommandToRedis('zRangeByScore', 'example:set', '-inf', '+inf', ['withscores' => true, 'limit' => [1, 2]]);
$I->sendCommandToRedis('flushdb');
```
* `param string` $command The command name
codeception WebDriver WebDriver
=========
Installation
------------
If you use Codeception installed using composer, install this module with the following command:
```
composer require --dev codeception/module-webdriver
```
Alternatively, you can enable `WebDriver` module in suite configuration file and run
```
codecept init upgrade4
```
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
Description
-----------
Run tests in real browsers using the W3C [WebDriver protocol](https://www.w3.org/TR/webdriver/). There are multiple ways of running browser tests using WebDriver:
Selenium (Recommended)
----------------------
* Java is required
* NodeJS is required
The fastest way to get started is to [Install and launch Selenium using selenium-standalone NodeJS package](https://www.npmjs.com/package/selenium-standalone).
Launch selenium standalone in separate console window:
```
selenium-standalone start
```
Update configuration in `acceptance.suite.yml`:
```
modules:
enabled:
- WebDriver:
url: 'http://localhost/'
browser: chrome # 'chrome' or 'firefox'
```
Headless Chrome Browser
-----------------------
To enable headless mode (launch tests without showing a window) for Chrome browser using Selenium use this config in `acceptance.suite.yml`:
```
modules:
enabled:
- WebDriver:
url: 'http://localhost/'
browser: chrome
capabilities:
chromeOptions:
args: ["--headless", "--disable-gpu"]
```
Headless Selenium in Docker
---------------------------
Docker can ship Selenium Server with all its dependencies and browsers inside a single container. Running tests inside Docker is as easy as pulling [official selenium image](https://github.com/SeleniumHQ/docker-selenium) and starting a container with Chrome:
```
docker run --net=host selenium/standalone-chrome
```
By using `--net=host` allow Selenium to access local websites.
Local Chrome and/or Firefox
---------------------------
Tests can be executed directly throgh ChromeDriver or GeckoDriver (for Firefox). Consider using this option if you don’t plan to use Selenium.
### ChromeDriver
* Download and install [ChromeDriver](https://sites.google.com/chromium.org/driver/downloads?authuser=0)
* Launch ChromeDriver in a separate console window: `chromedriver --url-base=/wd/hub`.
Configuration in `acceptance.suite.yml`:
```
modules:
enabled:
- WebDriver:
url: 'http://localhost/'
window_size: false # disabled in ChromeDriver
port: 9515
browser: chrome
capabilities:
chromeOptions:
args: ["--headless", "--disable-gpu"] # Run Chrome in headless mode
prefs:
download.default_directory: "..."
```
See here for additional [Chrome options](https://sites.google.com/a/chromium.org/chromedriver/capabilities)
### GeckoDriver
* [GeckoDriver])(https://github.com/mozilla/geckodriver/releases) must be installed
* Start GeckoDriver in a separate console window: `geckodriver`.
Configuration in `acceptance.suite.yml`:
```
modules:
enabled:
- WebDriver:
url: 'http://localhost/'
browser: firefox
path: ''
capabilities:
acceptInsecureCerts: true # allow self-signed certificates
moz:firefoxOptions:
args: ["-headless"] # Run Firefox in headless mode
prefs:
intl.accept_languages: "de-AT" # Set HTTP-Header `Accept-Language: de-AT` for requests
```
See here for [Firefox capabilities](https://developer.mozilla.org/en-US/docs/Web/WebDriver/Capabilities#List_of_capabilities)
Cloud Testing
-------------
Cloud Testing services can run your WebDriver tests in the cloud. In case you want to test a local site or site behind a firewall you should use a tunnel application provided by a service.
### SauceLabs
1. Create an account at [SauceLabs.com](http://SauceLabs.com) to get your username and access key
2. In the module configuration use the format `username`:`access_key`@ondemand.saucelabs.com’ for `host`
3. Configure `platform` under `capabilities` to define the [Operating System](https://docs.saucelabs.com/reference/platforms-configurator/#/)
4. run a tunnel app if your site can’t be accessed from Internet
```
modules:
enabled:
- WebDriver:
url: http://mysite.com
host: '<username>:<access key>@ondemand.saucelabs.com'
port: 80
browser: chrome
capabilities:
platform: 'Windows 10'
```
### BrowserStack
1. Create an account at [BrowserStack](https://www.browserstack.com/) to get your username and access key
2. In the module configuration use the format `username`:`access_key`@hub.browserstack.com’ for `host`
3. Configure `os` and `os_version` under `capabilities` to define the operating System
4. If your site is available only locally or via VPN you should use a tunnel app. In this case add `browserstack.local` capability and set it to true.
```
modules:
enabled:
- WebDriver:
url: http://mysite.com
host: '<username>:<access key>@hub.browserstack.com'
port: 80
browser: chrome
capabilities:
os: Windows
os_version: 10
browserstack.local: true # for local testing
```
### LambdaTest
1. Create an account at [LambdaTest](https://www.lambdatest.com/) to get your username and access key
2. In the module configuration use the format `username`:`access key`@hub.lambdatest.com’ for `host`
3. Configure `os` and `os_version` under `capabilities` to define the operating System
4. If your site is available only locally or via VPN you should use a tunnel app. In this case add capabilities.setCapability(“tunnel”,true);.
```
modules:
enabled:
- WebDriver:
url: http://mysite.com
host: '<username>:<access key>@hub.lambdatest.com'
build: <your build name>
name: <your test name>
port: 80
browser: chrome
capabilities:
os: Windows
os_version: 10
browser_version: 86
resolution: 1366x768
tunnel: true # for local testing
```
### TestingBot
1. Create an account at [TestingBot](https://testingbot.com/) to get your key and secret
2. In the module configuration use the format `key`:`secret`@hub.testingbot.com’ for `host`
3. Configure `platform` under `capabilities` to define the [Operating System](https://testingbot.com/support/getting-started/browsers.html)
4. Run [TestingBot Tunnel](https://testingbot.com/support/other/tunnel) if your site can’t be accessed from Internet
```
modules:
enabled:
- WebDriver:
url: http://mysite.com
host: '<key>:<secret>@hub.testingbot.com'
port: 80
browser: chrome
capabilities:
platform: Windows 10
```
Configuration
-------------
* `url` *required* - Base URL for your app (amOnPage opens URLs relative to this setting).
* `browser` *required* - Browser to launch.
* `host` - Selenium server host (127.0.0.1 by default).
* `port` - Selenium server port (4444 by default).
* `restart` - Set to `false` (default) to use the same browser window for all tests, or set to `true` to create a new window for each test. In any case, when all tests are finished the browser window is closed.
* `start` - Autostart a browser for tests. Can be disabled if browser session is started with `_initializeSession` inside a Helper.
* `window_size` - Initial window size. Set to `maximize` or a dimension in the format `640x480`.
* `clear_cookies` - Set to false to keep cookies, or set to true (default) to delete all cookies between tests.
* `wait` (default: 0 seconds) - Whenever element is required and is not on page, wait for n seconds to find it before fail.
* `capabilities` - Sets Selenium [desired capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities). Should be a key-value array.
* `connection_timeout` - timeout for opening a connection to remote selenium server (30 seconds by default).
* `request_timeout` - timeout for a request to return something from remote selenium server (30 seconds by default).
* `pageload_timeout` - amount of time to wait for a page load to complete before throwing an error (default 0 seconds).
* `http_proxy` - sets http proxy server url for testing a remote server.
* `http_proxy_port` - sets http proxy server port
* `ssl_proxy` - sets ssl(https) proxy server url for testing a remote server.
* `ssl_proxy_port` - sets ssl(https) proxy server port
* `debug_log_entries` - how many selenium entries to print with `debugWebDriverLogs` or on fail (0 by default).
* `log_js_errors` - Set to true to include possible JavaScript to HTML report, or set to false (default) to deactivate.
* `webdriver_proxy` - sets http proxy to tunnel requests to the remote Selenium WebDriver through
* `webdriver_proxy_port` - sets http proxy server port to tunnel requests to the remote Selenium WebDriver through
Example (`acceptance.suite.yml`)
```
modules:
enabled:
- WebDriver:
url: 'http://localhost/'
browser: firefox
window_size: 1024x768
capabilities:
unexpectedAlertBehaviour: 'accept'
firefox_profile: '~/firefox-profiles/codeception-profile.zip.b64'
```
Loading Parts from other Modules
--------------------------------
While all Codeception modules are designed to work stand-alone, it’s still possible to load *several* modules at once. To use e.g. the [Asserts module](asserts) in your acceptance tests, just load it like this in your `acceptance.suite.yml`:
```
modules:
enabled:
- WebDriver
- Asserts
```
However, when loading a framework module (e.g. [Symfony](symfony)) like this, it would lead to a conflict: When you call `$I->amOnPage()`, Codeception wouldn’t know if you want to access the page using WebDriver’s `amOnPage()`, or Symfony’s `amOnPage()`. That’s why possibly conflicting modules are separated into “parts”. Here’s how to load just the “services” part from e.g. Symfony:
```
modules:
enabled:
- WebDriver
- Symfony:
part: services
```
To find out which parts each module has, look at the “Parts” header on the module’s page.
Usage
-----
### Locating Elements
Most methods in this module that operate on a DOM element (e.g. `click`) accept a locator as the first argument, which can be either a string or an array.
If the locator is an array, it should have a single element, with the key signifying the locator type (`id`, `name`, `css`, `xpath`, `link`, or `class`) and the value being the locator itself. This is called a “strict” locator. Examples:
* `['id' => 'foo']` matches `<div id="foo">`
* `['name' => 'foo']` matches `<div name="foo">`
* `['css' => 'input[type=input][value=foo]']` matches `<input type="input" value="foo">`
* `['xpath' => "//input[@type='submit'][contains(@value, 'foo')]"]` matches `<input type="submit" value="foobar">`
* `['link' => 'Click here']` matches `<a href="google.com">Click here</a>`
* `['class' => 'foo']` matches `<div class="foo">`
Writing good locators can be tricky. The Mozilla team has written an excellent guide titled [Writing reliable locators for Selenium and WebDriver tests](https://blog.mozilla.org/webqa/2013/09/26/writing-reliable-locators-for-selenium-and-webdriver-tests/).
If you prefer, you may also pass a string for the locator. This is called a “fuzzy” locator. In this case, Codeception uses a a variety of heuristics (depending on the exact method called) to determine what element you’re referring to. For example, here’s the heuristic used for the `submitForm` method:
1. Does the locator look like an ID selector (e.g. “#foo”)? If so, try to find a form matching that ID.
2. If nothing found, check if locator looks like a CSS selector. If so, run it.
3. If nothing found, check if locator looks like an XPath expression. If so, run it.
4. Throw an `ElementNotFound` exception.
Be warned that fuzzy locators can be significantly slower than strict locators. Especially if you use Selenium WebDriver with `wait` (aka implicit wait) option. In the example above if you set `wait` to 5 seconds and use XPath string as fuzzy locator, `submitForm` method will wait for 5 seconds at each step. That means 5 seconds finding the form by ID, another 5 seconds finding by CSS until it finally tries to find the form by XPath). If speed is a concern, it’s recommended you stick with explicitly specifying the locator type via the array syntax.
### Get Scenario Metadata
You can inject `\Codeception\Scenario` into your test to get information about the current configuration:
```
use Codeception\Scenario
public function myTest(AcceptanceTester $I, Scenario $scenario)
{
if ('firefox' === $scenario->current('browser')) {
// ...
}
}
```
See [Get Scenario Metadata](../07-advancedusage#Get-Scenario-Metadata) for more information on `$scenario`.
Public Properties
-----------------
* `webDriver` - instance of `\Facebook\WebDriver\Remote\RemoteWebDriver`. Can be accessed from Helper classes for complex WebDriver interactions.
```
// inside Helper class
$this->getModule('WebDriver')->webDriver->getKeyboard()->sendKeys('hello, webdriver');
```
Actions
-------
### \_backupSession
*hidden API method, expected to be used from Helper classes*
Returns current WebDriver session for saving
* `return RemoteWebDriver`
### \_capabilities
*hidden API method, expected to be used from Helper classes*
Change capabilities of WebDriver. Should be executed before starting a new browser session. This method expects a function to be passed which returns array or [WebDriver Desired Capabilities](https://github.com/php-webdriver/php-webdriver/blob/main/lib/Remote/DesiredCapabilities.php) object. Additional [Chrome options](https://github.com/php-webdriver/php-webdriver/wiki/ChromeOptions) (like adding extensions) can be passed as well.
```
<?php // in helper
public function _before(TestInterface $test)
{
$this->getModule('WebDriver')->_capabilities(function($currentCapabilities) {
// or new \Facebook\WebDriver\Remote\DesiredCapabilities();
return \Facebook\WebDriver\Remote\DesiredCapabilities::firefox();
});
}
```
to make this work load `\Helper\Acceptance` before `WebDriver` in `acceptance.suite.yml`:
```
modules:
enabled:
- \Helper\Acceptance
- WebDriver
```
For instance, [**BrowserStack** cloud service](https://www.browserstack.com/automate/capabilities) may require a test name to be set in capabilities. This is how it can be done via `_capabilities` method from `Helper\Acceptance`:
```
<?php // inside Helper\Acceptance
public function _before(TestInterface $test)
{
$name = $test->getMetadata()->getName();
$this->getModule('WebDriver')->_capabilities(function($currentCapabilities) use ($name) {
$currentCapabilities['name'] = $name;
return $currentCapabilities;
});
}
```
In this case, please ensure that `\Helper\Acceptance` is loaded before WebDriver so new capabilities could be applied.
* `param \Closure` $capabilityFunction
### \_closeSession
*hidden API method, expected to be used from Helper classes*
Manually closes current WebDriver session.
```
<?php
$this->getModule('WebDriver')->_closeSession();
// close a specific session
$webDriver = $this->getModule('WebDriver')->webDriver;
$this->getModule('WebDriver')->_closeSession($webDriver);
```
* `param` $webDriver (optional) a specific webdriver session instance
### \_findClickable
*hidden API method, expected to be used from Helper classes*
Locates a clickable element.
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$module = $this->getModule('WebDriver');
$page = $module->webDriver;
// search a link or button on a page
$el = $module->_findClickable($page, 'Click Me');
// search a link or button within an element
$topBar = $module->_findElements('.top-bar')[0];
$el = $module->_findClickable($topBar, 'Click Me');
```
* `param RemoteWebDriver` $page WebDriver instance or an element to search within
* `param` $link a link text or locator to click
* `return WebDriverElement`
### \_findElements
*hidden API method, expected to be used from Helper classes*
Locates element using available Codeception locator types:
* XPath
* CSS
* Strict Locator
Use it in Helpers or GroupObject or Extension classes:
```
<?php
$els = $this->getModule('WebDriver')->_findElements('.items');
$els = $this->getModule('WebDriver')->_findElements(['name' => 'username']);
$editLinks = $this->getModule('WebDriver')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs
```
WebDriver module returns `Facebook\WebDriver\Remote\RemoteWebElement` instances PhpBrowser and Framework modules return `Symfony\Component\DomCrawler\Crawler` instances
* `param` $locator
* `return array` of interactive elements
### \_getCurrentUri
*hidden API method, expected to be used from Helper classes*
Uri of currently opened page.
* `return string` @throws ModuleException
### \_getUrl
*hidden API method, expected to be used from Helper classes*
Returns URL of a host.
@throws ModuleConfigException
### \_initializeSession
*hidden API method, expected to be used from Helper classes*
Manually starts a new browser session.
```
<?php
$this->getModule('WebDriver')->_initializeSession();
```
### \_loadSession
*hidden API method, expected to be used from Helper classes*
Loads current RemoteWebDriver instance as a session
* `param RemoteWebDriver` $session
### \_restart
*hidden API method, expected to be used from Helper classes*
Restarts a web browser. Can be used with `_reconfigure` to open browser with different configuration
```
<?php
// inside a Helper
$this->getModule('WebDriver')->_restart(); // just restart
$this->getModule('WebDriver')->_restart(['browser' => $browser]); // reconfigure + restart
```
* `param array` $config
### \_savePageSource
*hidden API method, expected to be used from Helper classes*
Saves HTML source of a page to a file
* `param` $filename
### \_saveScreenshot
*hidden API method, expected to be used from Helper classes*
Saves screenshot of current page to a file
```
$this->getModule('WebDriver')->_saveScreenshot(codecept_output_dir().'screenshot_1.png');
```
* `param` $filename
### acceptPopup
Accepts the active JavaScript native popup window, as created by `window.alert`|`window.confirm`|`window.prompt`. Don’t confuse popups with modal windows, as created by [various libraries](http://jster.net/category/windows-modals-popups).
### amOnPage
Opens the page for the given relative URI.
```
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
```
* `param string` $page
### amOnSubdomain
Changes the subdomain for the ‘url’ configuration parameter. Does not open a page; use `amOnPage` for that.
```
<?php
// If config is: 'http://mysite.com'
// or config is: 'http://www.mysite.com'
// or config is: 'http://company.mysite.com'
$I->amOnSubdomain('user');
$I->amOnPage('/');
// moves to http://user.mysite.com/
?>
```
* `param` $subdomain
### amOnUrl
Open web page at the given absolute URL and sets its hostname as the base host.
```
<?php
$I->amOnUrl('http://codeception.com');
$I->amOnPage('/quickstart'); // moves to http://codeception.com/quickstart
?>
```
### appendField
Append the given text to the given element. Can also add a selection to a select box.
```
<?php
$I->appendField('#mySelectbox', 'SelectValue');
$I->appendField('#myTextField', 'appended');
?>
```
* `param string` $field
* `param string` $value @throws \Codeception\Exception\ElementNotFound
### attachFile
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
```
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
```
* `param` $field
* `param` $filename
### cancelPopup
Dismisses the active JavaScript popup, as created by `window.alert`, `window.confirm`, or `window.prompt`.
### checkOption
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
```
<?php
$I->checkOption('#agree');
?>
```
* `param` $option
### clearField
Clears given field which isn’t empty.
```
<?php
$I->clearField('#username');
```
* `param` $field
### click
Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.
The second parameter is a context (CSS or XPath locator) to narrow the search.
Note that if the locator matches a button of type `submit`, the form will be submitted.
```
<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
```
* `param` $link
* `param` $context
### clickWithLeftButton
Performs click with the left mouse button on an element. If the first parameter `null` then the offset is relative to the actual mouse position. If the second and third parameters are given, then the mouse is moved to an offset of the element’s top-left corner. Otherwise, the mouse is moved to the center of the element.
```
<?php
$I->clickWithLeftButton(['css' => '.checkout']);
$I->clickWithLeftButton(null, 20, 50);
$I->clickWithLeftButton(['css' => '.checkout'], 20, 50);
?>
```
* `param string` $cssOrXPath css or xpath of the web element (body by default).
* `param int` $offsetX
* `param int` $offsetY
@throws \Codeception\Exception\ElementNotFound
### clickWithRightButton
Performs contextual click with the right mouse button on an element. If the first parameter `null` then the offset is relative to the actual mouse position. If the second and third parameters are given, then the mouse is moved to an offset of the element’s top-left corner. Otherwise, the mouse is moved to the center of the element.
```
<?php
$I->clickWithRightButton(['css' => '.checkout']);
$I->clickWithRightButton(null, 20, 50);
$I->clickWithRightButton(['css' => '.checkout'], 20, 50);
?>
```
* `param string` $cssOrXPath css or xpath of the web element (body by default).
* `param int` $offsetX
* `param int` $offsetY
@throws \Codeception\Exception\ElementNotFound
### closeTab
Closes current browser tab and switches to previous active tab.
```
<?php
$I->closeTab();
```
### debugWebDriverLogs
Print out latest Selenium Logs in debug mode
* `param \Codeception\TestInterface` $test
### deleteSessionSnapshot
Deletes session snapshot.
See [saveSessionSnapshot](#saveSessionSnapshot)
* `param` $name
### dontSee
Checks that the current page doesn’t contain the text specified (case insensitive). Give a locator as the second parameter to match a specific region.
```
<?php
$I->dontSee('Login'); // I can suppose user is already logged in
$I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1'); // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->dontSee('strong')` will fail on strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will ignore strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### dontSeeCheckboxIsChecked
Check that the specified checkbox is unchecked.
```
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
```
* `param` $checkbox
### dontSeeCookie
Checks that there isn’t a cookie with the given name. You can set additional cookie params like `domain`, `path` as array passed in last argument.
* `param` $cookie
* `param array` $params
### dontSeeCurrentUrlEquals
Checks that the current URL doesn’t equal the given string. Unlike `dontSeeInCurrentUrl`, this only matches the full URL.
```
<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### dontSeeCurrentUrlMatches
Checks that current url doesn’t match the given regular expression.
```
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### dontSeeElement
Checks that the given element is invisible or not present on the page. You can also specify expected attributes of this element.
```
<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
```
* `param` $selector
* `param array` $attributes
### dontSeeElementInDOM
Opposite of `seeElementInDOM`.
* `param` $selector
* `param array` $attributes
### dontSeeInCurrentUrl
Checks that the current URI doesn’t contain the given string.
```
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### dontSeeInField
Checks that an input field or textarea doesn’t contain the given value. For fuzzy locators, the field is matched by label text, CSS and XPath.
```
<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### dontSeeInFormFields
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
```
<?php
$I->dontSeeInFormFields('form[name=myform]', [
'input1' => 'non-existent value',
'input2' => 'other non-existent value',
]);
?>
```
To check that an element hasn’t been assigned any one of many values, an array can be passed as the value:
```
<?php
$I->dontSeeInFormFields('.form-class', [
'fieldName' => [
'This value shouldn\'t be set',
'And this value shouldn\'t be set',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->dontSeeInFormFields('#form-id', [
'checkbox1' => true, // fails if checked
'checkbox2' => false, // fails if unchecked
]);
?>
```
* `param` $formSelector
* `param` $params
### dontSeeInPageSource
Checks that the page source doesn’t contain the given string.
* `param` $text
### dontSeeInPopup
Checks that the active JavaScript popup, as created by `window.alert`|`window.confirm`|`window.prompt`, does NOT contain the given string.
* `param` $text
@throws \Codeception\Exception\ModuleException
### dontSeeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->dontSeeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### dontSeeInTitle
Checks that the page title does not contain the given string.
* `param` $title
### dontSeeLink
Checks that the page doesn’t contain a link with the given string. If the second parameter is given, only links with a matching “href” attribute will be checked.
```
<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
```
* `param string` $text
* `param string` $url optional
### dontSeeOptionIsSelected
Checks that the given option is not selected.
```
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### doubleClick
Performs a double-click on an element matched by CSS or XPath.
* `param` $cssOrXPath @throws \Codeception\Exception\ElementNotFound
### dragAndDrop
Performs a simple mouse drag-and-drop operation.
```
<?php
$I->dragAndDrop('#drag', '#drop');
?>
```
* `param string` $source (CSS ID or XPath)
* `param string` $target (CSS ID or XPath)
### executeAsyncJS
Executes asynchronous JavaScript. A callback should be executed by JavaScript to exit from a script. Callback is passed as a last element in `arguments` array. Additional arguments can be passed as array in second parameter.
```
js
// wait for 1200 milliseconds my running `setTimeout`
* $I->executeAsyncJS('setTimeout(arguments[0], 1200)');
$seconds = 1200; // or seconds are passed as argument
$I->executeAsyncJS('setTimeout(arguments[1], arguments[0])', [$seconds]);
```
* `param` $script
* `param array` $arguments
### executeInSelenium
Low-level API method. If Codeception commands are not enough, this allows you to use Selenium WebDriver methods directly:
```
$I->executeInSelenium(function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
$webdriver->get('http://google.com');
});
```
This runs in the context of the [RemoteWebDriver class](https://github.com/php-webdriver/php-webdriver/blob/master/lib/remote/RemoteWebDriver.php). Try not to use this command on a regular basis. If Codeception lacks a feature you need, please implement it and submit a patch.
* `param callable` $function
### executeJS
Executes custom JavaScript.
This example uses jQuery to get a value and assigns that value to a PHP variable:
```
<?php
$myVar = $I->executeJS('return $("#myField").val()');
// additional arguments can be passed as array
// Example shows `Hello World` alert:
$I->executeJS("window.alert(arguments[0])", ['Hello world']);
```
* `param` $script
* `param array` $arguments
### fillField
Fills a text field or textarea with the given string.
```
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], '[email protected]');
?>
```
* `param` $field
* `param` $value
### grabAttributeFrom
Grabs the value of the given attribute value from the given element. Fails if element is not found.
```
<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
```
* `param` $cssOrXpath
* `param` $attribute
### grabCookie
Grabs a cookie value. You can set additional cookie params like `domain`, `path` in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try `$I->wait(0.1)`.
* `param` $cookie
* `param array` $params
### grabFromCurrentUrl
Executes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
```
<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
```
* `param string` $uri optional
### grabMultiple
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
```
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
```
```
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');
// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
```
* `param` $cssOrXpath
* `param` $attribute
* `return string[]`
### grabPageSource
Grabs current page source code.
@throws ModuleException if no page was opened.
* `return string` Current page source code.
### grabTextFrom
Finds and returns the text contents of the given element. If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.
```
<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
```
* `param` $cssOrXPathOrRegex
### grabValueFrom
Finds the value for the given form field. If a fuzzy locator is used, the field is found by field name, CSS, and XPath.
```
<?php
$name = $I->grabValueFrom('Name');
$name = $I->grabValueFrom('input[name=username]');
$name = $I->grabValueFrom('descendant-or-self::form/descendant::input[@name = 'username']');
$name = $I->grabValueFrom(['name' => 'username']);
?>
```
* `param` $field
### loadSessionSnapshot
Loads cookies from a saved snapshot. Allows to reuse same session across tests without additional login.
See [saveSessionSnapshot](#saveSessionSnapshot)
* `param` $name
### makeElementScreenshot
Takes a screenshot of an element of the current window and saves it to `tests/_output/debug`.
```
<?php
$I->amOnPage('/user/edit');
$I->makeElementScreenshot('#dialog', 'edit_page');
// saved to: tests/_output/debug/edit_page.png
$I->makeElementScreenshot('#dialog');
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.png
```
* `param` $name
### makeHtmlSnapshot
Use this method within an [interactive pause](../02-gettingstarted#Interactive-Pause) to save the HTML source code of the current page.
```
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
```
* `param null` $name
### makeScreenshot
Takes a screenshot of the current window and saves it to `tests/_output/debug`.
```
<?php
$I->amOnPage('/user/edit');
$I->makeScreenshot('edit_page');
// saved to: tests/_output/debug/edit_page.png
$I->makeScreenshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.png
```
* `param` $name
### maximizeWindow
Maximizes the current window.
### moveBack
Moves back in history.
### moveForward
Moves forward in history.
### moveMouseOver
Move mouse over the first element matched by the given locator. If the first parameter null then the page is used. If the second and third parameters are given, then the mouse is moved to an offset of the element’s top-left corner. Otherwise, the mouse is moved to the center of the element.
```
<?php
$I->moveMouseOver(['css' => '.checkout']);
$I->moveMouseOver(null, 20, 50);
$I->moveMouseOver(['css' => '.checkout'], 20, 50);
?>
```
* `param string` $cssOrXPath css or xpath of the web element
* `param int` $offsetX
* `param int` $offsetY
@throws \Codeception\Exception\ElementNotFound
### openNewTab
Opens a new browser tab and switches to it.
```
<?php
$I->openNewTab();
```
The tab is opened with JavaScript’s `window.open()`, which means:
* Some adblockers might restrict it.
* The sessionStorage is copied to the new tab (contrary to a tab that was manually opened by the user)
### performOn
Waits for element and runs a sequence of actions inside its context. Actions can be defined with array, callback, or `Codeception\Util\ActionSequence` instance.
Actions as array are recommended for simple to combine “waitForElement” with assertions; `waitForElement($el)` and `see('text', $el)` can be simplified to:
```
<?php
$I->performOn($el, ['see' => 'text']);
```
List of actions can be pragmatically build using `Codeception\Util\ActionSequence`:
```
<?php
$I->performOn('.model', ActionSequence::build()
->see('Warning')
->see('Are you sure you want to delete this?')
->click('Yes')
);
```
Actions executed from array or ActionSequence will print debug output for actions, and adds an action name to exception on failure.
Whenever you need to define more actions a callback can be used. A WebDriver module is passed for argument:
```
<?php
$I->performOn('.rememberMe', function (WebDriver $I) {
$I->see('Remember me next time');
$I->seeElement('#LoginForm_rememberMe');
$I->dontSee('Login');
});
```
In 3rd argument you can set number a seconds to wait for element to appear
* `param` $element
* `param` $actions
* `param int` $timeout
### pressKey
Presses the given key on the given element. To specify a character and modifier (e.g. `Ctrl`, Alt, Shift, Meta), pass an array for `$char` with the modifier as the first element and the character as the second. For special keys, use the constants from [`Facebook\WebDriver\WebDriverKeys`](https://github.com/php-webdriver/php-webdriver/blob/main/lib/WebDriverKeys.php).
```
<?php
// <input id="page" value="old" />
$I->pressKey('#page','a'); // => olda
$I->pressKey('#page',array('ctrl','a'),'new'); //=> new
$I->pressKey('#page',array('shift','111'),'1','x'); //=> old!!!1x
$I->pressKey('descendant-or-self::*[@id='page']','u'); //=> oldu
$I->pressKey('#name', array('ctrl', 'a'), \Facebook\WebDriver\WebDriverKeys::DELETE); //=>''
?>
```
* `param` $element
* `param` $char string|array Can be char or array with modifier. You can provide several chars. @throws \Codeception\Exception\ElementNotFound
### reloadPage
Reloads the current page.
### resetCookie
Unsets cookie with the given name. You can set additional cookie params like `domain`, `path` in array passed as last argument.
* `param` $cookie
* `param array` $params
### resizeWindow
Resize the current window.
```
<?php
$I->resizeWindow(800, 600);
```
* `param int` $width
* `param int` $height
### saveSessionSnapshot
Saves current cookies into named snapshot in order to restore them in other tests This is useful to save session state between tests. For example, if user needs log in to site for each test this scenario can be executed once while other tests can just restore saved cookies.
```
<?php
// inside AcceptanceTester class:
public function login()
{
// if snapshot exists - skipping login
if ($I->loadSessionSnapshot('login')) return;
// logging in
$I->amOnPage('/login');
$I->fillField('name', 'jon');
$I->fillField('password', '123345');
$I->click('Login');
// saving snapshot
$I->saveSessionSnapshot('login');
}
?>
```
* `param` $name
### scrollTo
Move to the middle of the given element matched by the given locator. Extra shift, calculated from the top-left corner of the element, can be set by passing $offsetX and $offsetY parameters.
```
<?php
$I->scrollTo(['css' => '.checkout'], 20, 50);
?>
```
* `param` $selector
* `param int` $offsetX
* `param int` $offsetY
### see
Checks that the current page contains the given string (case insensitive).
You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.
```
<?php
$I->see('Logout'); // I can suppose user is logged in
$I->see('Sign Up', 'h1'); // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1'); // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator
```
Note that the search is done after stripping all HTML tags from the body, so `$I->see('strong')` will return true for strings like:
* `<p>I am Stronger than thou</p>`
* `<script>document.createElement('strong');</script>`
But will *not* be true for strings like:
* `<strong>Home</strong>`
* `<div class="strong">Home</strong>`
* `<!-- strong -->`
For checking the raw source code, use `seeInSource()`.
* `param string` $text
* `param array|string` $selector optional
### seeCheckboxIsChecked
Checks that the specified checkbox is checked.
```
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
```
* `param` $checkbox
### seeCookie
Checks that a cookie with the given name is set. You can set additional cookie params like `domain`, `path` as array passed in last argument.
```
<?php
$I->seeCookie('PHPSESSID');
?>
```
* `param` $cookie
* `param array` $params
### seeCurrentUrlEquals
Checks that the current URL is equal to the given string. Unlike `seeInCurrentUrl`, this only matches the full URL.
```
<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
```
* `param string` $uri
### seeCurrentUrlMatches
Checks that the current URL matches the given regular expression.
```
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
```
* `param string` $uri
### seeElement
Checks that the given element exists on the page and is visible. You can also specify expected attributes of this element.
```
<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);
// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
```
* `param` $selector
* `param array` $attributes
### seeElementInDOM
Checks that the given element exists on the page, even it is invisible.
```
<?php
$I->seeElementInDOM('//form/input[type=hidden]');
?>
```
* `param` $selector
* `param array` $attributes
### seeInCurrentUrl
Checks that current URI contains the given string.
```
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
```
* `param string` $uri
### seeInField
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value. Fields are matched by label text, the “name” attribute, CSS, or XPath.
```
<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
```
* `param` $field
* `param` $value
### seeInFormFields
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
```
<?php
$I->seeInFormFields('form[name=myform]', [
'input1' => 'value',
'input2' => 'other value',
]);
?>
```
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
```
<?php
$I->seeInFormFields('.form-class', [
'multiselect' => [
'value1',
'value2',
],
'checkbox[]' => [
'a checked value',
'another checked value',
],
]);
?>
```
Additionally, checkbox values can be checked with a boolean.
```
<?php
$I->seeInFormFields('#form-id', [
'checkbox1' => true, // passes if checked
'checkbox2' => false, // passes if unchecked
]);
?>
```
Pair this with submitForm for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
* `param` $formSelector
* `param` $params
### seeInPageSource
Checks that the page source contains the given string.
```
<?php
$I->seeInPageSource('<link rel="apple-touch-icon"');
```
* `param` $text
### seeInPopup
Checks that the active JavaScript popup, as created by `window.alert`|`window.confirm`|`window.prompt`, contains the given string.
* `param` $text
@throws \Codeception\Exception\ModuleException
### seeInSource
Checks that the current page contains the given string in its raw source code.
```
<?php
$I->seeInSource('<h1>Green eggs & ham</h1>');
```
* `param` $raw
### seeInTitle
Checks that the page title contains the given string.
```
<?php
$I->seeInTitle('Blog - Post #1');
?>
```
* `param` $title
### seeLink
Checks that there’s a link with the specified text. Give a full URL as the second parameter to match links with that exact URL.
```
<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
```
* `param string` $text
* `param string` $url optional
### seeNumberOfElements
Checks that there are a certain number of elements matched by the given locator on the page.
```
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
```
* `param` $selector
* `param mixed` $expected int or int[]
### seeNumberOfElementsInDOM
**not documented**
### seeNumberOfTabs
Checks current number of opened tabs
```
<?php
$I->seeNumberOfTabs(2);
```
* `param` $number number of tabs
### seeOptionIsSelected
Checks that the given option is selected.
```
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
```
* `param` $selector
* `param` $optionText
### selectOption
Selects an option in a select tag or in radio button group.
```
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>
```
Provide an array for the second argument to select multiple options:
```
<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>
```
Or provide an associative array for the second argument to specifically define which selection method should be used:
```
<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
```
* `param` $select
* `param` $option
### setCookie
Sets a cookie with the given name and value. You can set additional cookie params like `domain`, `path`, `expires`, `secure` in array passed as last argument.
```
<?php
$I->setCookie('PHPSESSID', 'el4ukv0kqbvoirg7nkp4dncpk3');
?>
```
* `param` $name
* `param` $val
* `param array` $params
### submitForm
Submits the given form on the page, optionally with the given form values. Give the form fields values as an array. Note that hidden fields can’t be accessed.
Skipped fields will be filled by their values from the page. You don’t need to click the ‘Submit’ button afterwards. This command itself triggers the request to form’s action.
You can optionally specify what button’s value to include in the request with the last parameter as an alternative to explicitly setting its value in the second parameter, as button values are not otherwise included in the request.
Examples:
```
<?php
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
]);
// or
$I->submitForm('#login', [
'login' => 'davert',
'password' => '123456'
], 'submitButtonName');
```
For example, given this sample “Sign Up” form:
```
<form action="/sign_up">
Login:
<input type="text" name="user[login]" /><br/>
Password:
<input type="password" name="user[password]" /><br/>
Do you agree to our terms?
<input type="checkbox" name="user[agree]" /><br/>
Select pricing plan:
<select name="plan">
<option value="1">Free</option>
<option value="2" selected="selected">Paid</option>
</select>
<input type="submit" name="submitButton" value="Submit" />
</form>
```
You could write the following to submit it:
```
<?php
$I->submitForm(
'#userForm',
[
'user[login]' => 'Davert',
'user[password]' => '123456',
'user[agree]' => true
],
'submitButton'
);
```
Note that “2” will be the submitted value for the “plan” field, as it is the selected option.
Also note that this differs from PhpBrowser, in that
```
'user' => [ 'login' => 'Davert' ]
```
is not supported at the moment. Named array keys *must* be included in the name as above.
Pair this with seeInFormFields for quick testing magic.
```
<?php
$form = [
'field1' => 'value',
'field2' => 'another value',
'checkbox1' => true,
// ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
```
Parameter values must be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, either the string value can be used, or boolean values which will be replaced by the checkbox’s value in the DOM.
```
<?php
$I->submitForm('#my-form', [
'field1' => 'value',
'checkbox' => [
'value of first checkbox',
'value of second checkbox',
],
'otherCheckboxes' => [
true,
false,
false,
],
'multiselect' => [
'first option value',
'second option value',
]
]);
?>
```
Mixing string and boolean values for a checkbox’s value is not supported and may produce unexpected results.
Field names ending in “[]” must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:
```
$I->submitForm('#my-form', [
'field[]' => 'value',
'field[]' => 'another value', // 'field[]' is already a defined key
]);
```
The solution is to pass an array value:
```
// this way both values are submitted
$I->submitForm('#my-form', [
'field' => [
'value',
'another value',
]
]);
```
The `$button` parameter can be either a string, an array or an instance of Facebook\WebDriver\WebDriverBy. When it is a string, the button will be found by its “name” attribute. If $button is an array then it will be treated as a strict selector and a WebDriverBy will be used verbatim.
For example, given the following HTML:
```
<input type="submit" name="submitButton" value="Submit" />
```
`$button` could be any one of the following:
* ‘submitButton’
* [‘name’ => ‘submitButton’]
* WebDriverBy::name(‘submitButton’)
* `param` $selector
* `param` $params
* `param` $button
### switchToFrame
Switch to another frame on the page.
Example:
```
<frame name="another_frame" id="fr1" src="http://example.com">
```
```
<?php
# switch to frame by name
$I->switchToFrame("another_frame");
# switch to frame by CSS or XPath
$I->switchToFrame("#fr1");
# switch to parent page
$I->switchToFrame();
```
* `param string|null` $locator (name, CSS or XPath)
### switchToIFrame
Switch to another iframe on the page.
Example:
```
<iframe name="another_frame" id="fr1" src="http://example.com">
```
```
<?php
# switch to iframe by name
$I->switchToIFrame("another_frame");
# switch to iframe by CSS or XPath
$I->switchToIFrame("#fr1");
# switch to parent page
$I->switchToIFrame();
```
* `param string|null` $locator (name, CSS or XPath)
### switchToNextTab
Switches to next browser tab. An offset can be specified.
```
<?php
// switch to next tab
$I->switchToNextTab();
// switch to 2nd next tab
$I->switchToNextTab(2);
```
* `param int` $offset 1
### switchToPreviousTab
Switches to previous browser tab. An offset can be specified.
```
<?php
// switch to previous tab
$I->switchToPreviousTab();
// switch to 2nd previous tab
$I->switchToPreviousTab(2);
```
* `param int` $offset 1
### switchToWindow
Switch to another window identified by name.
The window can only be identified by name. If the $name parameter is blank, the parent window will be used.
Example:
```
<input type="button" value="Open window" onclick="window.open('http://example.com', 'another_window')">
```
```
<?php
$I->click("Open window");
# switch to another window
$I->switchToWindow("another_window");
# switch to parent window
$I->switchToWindow();
?>
```
If the window has no name, match it by switching to next active tab using `switchToNextTab` method.
Or use native Selenium functions to get access to all opened windows:
```
<?php
$I->executeInSelenium(function (\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
$handles=$webdriver->getWindowHandles();
$last_window = end($handles);
$webdriver->switchTo()->window($last_window);
});
?>
```
* `param string|null` $name
### type
Type in characters on active element. With a second parameter you can specify delay between key presses.
```
<?php
// activate input element
$I->click('#input');
// type text in active element
$I->type('Hello world');
// type text with a 1sec delay between chars
$I->type('Hello World', 1);
```
This might be useful when you an input reacts to typing and you need to slow it down to emulate human behavior. For instance, this is how Credit Card fields can be filled in.
* `param` $text
* `param` $delay [sec]
### typeInPopup
Enters text into a native JavaScript prompt popup, as created by `window.prompt`.
* `param` $keys
@throws \Codeception\Exception\ModuleException
### uncheckOption
Unticks a checkbox.
```
<?php
$I->uncheckOption('#notify');
?>
```
* `param` $option
### unselectOption
Unselect an option in the given select box.
* `param` $select
* `param` $option
### wait
Wait for $timeout seconds.
* `param int|float` $timeout secs @throws \Codeception\Exception\TestRuntimeException
### waitForElement
Waits up to $timeout seconds for an element to appear on the page. If the element doesn’t appear, a timeout exception is thrown.
```
<?php
$I->waitForElement('#agree_button', 30); // secs
$I->click('#agree_button');
?>
```
* `param` $element
* `param int` $timeout seconds @throws \Exception
### waitForElementChange
Waits up to $timeout seconds for the given element to change. Element “change” is determined by a callback function which is called repeatedly until the return value evaluates to true.
```
<?php
use \Facebook\WebDriver\WebDriverElement
$I->waitForElementChange('#menu', function(WebDriverElement $el) {
return $el->isDisplayed();
}, 100);
?>
```
* `param` $element
* `param \Closure` $callback
* `param int` $timeout seconds @throws \Codeception\Exception\ElementNotFound
### waitForElementClickable
Waits up to $timeout seconds for the given element to be clickable. If element doesn’t become clickable, a timeout exception is thrown.
```
<?php
$I->waitForElementClickable('#agree_button', 30); // secs
$I->click('#agree_button');
?>
```
* `param` $element
* `param int` $timeout seconds @throws \Exception
### waitForElementNotVisible
Waits up to $timeout seconds for the given element to become invisible. If element stays visible, a timeout exception is thrown.
```
<?php
$I->waitForElementNotVisible('#agree_button', 30); // secs
?>
```
* `param` $element
* `param int` $timeout seconds @throws \Exception
### waitForElementVisible
Waits up to $timeout seconds for the given element to be visible on the page. If element doesn’t appear, a timeout exception is thrown.
```
<?php
$I->waitForElementVisible('#agree_button', 30); // secs
$I->click('#agree_button');
?>
```
* `param` $element
* `param int` $timeout seconds @throws \Exception
### waitForJS
Executes JavaScript and waits up to $timeout seconds for it to return true.
In this example we will wait up to 60 seconds for all jQuery AJAX requests to finish.
```
<?php
$I->waitForJS("return $.active == 0;", 60);
?>
```
* `param string` $script
* `param int` $timeout seconds
### waitForText
Waits up to $timeout seconds for the given string to appear on the page.
Can also be passed a selector to search in, be as specific as possible when using selectors. waitForText() will only watch the first instance of the matching selector / text provided. If the given text doesn’t appear, a timeout exception is thrown.
```
<?php
$I->waitForText('foo', 30); // secs
$I->waitForText('foo', 30, '.title'); // secs
?>
```
* `param string` $text
* `param int` $timeout seconds
* `param string` $selector optional @throws \Exception
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.