Collections and data structures
Iteration
Sequential iteration is implemented using the function iterate
. The general for
cycle:
for i in iter # или "for i = iter"
# тело
end
converted to
next = iterate(iter)
while next !== nothing
(i, state) = next
# тело
next = iterate(iter, state)
end
The 'state` object can be anything. It must be selected appropriately for each iterable type. For more information about defining a custom iterable type, see the section of the manual devoted to the iteration interface.
#
Base.iterate
— Function
iterate(iter [, state]) -> Union{Nothing, Tuple{Any, Any}}
Continues iterator execution to get the next element. If there are no elements left, `nothing' is returned. Otherwise, the two-element tuple of the next element and the new iteration state are returned.
#
Base.IteratorSize
— Type
IteratorSize(itertype::Type) -> IteratorSize
Depending on the type of iterator, one of the following values is returned:
-
SizeUnknown()
, if the length (number of elements) cannot be determined in advance; -
HasLength()
in case of a fixed finite length; -
HasShape{N}()
if the length is known and a definition of the multidimensional shape is available (as for an array); in this case,N
should return the number of dimensions, and the functionaxes
is valid for an iterator; -
IsInfinite()
if the iterator outputs values indefinitely.
By default, the value (for iterators that do not define this function) is HasLength()'. That is, most iterators presumably implement `length
.
This type is generally used to choose between algorithms that pre-allocate space for the result and algorithms that progressively resize the result.
julia> Base.IteratorSize(1:5)
Base.HasShape{1}()
julia> Base.IteratorSize((2,3))
Base.HasLength()
#
Base.IteratorEltype
— Type
IteratorEltype(itertype::Type) -> IteratorEltype
Depending on the type of iterator, one of the following values is returned:
-
EltypeUnknown()
, if the type of elements returned by the iterator is unknown in advance; -
HasEltype()
, if the element type is known and 'eltype` returns a meaningful value.
HasEltype()
is used by default, because iterators presumably implement eltype
.
This type is generally used to choose between algorithms that pre-define a specific type of result and algorithms that select the type of result based on the types of values given.
julia> Base.IteratorEltype(1:5)
Base.HasEltype()
It is fully implemented by the following types:
Constructors and types
#
Base.AbstractRange
— Type
AbstractRange{T} <: AbstractVector{T}
A supertype for linear ranges containing elements of type T'. `UnitRange
, 'LinRange` and other types are subtypes of this type.
#
Base.OrdinalRange
— Type
OrdinalRange{T, S} <: AbstractRange{T}
A supertype for ordinal ranges containing elements of type T
with spaces of type S'. The steps should always be multiples of `oneunit
, and T
must be a "discrete" type that cannot contain values less than oneunit'. For example, the types `Integer
or Date' meet these requirements, but `Float64
does not (because this type can represent values less than oneunit(Float64)
). UnitRange
, StepRange
and other types are subtypes of this type.
#
Base.AbstractUnitRange
— Type
AbstractUnitRange{T} <: OrdinalRange{T, T}
Supertype for ranges with step size oneunit(T)
, containing elements of type T'. `UnitRange
and other types are subtypes of this type.
#
Base.StepRange
— Type
StepRange{T, S} <: OrdinalRange{T, S}
A supertype containing elements of type T
with a space of type S
. The step between the elements is a constant, and the range is defined in the context of start
and stop
of type T
and step
of type S
. Neither 'T` nor S
should belong to floating-point types. The syntax of a:b:c
c b != 0
and creates a StepRange
using integer algorithms a
, b
and `c'.
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}
#
Base.UnitRange
— Type
UnitRange{T<:Real}
The range parameterized by start
and stop
of type T
will be filled with elements separated by 1
from start' until `stop
is exceeded. The syntax of a:b
with a
and b
(both Integer
) 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}
#
Base.LinRange
— Type
LinRange{T,L}
A range with len
linearly spaced elements between start
and stop'. The size of the interval is controlled by the `len
argument, 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
In comparison with range
with the direct construction of LinRange
, the overhead will be lower, but floating-point errors are not corrected.
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
Also, see the function description. `Logrange' for points with logarithmic intervals.
Shared collections
#
Base.isempty
— Function
isempty(collection) -> Bool
Determines whether the collection is empty (contains no elements).
|
Examples
julia> isempty([])
true
julia> isempty([1 2 3])
false
isempty(condition)
Returns true
if there are no tasks waiting to be processed according to the condition, otherwise it returns `false'.
#
Base.isdone
— Function
isdone(itr, [state]) -> Union{Bool, Missing}
This function provides an indication of a fast path to end the iterator. This is useful for stateful iterators, whose elements should not be used if they are not available to the user (for example, when checking readiness in isempty
or `zip').
For stateful iterators that require this capability, the isdone
method should be defined, which returns true or false depending on whether the iterator is completed. Stateless iterators do not need to implement this feature.
If the result is missing
, the caller can continue execution and calculate iterate(x, state) === nothing
to get a specific response.
#
Base.empty!
— Function
empty!(collection) -> collection
Deletes all items from the `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}()
empty!(c::Channel)
Clears the 'c` channel by calling empty!
for the internal buffer. Returns an empty channel.
#
Base.checked_length
— Function
Base.checked_length(r)
Calculates the length(r)
, but can check for overflow errors if necessary if the result does not fit in the Union{Integer(eltype(r)),Int}
.
It is fully implemented by the following types:
Iterable collections
#
Base.in
— Function
in(item, collection) -> Bool
∈(item, collection) -> Bool
Determines whether an item is included in the given collection (that is, it is ==
to one of the values created by iterating the collection). Returns the value of Bool
, except when item
is equal to missing
or when collection
contains missing
but not item
(in this case, missing
is returned, meaning it applies https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic], which corresponds to the behavior any
and ==
).
For some collections, a slightly different definition is used. For example, Set
checks whether (isequal
) element to one of the elements. Dict
searches for pairs of key=>value
and matches the key (key
) using isequal
.
To check for a key in the dictionary, use haskey
or `k in keys(dict)'. For the above collections, the result is always `Bool'.
In the case of a broadcast using in.(items, collection)
or items .∈ collection
both item
and collection
are broadcast, although this result is often undesirable. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each of the values in the items
collection is included in the value at the corresponding position in the collection'. To get a vector indicating for each of the values in `items
whether it is included in the collection
, enclose collection
in a tuple or Ref
as follows: 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> (1=>missing) in Dict(1=>10, 2=>20)
missing
julia> [1, 2] .∈ [2, 3]
2-element BitVector:
0
0
julia> [1, 2] .∈ ([2, 3],)
2-element BitVector:
0
1
#
Base.:∉
— Function
∉(item, collection) -> Bool
∌(collection, item) -> Bool
Negating ∈
and ∋
, that is, it checks that item
is not included in the collection
.
In the case of broadcasting using items .∉ collection
both item
and collection
are broadcast, although this result is often undesirable. For example, if both arguments are vectors (and the sizes match), the result is a vector indicating for each of the values in the items
collection that it is not included in the value at the corresponding position in the collection
. To get a vector indicating that each of the values in items
is not included in the collection
, enclose collection
in a tuple or Ref
as follows: 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
#
Base.hasfastin
— Function
Base.hasfastin(T)
Defines the calculation of x ∈ collection
, where collection::T
can be considered a "fast" operation (usually with constant or logarithmic complexity). For convenience, it is accepted that hasfastin(x) = hasfastin(typeof(x))
so that instances can be passed instead of types. However, for new types, it is necessary to define a form that accepts the type argument.
The default value for hasfastin(T)
is true
for subtypes AbstractSet
, AbstractDict
and AbstractRange
and false
otherwise.
#
Base.eltype
— Function
eltype(type)
Defines the type of items created by iterating through a collection of this type type'. For dictionary types, a `Pair' is used.{KeyType,ValType}
. For convenience, it is accepted that eltype(x) = eltype(typeof(x))
so that instances can be passed instead of types. However, for new types, it is necessary to define a form that accepts the type argument.
Examples
julia> eltype(fill(1f0, (2,2)))
Float32
julia> eltype(fill(0x1, (2,2)))
UInt8
#
Base.indexin
— Function
indexin(a, b)
Returns an array that contains the first index in b
for each value in a
that is a member of b'. The output array contains `nothing
in all cases where a
is not a member of `b'.
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
#
Base.unique
— Function
unique(itr)
Returns an array that contains only the unique elements of the itr
collection according to the definition isequal
and hash
in the order in which the first element from each set of equivalent elements is initially located. The input data element type is saved.
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
unique(f, itr)
Returns an array that contains one value from the itr
for each unique value created when applying the f
function to the itr
elements.
Examples
julia> unique(x -> x^2, [1, -1, 3, -3, 4])
3-element Vector{Int64}:
1
3
4
You can also use this function to get the index of the first occurrences of unique elements in an array.:
julia> a = [3.1, 4.2, 5.3, 3.1, 3.1, 3.1, 4.2, 1.7];
julia> i = unique(i -> a[i], eachindex(a))
4-element Vector{Int64}:
1
2
3
8
julia> a[i]
4-element Vector{Float64}:
3.1
4.2
5.3
1.7
julia> a[i] == unique(a)
true
unique(A::AbstractArray; dims::Int)
Returns the unique regions A
over the entire length of the dims
dimension.
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
#
Base.unique!
— Function
unique!(f, A::AbstractVector)
Selects one value from A
for each unique value created when applying the function f
to the elements of A
, and then returns the modified A.
Compatibility: Julia 1.1
This method was first implemented in 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
unique!(A::AbstractVector)
Removes duplicate elements defined using isequal
and hash
, and then returns the modified A'. `unique!
returns the elements of A
in the order in which they appear. If the order of the returned data does not matter, call (sort!(A); unique!(A))`will be much more efficient because 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! может обрабатывать отсортированные данные гораздо эффективнее.
julia> unique!(B)
3-element Vector{Int64}:
6
7
42
#
Base.allunique
— Function
allunique(itr) -> Bool
allunique(f, itr) -> Bool
Returns true
if all values from itr' are clearly distinguishable when compared with `isequal
or if all [f(x) for x in itr]
are distinguishable in the case of the second method.
Note that allunique(f, itr)
may cause f
to be less than `length(itr)`one time. The exact number of calls depends on the implementation.
If the input data is sorted, allunique
can use a special implementation.
Compatibility: Julia 1.11
For the |
Examples
julia> allunique([1, 2, 3])
true
julia> allunique([1, 2, 1, 2])
false
julia> allunique(Real[1, 1.0, 2])
false
julia> allunique([NaN, 2.0, NaN, 4.0])
false
julia> allunique(abs, [1, -1, 2])
false
#
Base.allequal
— Function
allequal(itr) -> Bool
allequal(f, itr) -> Bool
Returns true
if all values from itr' are equal when compared using `isequal
or if all [f(x) for x in itr]
are equal in the case of the second method.
Note that 'allequal(f, itr)` may cause f
to be less than `length(itr)`one time. The exact number of calls depends on the implementation.
Compatibility: Julia 1.8
The "allequal` function requires a Julia version of at least 1.8. |
Compatibility: Julia 1.11
For the method |
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
julia> allequal(abs2, [1, -1])
true
#
Base.reduce
— Method
reduce(op, itr; [init])
Reduces the 'itr` collection to a simpler form using the specified binary operator op'. If the initial value of `init' is specified, it must be a neutral element for `op
, which is returned for empty collections. It is not specified whether init
is used for non-empty collections.
For empty collections, in some cases it is necessary to specify init
(for example, if op
is one of the operators +
, *
, ` max`, min
, &
, |
), when Julia can identify a neutral element op
.
The operations of reducing to a simpler form for certain common operators may have special implementations, which in this case should be used.: maximum
(itr)
, minimum
(itr)
, sum
(itr)
, prod
(itr)
, any
(itr)
, all
(itr)
. There are effective methods for concatenating certain arrays of arrays by calling reduce(``vcat
, arr)`or `reduce(``hcat
, arr)
.
The associativity of the reduction operation to a simpler form does not depend on the implementation. This means that non-associative operations such as -
cannot be used, because it has not been determined whether to calculate reduce(-,[1,2,3])
as (1-2)-3
or 1-(2-3)
. Instead, use foldl
or foldr
for guaranteed left-to-right or right-to-left associativity.
Errors accumulate in some operations. Parallelism is easier to use if you can perform the reduction to a simpler form in groups. In future versions of Julia, the algorithm may be changed. Note that if an ordered collection is used, the order of the elements does not change.
Examples
julia> reduce(*, [2; 3; 4])
24
julia> reduce(*, [2; 3; 4]; init=-1)
-24
#
Base.reduce
— Method
reduce(f, A::AbstractArray; dims=:, [init])
Reduces the function f
with two arguments by the dimensions of A'. `dims
is a vector indicating the dimensions to be abbreviated, and the named argument init
is the initial value to use in abbreviations. For +
, *
, ` The 'max` and min
arguments of `init' are optional.
The associativity of the reduction to a simpler form depends on the implementation. If you need a specific associativity, for example from left to right, you should write your own loop or consider using foldl
or foldr
. See the documentation for reduce
.
Examples
julia> a = 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> reduce(max, a, dims=2)
4×1 Matrix{Int64}:
13
14
15
16
julia> reduce(max, a, dims=1)
1×4 Matrix{Int64}:
4 8 12 16
#
Base.foldl
— Method
foldl(op, itr; [init])
Similarly reduce
, but with guaranteed left-to-right associativity. If the named argument init
is specified, it will be used exactly once. As a rule, to work with empty collections, you must specify `init'.
See also the description mapfoldl
, foldr
and 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)
#
Base.foldr
— Method
foldr(op, itr; [init])
Similarly reduce
, but with guaranteed right-to-left associativity. If the named argument init
is specified, it will be used exactly once. As a rule, to work with empty collections, you must specify `init'.
Examples
julia> foldr(=>, 1:4)
1 => (2 => (3 => 4))
julia> foldr(=>, 1:4; init=0)
1 => (2 => (3 => (4 => 0)))
#
Base.maximum
— Function
maximum(f, itr; [init])
Returns the highest result of calling the f
function for each itr
element.
The value returned for an empty itr' can be specified in `init
. This should be a neutral element for max' (that is, an element that is smaller than or equal to any other element), since it is not specified whether `init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> maximum(length, ["Julion", "Julia", "Jule"])
6
julia> maximum(length, []; init=-1)
-1
julia> maximum(sin, Real[]; init=-1.0) # is good because the output is sin >= -1
-1.0
maximum(itr; [init])
Returns the largest item in the collection.
The value returned for an empty itr' can be specified in `init
. This should be a neutral element for max' (that is, an element that is smaller than or equal to any other element), since it is not specified whether `init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> maximum(-20.5:10)
9.5
julia> maximum([1,2,3])
3
julia> maximum(())
ERROR: ArgumentError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
[...]
julia> maximum((); init=-Inf)
-Inf
maximum(A::AbstractArray; dims)
Calculates the maximum value of an array based on the specified dimensions. See also the function description max(a,b)
, which returns the maximum of two (or more) arguments and can be applied to arrays element-by-element using max.(a,b)
.
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
maximum(f, A::AbstractArray; dims)
Calculates the maximum value by calling the function f
for each element of the array according to the specified 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
#
Base.maximum!
— Function
maximum!(r, A)
Calculates the maximum value of A
from individual measurements of r
and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.minimum
— Function
minimum(f, itr; [init])
Returns the smallest result of calling the f
function for each itr
element.
The value returned for an empty itr' can be specified in `init
. This should be a neutral element for min' (that is, an element that is greater than or equal to any other element), since it is not specified whether `init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> minimum(length, ["Julion", "Julia", "Jule"])
4
julia> minimum(length, []; init=typemax(Int64))
9223372036854775807
julia> minimum(sin, Real[]; init=1.0) # хороший, поскольку вывод sin <= 1
1.0
minimum(itr; [init])
Returns the smallest item in the collection.
The value returned for an empty itr' can be specified in `init
. This should be a neutral element for min' (that is, an element that is greater than or equal to any other element), since it is not specified whether `init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> minimum(-20.5:10)
-20.5
julia> minimum([1,2,3])
1
julia> minimum([])
ERROR: ArgumentError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
[...]
julia> minimum([]; init=Inf)
Inf
minimum(A::AbstractArray; dims)
Calculates the minimum value of an array based on the specified dimensions. See also the function description min(a,b)
, which returns the minimum of two (or more) arguments and can be applied to arrays element-by-element using min.(a,b)
.
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
minimum(f, A::AbstractArray; dims)
Calculates the minimum value by calling the function f
for each element of the array according to the specified 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
#
Base.minimum!
— Function
minimum!(r, A)
Calculates the minimum value of A
from individual measurements of r
and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.extrema
— Function
extrema(itr; [init]) -> (mn, mx)
Calculates both the minimum (mn
) and maximum (mx
) elements in one pass, returning them as a two-element tuple.
The value returned for an empty itr' can be specified in `init
. It should be a two-element tuple in which the first and second elements are neutral for min
and max
respectively (that is, greater/less than or equal to any other element). As a consequence, if itr
is empty, the returned tuple (mn, mx)
matches the condition mn ≥ mx'. If the `init
argument is set, it can be used even for non-empty `itrs'.
Compatibility: Julia 1.8
The named |
Examples
julia> extrema(2:10)
(2, 10)
julia> extrema([9,pi,4.5])
(3.141592653589793, 9.0)
julia> extrema([]; init = (Inf, -Inf))
(Inf, -Inf)
extrema(f, itr; [init]) -> (mn, mx)
Calculates both the minimum (mn
) and maximum (mx
) result of applying the function f
to each element in itr
and returns them as a two-element tuple. Performs only one pass of the `itr'.
The value returned for an empty itr' can be specified in `init
. It should be a two-element tuple in which the first and second elements are neutral for min
and max
, respectively (that is, greater than/less than or equal to any other element). Used for non-empty collections. Note. It is assumed that for empty itrs
the return value (mn, mx)
corresponds to the condition mn ≥ mx
, even though for non-empty itrs
it corresponds to the condition mn ≤ mx
. This is a "paradoxical" but expected result.
Compatibility: Julia 1.2
This method requires a Julia version of at least 1.2. |
Compatibility: Julia 1.8
The named |
Examples
julia> extrema(sin, 0:π)
(0.0, 0.9092974268256817)
julia> extrema(sin, Real[]; init = (1.0, -1.0)) # хороший, поскольку –1 ≤ sin(::Real) ≤ 1
(1.0, -1.0)
extrema(A::AbstractArray; dims) -> Array{Tuple}
Calculates the minimum and maximum array elements based on the specified dimensions.
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)
extrema(f, A::AbstractArray; dims) -> Array{Tuple}
Calculates both the minimum and maximum result of applying the function f
to each element in the given dimensions `A'.
Compatibility: Julia 1.2
This method requires a Julia version of at least 1.2. |
#
Base.extrema!
— Function
extrema!(r, A)
Calculates the minimum and maximum value of A
from individual measurements of r
and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
Compatibility: Julia 1.8
This method requires a Julia version of at least 1.8. |
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)
#
Base.argmax
— Function
argmax(r::AbstractRange)
Ranges can contain multiple maximum elements. In this case, `argmax' returns the maximum index, but not necessarily the first one.
argmax(f, domain)
Returns the value x
from the domain
for which f(x)
is maximized. If multiple maximum values for f(x)
are available, the first value will be found.
The domain
must be a non-empty iterable collection.
The values are compared using `isless'.
Compatibility: Julia 1.7
This method requires a version of Julia at least 1.7. |
Examples
julia> argmax(abs, -10:5)
-10
julia> argmax(cos, 0:π/2:2π)
0.0
argmax(itr)
Returns the index or key of the maximum element in the collection. If multiple maximum elements are available, the first value will be returned.
The collection should not be empty.
The indexes are of the same type as the indexes returned by the methods. keys(itr)
and pairs(itr)
.
The values are compared using `isless'.
Examples
julia> argmax([8, 0.1, -9, pi])
1
julia> argmax([1, 7, 7, 6])
2
julia> argmax([1, 7, 7, NaN])
4
argmax(A; dims) -> indices
Returns the indexes of the maximum elements for the specified dimensions for the input data of the array. The value 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)
#
Base.argmin
— Function
argmin(r::AbstractRange)
Ranges can contain several minimum elements. In this case, `argmin' returns the minimum index, but not necessarily the first one.
argmin(f, domain)
Returns the value of x
from domain', for which `f(x)
is minimized. If there are multiple minimum values available for f(x)
, then the first value will be found.
domain
must be a non-empty iterable collection.
The value NaN
is treated as lower than all other values except `missing'.
Compatibility: Julia 1.7
This method requires a version of Julia at least 1.7. |
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
argmin(itr)
Returns the index or key of the minimum element in the collection. If several minimum elements are available, the first value will be returned.
The collection should not be empty.
The indexes are of the same type as the indexes returned by the methods. keys(itr)
and pairs(itr)
.
The value NaN
is treated as lower than all other values except `missing'.
Examples
julia> argmin([8, 0.1, -9, pi])
3
julia> argmin([7, 1, 1, 6])
2
julia> argmin([7, 1, 1, NaN])
4
argmin(A; dims) -> indices
For the input data of the array, it returns the indexes of the minimum elements according to the specified dimensions. The value NaN
is treated as lower 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)
#
Base.findmax
— Function
findmax(f, domain) -> (f(x), index)
Returns a pair consisting of the value in the domain (output data f
) at which f(x)
is maximized, and the index or key of this value in the domain' (input data for `f
). If multiple maximum points are available, the first value will be returned.
domain
must be a non-empty iterable collection that supports keys
. The indexes are of the same type as the indexes returned by the method. keys(domain)
.
The values are compared using `isless'.
Compatibility: Julia 1.7
This method requires a version of Julia at least 1.7. |
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)
findmax(itr) -> (x, index)
Returns the maximum element of the itr
collection and its index or key. If multiple maximum elements are available, the first value will be returned. The values are compared using `isless'.
The indexes are of the same type as the indexes returned by the methods. keys(itr)
and pairs(itr)
.
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)
findmax(A; dims) -> (maxval, index)
Returns the maximum value and index for the specified dimensions for the input data of the array. The value 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);;])
findmax(f, A; dims) -> (f(x), index)
For the input data of the array, it returns the value in the range of values at which f
is maximized by the specified dimensions, and its index.
Examples
julia> A = [-1.0 1; -0.5 2]
2×2 Matrix{Float64}:
-1.0 1.0
-0.5 2.0
julia> findmax(abs2, A, dims=1)
([1.0 4.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(2, 2)])
julia> findmax(abs2, A, dims=2)
([1.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 2);;])
#
Base.findmin
— Function
findmin(f, domain) -> (f(x), index)
Returns a pair consisting of a value in the domain (output data f
), at which f(x)
is minimized, and the index or key of this value in the domain' (input data for `f
). If several minimum points are available, the first value will be returned.
The domain
must be a non-empty iterable collection.
The indexes are of the same type as the indexes returned by the methods. keys(domain)
and pairs(domain)
.
The value NaN
is treated as lower than all other values except `missing'.
Compatibility: Julia 1.7
This method requires a version of Julia at least 1.7. |
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)
findmin(itr) -> (x, index)
Returns the minimum element of the itr
collection and its index or key. If several minimum elements are available, the first value will be returned. The value NaN
is treated as lower than all other values except `missing'.
The indexes are of the same type as the indexes returned by the methods. keys(itr)
and pairs(itr)
.
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)
findmin(A; dims) -> (minval, index)
Returns the minimum value and index for the specified dimensions for the input data of the array. The value NaN
is treated as lower 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);;])
findmin(f, A; dims) -> (f(x), index)
For the input data of the array, it returns a value in the range of values at which f
is minimized by the specified dimensions, and its index.
Examples
julia> A = [-1.0 1; -0.5 2]
2×2 Matrix{Float64}:
-1.0 1.0
-0.5 2.0
julia> findmin(abs2, A, dims=1)
([0.25 1.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(1, 2)])
julia> findmin(abs2, A, dims=2)
([1.0; 0.25;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])
#
Base.findmax!
— Function
findmax!(rval, rind, A) -> (maxval, index)
Finds the maximum of A
and the corresponding linear index for the individual dimensions rval
and rind
, storing the results in rval
and rind'. The value `NaN
is treated as greater than all other values except `missing'.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
#
Base.findmin!
— Function
findmin!(rval, rind, A) -> (minval, index)
Finds the minimum A
and the corresponding linear index for the individual dimensions rval
and rind
, storing the results in rval
and rind'. The value `NaN
is treated as lower than all other values except `missing'.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
#
Base.sum
— Function
sum(f, itr; [init])
Summarizes the results of the calling function f
for each element of `itr'.
For signed integers less than the size of the system word, the type Int
is returned, and for unsigned integers less than the size of the system word, the type `UInt'. For the remaining arguments, there is a common return type to which all arguments are promoted.
The value returned for an empty itr' can be specified in `init
. This must be the zero element for the addition operation (for example, zero), since it is not specified whether init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> sum(abs2, [2; 3; 4])
29
Note the important difference between sum(A)
and reduce(+, A)
for arrays with a small integer type eltype.
julia> sum(Int8[100, 28])
128
julia> reduce(+, Int8[100, 28])
-128
In the first case, the integer values are expanded to the size of the system word, and thus the result is 128. In the second case, no such expansion occurs, and overflow of the integer value yields the result --128.
sum(itr; [init])
Returns the sum of all the items in the collection.
For signed integers less than the size of the system word, the type Int
is returned, and for unsigned integers less than the size of the system word, the type `UInt'. For the remaining arguments, there is a common return type to which all arguments are promoted.
The value returned for an empty itr' can be specified in `init
. This must be the zero element for the addition operation (for example, zero), since it is not specified whether init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> sum(1:20)
210
julia> sum(1:20; init = 0.0)
210.0
sum(A::AbstractArray; dims)
Summarizes the elements of the array according to the specified 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
sum(f, A::AbstractArray; dims)
Summarizes the results of calling the function f
for each element of the array according to the specified 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
#
Base.sum!
— Function
sum!(r, A)
Summarizes the elements of A
by individual dimensions of r
and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.prod
— Function
prod(f, itr; [init])
Returns the product of f
and each element of `itr'.
For signed integers less than the size of the system word, the type Int
is returned, and for unsigned integers less than the size of the system word, the type `UInt'. For the remaining arguments, there is a common return type to which all arguments are promoted.
The value returned for an empty itr' can be specified in `init
. This must be a single multiplication element (for example, one), since it is not specified whether init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> prod(abs2, [2; 3; 4])
576
prod(itr; [init])
Returns the product of all the items in the collection.
For signed integers less than the size of the system word, the type Int
is returned, and for unsigned integers less than the size of the system word, the type `UInt'. For the remaining arguments, there is a common return type to which all arguments are promoted.
The value returned for an empty itr' can be specified in `init
. This must be a single multiplication element (for example, one), since it is not specified whether init
is used for non-empty collections.
Compatibility: Julia 1.6
The named |
Examples
julia> prod(1:5)
120
julia> prod(1:5; init = 1.0)
120.0
prod(A::AbstractArray; dims)
Multiplies the array elements by the specified 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
prod(f, A::AbstractArray; dims)
Multiplies the results of calling the function f
for each element of the array by the specified 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
#
Base.prod!
— Function
prod!(r, A)
Multiplies the elements of A
by individual dimensions of r
and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.any
— Method
any(itr) -> Bool
Checks whether any elements of the logical collection are true
, returning true
as soon as the first value of true
in the 'itr' is detected (calculation according to the abbreviated scheme). To calculate false
using the abbreviated scheme, use all
.
If the input data contains the values missing
, missing
is returned provided that all non-missing values are false
(and the same if the input data does not contain the value true
), according to https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic].
See also the description |
), [ |
). |
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
#
Base.any
— Method
any(p, itr) -> Bool
Determines whether the predicate p
returns the value true
for any elements of the itr
, returning true
as soon as the first element in the itr
is found for which p
returns true' (calculation according to an abbreviated scheme). To calculate `false
using the abbreviated scheme, use all
.
If the input data contains the values missing
, missing
is returned provided that all non-missing values are false
(and the same if the input data does not contain the value true
), according to https://en.wikipedia.org/wiki/Three-valued_logic [ternary 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
#
Base.any!
— Function
any!(r, A)
Checks whether any values in A
for individual measurements of r
are equal to true
, and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.all
— Method
all(itr) -> Bool
Checks whether all the elements of the logical collection are true
, returning false
as soon as the first value of false
in the 'itr' is detected (calculation according to the abbreviated scheme). To calculate true
using the abbreviated scheme, use any
.
If the input data contains the values missing
, missing
is returned provided that all non-missing values are true
(and the same if the input data does not contain the value false
), according to https://en.wikipedia.org/wiki/Three-valued_logic [ternary logic].
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
#
Base.all
— Method
all(p, itr) -> Bool
Determines whether the predicate p
returns the value true
for all elements of itr
, returning false
as soon as the first element in itr
is found, for which p
returns false' (calculation according to the abbreviated scheme). To calculate `true
using the abbreviated scheme, use any
.
If the input data contains the values missing
, missing
is returned provided that all non-missing values are true
(and the same if the input data does not contain the value false
), according to https://en.wikipedia.org/wiki/Three-valued_logic [ternary 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
#
Base.all!
— Function
all!(r, A)
Checks whether all values in A
for individual measurements of r
are true
, and writes the results to r
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.count
— Function
count([f=identity,] itr; init=0) -> Integer
Counts the number of elements in the itr
for which the function f
returns true'. If 'f
is skipped, the number of true
elements in the itr
is counted (which should be a collection of boolean values). 'init` additionally specifies the value from which the counting starts, and thus also determines the type of output.
Compatibility: Julia 1.6
The named |
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
count( pattern::Union{AbstractChar,AbstractString,AbstractPattern}, string::AbstractString; overlap::Bool = false, )
Returns the number of matches from pattern
to string'. This is equivalent to calling `length(findall(pattern, string))
, but more efficient.
With overlap=true
, matching sequences are allowed to overlap with the indexes in the source string, otherwise they must be from disparate character ranges.
Compatibility: Julia 1.3
This method requires a Julia version of 1.3 or higher. |
Compatibility: Julia 1.7
To use a symbol as a template, a Julia version of at least 1.7 is required. |
Examples
julia> count('a', "JuliaLang")
2
julia> count(r"a(.)a", "cabacabac", overlap=true)
3
julia> count(r"a(.)a", "cabacabac")
2
count([f=identity,] A::AbstractArray; dims=:)
Counts the number of elements in A
for which the function f
returns true
according to the specified measurements.
Compatibility: Julia 1.5
The named argument `dims' was added in Julia 1.5. |
Compatibility: Julia 1.6
The named |
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
#
Base.foreach
— Function
foreach(f, c...) -> Nothing
Calls the function f
for each element of the iterated object c'. If there are several iterable arguments, an element-wise call to `f
is performed and iterations stop at the end of any iterator.
foreach
should be used instead of map
, if the results of f
are not required, 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
#
Base.map
— Function
map(f, c...) -> collection
Transforms the collection c
by applying f
to each element. If multiple collection arguments are specified, f
is applied piecemeal and the procedure is terminated when any of them is exhausted.
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
map(f, A::AbstractArray...) -> N-array
When performing actions with multidimensional arrays of the same dimension ndims
they must have the same axes axes
, and the result will have the same ones.
See also the function description broadcast
, which allows size mismatch.
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)) # выполняет итерацию вплоть до исчерпания третьей коллекции 3-element Vector{Float64}: 2.0 13.0 102.0
#
Base.map!
— Function
map!(function, destination, collection...)
Similarly map
, but the result is saved in the destination', not in the new collection. The `destination
must be at least the size of the smallest collection.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
map!(f, values(dict::AbstractDict))
Modifies the dict
by converting each of the values 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 dict
, then it is converted to the value type if possible; otherwise, an error is returned.
Compatibility: Julia 1.2
For |
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
#
Base.mapreduce
— Method
mapreduce(f, op, itrs...; [init])
Applies the function f
to each element in itrs', and then reduces the result to a simpler form using the binary function `op'. If the value `init' is specified, it must be a neutral element for `op
, which is returned for empty collections. It is not specified whether init
is used for non-empty collections. As a rule, to work with empty collections, you must specify `init'.
mapreduce
is functionally equivalent to calling reduce(op, map(f, itr); init=init)
, but is generally faster because it does not require creating an intermediate collection. See the documentation for reduce
and map
.
Compatibility: Julia 1.2
For 'mapreduce` with multiple iterators, a Julia version of at least 1.2 is required. |
Examples
julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9
14
The associativity of the reduction to a simpler form depends on the implementation. In addition, some implementations may reuse the return value f
, which appears several times in itr'. Use instead `mapfoldl
or mapfoldr
for guaranteed left-to-right or right-to-left associativity and calling f
for each of the values.
#
Base.first
— Function
first(coll)
Retrieves the first element of the iterated collection. Returns the starting point of the range AbstractRange
, even if it is empty.
See also the description only
, firstindex
, last
.
Examples
julia> first(2:2:10)
2
julia> first([1; 2; 3; 4])
1
first(itr, n::Integer)
Retrieves the first n
elements of the iterated itr
collection, or fewer elements if the itr
is not long enough.
See also the description startswith
, Iterators.take
.
Compatibility: Julia 1.6
This method requires a Julia version at least 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[]
first(s::AbstractString, n::Integer)
Returns a string consisting of the first n
characters of the string s
.
Examples
julia> first("∀ϵ≠0: ϵ²>0", 0)
""
julia> first("∀ϵ≠0: ϵ²>0", 1)
"∀"
julia> first("∀ϵ≠0: ϵ²>0", 3)
"∀ϵ≠"
#
Base.last
— Function
last(coll)
Gets the last element of the ordered collection if it can be calculated in O(1) time. This is achieved by calling lastindex
in order to get the latest index. Returns the end point of the range AbstractRange
, even if it is empty.
Examples
julia> last(1:2:10)
9
julia> last([1; 2; 3; 4])
4
last(itr, n::Integer)
Retrieves the last n
elements of the iterated itr
collection, or fewer elements if the itr
is not long enough.
Compatibility: Julia 1.6
This method requires a Julia version of at least 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[]
last(s::AbstractString, n::Integer)
Returns a string consisting of the last n
characters of the string s
.
Examples
julia> last("∀ϵ≠0: ϵ²>0", 0)
""
julia> last("∀ϵ≠0: ϵ²>0", 1)
"0"
julia> last("∀ϵ≠0: ϵ²>0", 3)
"²>0"
#
Base.tail
— Function
tail(x::Tuple)::Tuple
Returns the tuple `Tuple', which includes all the components of `x' except the first one.
See also the description front
, rest
, first
, Iterators.peel
.
Examples
julia> Base.tail((1,2,3))
(2, 3)
julia> Base.tail(())
ERROR: ArgumentError: Cannot call tail on an empty tuple.
#
Base.step
— Function
step(r)
Gets the step size for the object AbstractRange
.
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
#
Base.collect
— Method
collect(collection)
Returns an array with all the elements in the collection or iterator. For dictionaries, returns a vector of Vector
pairs Pair
key=>value
. If the argument is similar to an array or is an iterator with the type 'HasShape`, the result will have the same shape and the same number of dimensions as the argument.
Is used inclusions for conversion generator expressions in Array'. Thus, _ in generators, you can use the entry in square brackets instead of calling `collect
; see the second example.
Examples
Collecting items from the collection UnitRange{Int64}
:
julia> collect(1:3)
3-element Vector{Int64}:
1
2
3
Collecting elements from the generator (same result as for [x^2 for x in 1:3]
):
julia> collect(x^2 for x in 1:3)
3-element Vector{Int64}:
1
4
9
#
Base.collect
— Method
collect(element_type, collection)
Returns an array with the given element type, containing all the elements of the collection or the object being iterated. The result has the same shape and the same number of dimensions as the `collection'.
Examples
julia> collect(Float64, 1:2:5)
3-element Vector{Float64}:
1.0
3.0
5.0
#
Base.filter
— Function
filter(f, a)
Returns a copy of the collection a
, deleting the elements for which f
is false'. The function `f
is passed a single argument.
Compatibility: Julia 1.4
To support |
See also the description filter!
, Iterators.filter
.
Examples
julia> a = 1:10
1:10
julia> filter(isodd, a)
5-element Vector{Int64}:
1
3
5
7
9
filter(f)
Creates a function that filters its arguments using the f
function using filter
, i.e. a function equivalent to x -> filter(f, x)
.
The returned function is of type Base.Fix1{typeof(filter)}
and can be used to implement specialized methods.
Examples
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)
(1, 2, 4, 6)
julia> map(filter(iseven), [1:3, 2:4, 3:5])
3-element Vector{Vector{Int64}}:
[2]
[2, 4]
[4]
Compatibility: Julia 1.9
This method requires a Julia version of at least 1.9. |
filter(f, d::AbstractDict)
Returns a copy of d
, deletes the elements for which f
is false'. The `+key⇒value+
pairs are passed to the `f' function.
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"
filter(f, itr::SkipMissing{<:AbstractArray})
Returns a vector similar to the array enclosed in the specified iterator SkipMissing
, but all missing elements, as well as elements for which f
returns the value false
, are deleted.
Compatibility: Julia 1.2
This method requires a Julia version of at least 1.2. |
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
#
Base.filter!
— Function
filter!(f, a)
Updates collection a
by deleting items for which f
is false'. The function `f
is passed a single argument.
Examples
julia> filter!(isodd, Vector(1:10))
5-element Vector{Int64}:
1
3
5
7
9
filter!(f, d::AbstractDict)
Updates d
by removing elements for which f
is false'. The `+key⇒value+
pairs are passed to the `f' function.
Examples
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"
#
Base.replace
— Method
replace(A, old_new::Pair...; [count::Integer])
Returns a copy of the collection A
, where for each pair of old=>new
in old_new
all occurrences of old
are replaced with new
. Equality is defined using isequal
. If count
is specified, a total of no more than count
occurrences are replaced.
The type of result elements is selected using promotion (see promote_type'
), taking into account the element type `A and the value types new
in pairs. If count
is omitted and the elements of A
are of type Union
, then the type of the result elements does not include single types, which are replaced by values of another type: for example, Union{T,Missing}`becomes `T
if missing
is replaced.
Compatibility: Julia 1.7
Version 1.7 is required to replace the |
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
#
Base.replace
— Method
replace(new::Union{Function, Type}, A; [count::Integer])
Returns a copy of A
, where each of the values of x
in A
is replaced with new(x)
. If count
is specified, a total of no more than count
values are replaced (replacements are defined as new(x) !==x
).
Compatibility: Julia 1.7
Version 1.7 is required to replace the |
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
#
Base.replace!
— Function
replace!(A, old_new::Pair...; [count::Integer])
For each pair of old=>new
in old_new
, replaces all occurrences of old
in collection A
with new
. Equality is defined using isequal
. If count
is specified, a total of no more than count
occurrences are replaced. See also replace
.
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
replace!(new::Union{Function, Type}, A; [count::Integer])
Replaces each element x
in the collection A
with new(x)
. If count
is specified, a total of no more than count
values are replaced (replacements are 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
#
Base.rest
— Function
Base.rest(collection[, itr_state])
A universal function for accepting the last elements of the collection', starting from a specific iteration state `itr_state'. Returns `Tuple
if collection
is a Tuple
, subtype AbstractVector
if collection
is an AbstractArray
, subtype AbstractString
if collection
is an AbstractString
, otherwise an arbitrary iterator that rolls back to Iterators.rest(collection[, itr_state])
.
You can overload for user-defined collection types to customize the behavior. reads entirely in assignments in the final location, for example a, b... = collection
.
Compatibility: Julia 1.6
The |
See also the description first
, Iterators.rest
, Base.split_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])
#
Base.split_rest
— Function
Base.split_rest(collection, n::Int[, itr_state]) -> (rest_but_n, last_n)
A universal function for separating the end of a collection', starting from a specific iteration state `itr_state'. Returns a tuple of two new collections. The first one contains all the elements of the end, except the `n
last ones, which make up the second collection.
The type of the first collection generally corresponds to the type Base.rest
, except that the backup option is not deferred, but can be quickly formed into a vector.
You can overload for user-defined collection types to customize the behavior. reads entirely in assignments in a non-finite location, for example a, b..., c = collection
.
Compatibility: Julia 1.9
The |
See also the description Base.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.split_rest(a, 1, state)
(1, ([3, 2], [4]))
Indexed collections
#
Base.getindex
— Function
getindex(collection, key...)
Retrieves the values stored by the specified key or index in the collection. The syntax a[i,j,...]
is converted by the compiler to getindex(a, i, j, ...)
.
Examples
julia> A = Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> getindex(A, "a")
1
#
Base.setindex!
— Function
setindex!(collection, value, key...)
Saves the specified value by the specified key or index in the collection. The syntax a[i,j,...] = x
is converted by the compiler to (setindex!(a, x, i, j, ...); x)
.
Examples
julia> a = Dict("a"=>1)
Dict{String, Int64} with 1 entry:
"a" => 1
julia> setindex!(a, 2, "b")
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
#
Base.firstindex
— Function
firstindex(collection) -> Integer
firstindex(collection, d) -> Integer
Returns the first index of the collection'. If the argument `d
is set, returns the first index of the collection
by dimension `d'.
The syntax of A[begin]
and A[1, begin]
is downgraded to A[firstindex(A)]
and A[1, firstindex(A, 2)]
, respectively.
Examples
julia> firstindex([1,2,4])
1
julia> firstindex(rand(3,4,5), 2)
1
#
Base.lastindex
— Function
lastindex(collection) -> Integer
lastindex(collection, d) -> Integer
Returns the last index of the collection'. If the argument `d
is set, returns the last index of the collection
by dimension d
.
The syntax of A[end]
and A[end, end]
is downgraded to A[lastindex(A)]
and A[lastindex(A, 1), lastindex(A, 2)]
, respectively.
See also the description axes
, firstindex
, eachindex
, prevind
.
Examples
julia> lastindex([1,2,4])
3
julia> lastindex(rand(3,4,5), 2)
4
It is fully implemented by the following types:
-
SubArray
Partially implemented by the following types:
Dictionaries
Dict
is a standard dictionary. Its implementation uses hash
as a hashing function for the key and 'isequal` to define equality. Define these two functions for custom types to redefine the way they are stored in the hash table.
'IdDict` is a special hash table where the keys are always object identifiers.
WeakKeyDict
is an implementation of a hash table in which keys are weak references to objects, and therefore can be garbage collected, even if this is indicated by references in the hash table. Like Dict
, this type uses hash
for hashing and isequal
for equality. Unlike Dict
, it does not transform keys upon insertion.
Objects Dict
can be created by passing pairs of objects constructed using =>
to the constructor Dict
: Dict("A"=>1, "B"=>2)
. This call will attempt to infer type information from keys and values (for example, in this example, a Dict' is created{String, Int64}
). To explicitly specify the types, use the syntax Dict{KeyType,ValueType}(...)
. For example, Dict{String,Int32}("A"=>1, "B"=>2)
.
Dictionaries can also be created using generators. For example, Dict(i => f(i) for i = 1:10)
.
If the dictionary D
is specified, the syntax D[x]
returns the value of the key x
(if it exists) or it returns an error, and D[x] = y
saves the key-value pair x => y
in D
(replacing all existing values for the key x
). Multiple arguments for D[...]
are converted to tuples. For example, the syntax 'D[x,y]` is equivalent to D[(x,y)]
, i.e. it refers to a value whose key is the tuple (x,y)
.
#
Base.Dict
— Type
Dict([itr])
Dict{K,V}()
builds a hash table with keys of type K
and values of type V'. The keys are compared using `isequal
and are hashed using hash
.
If a single iterable argument is passed, creates Dict
, the key-value pairs of which are taken from the two-element 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 arguments can be passed in pairs.
julia> Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
The keys can be mutable, but if you change the stored keys, the hash table may become internally inconsistent, in which case |
#
Base.IdDict
— Type
IdDict([itr])
IdDict{K,V}()
performs the construction of a hash table using objectid
as a hash and ===
as an equality operator, with keys of type K
and values of type V'. For additional reference information, see the description `Dict
. A version of this function for sets — IdSet
.
In the following example, all the Dict
keys are isequal
and are hashed in the same way, so they are overwritten. 'IdDict` performs hashing on the object ID, thus storing three 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
#
Base.WeakKeyDict
— Type
WeakKeyDict([itr])
WeakKeyDict() builds a hash table where the keys are weak references to garbage collection-enabled objects, even if the reference exists in the hash table.
For additional reference information, see the description Dict
. Please note that unlike Dict
, WeakKeyDict
does not transform keys upon insertion, as this requires that the key object is not referenced anywhere before insertion.
See also the description WeakRef
.
#
Base.ImmutableDict
— Type
ImmutableDict
`ImmutableDict' is a dictionary implemented as an immutable linked list, which is optimally suited for small dictionaries created based on multiple individual inserts. Note that the value cannot be deleted, although it can be partially redefined and hidden by inserting a new value with the same key.
ImmutableDict(KV::Pair)
Creating a new entry in ImmutableDict
for the pair `key => value'
-
use
(key => value) in dict
to check if this particular combination is included in the property set.; -
use
get(dict, key, default)
to get the latest value for a specific key.
#
Base.PersistentDict
— Type
PersistentDict
'PersistentDict' is a dictionary implemented as a prefix tree mapped to a hash array, which is optimally suited for situations where data retention is required. Each operation returns a new dictionary that is unrelated to the previous one, but the basic implementation takes up little space and allows memory sharing for several separate dictionaries.
It works as an IdDict. |
PersistentDict(KV::Pair)
Examples
julia> dict = Base.PersistentDict(:a=>1)
Base.PersistentDict{Symbol, Int64} with 1 entry:
:a => 1
julia> dict2 = Base.delete(dict, :a)
Base.PersistentDict{Symbol, Int64}()
julia> dict3 = Base.PersistentDict(dict, :a=>2)
Base.PersistentDict{Symbol, Int64} with 1 entry:
:a => 2
#
Base.haskey
— Function
haskey(collection, key) -> Bool
Determines whether the collection contains a mapping for the 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
#
Base.get
— Function
get(collection, key, default)
Returns the value stored for this key, or the default value set if there is no matching for the key.
Compatibility: Julia 1.7
For tuples and numeric values, this function requires a version of 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
get(f::Union{Function, Type}, collection, key)
Returns the value stored for the given key, or if there is no mapping for the key, returns f()
. To save the default value in the dictionary, use get!
.
It is assumed that this function is called using the default value of the do
block syntax.,
get(dict, key) do
# вычисленного здесь.
time()
end
#
Base.get!
— Function
get!(collection, key, default)
Returns the value stored for the specified key, or if there is no mapping for the key, saves key => default
and returns `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
get!(f::Union{Function, Type}, collection, key)
Returns the value stored for the specified key, or, if there is no mapping for the key, saves key => f()
and returns `f()'.
It is assumed that this function is called using the syntax of the do
block.
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
#
Base.getkey
— Function
getkey(collection, key, default)
Returns the key corresponding to the key
argument if it exists in the collection
; otherwise, it returns `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)
#
Base.delete!
— Function
delete!(collection, key)
Deletes the mapping for the given key in the collection (if any), and returns 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 остается без изменений
Dict{String, Int64} with 1 entry:
"a" => 1
#
Base.pop!
— Method
pop!(collection, key[, default])
Deletes and returns the mapping for key' if it exists in `collection
, otherwise it returns default
or returns an error if the default
value is not set.
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
#
Base.keys
— Function
keys(iterator)
For an iterator or a collection that contains keys and values (for example, arrays and dictionaries), returns an iterator based on keys.
#
Base.values
— Function
values(iterator)
For an iterator or collection that contains keys and values, returns an iterator by values. By default, this function simply returns its arguments, since the elements of a common iterator are usually 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
values(a::AbstractDict)
Returns an iterator over all values in the collection. collect(values(a))
returns an array of values. If the values are stored in a hash table, as in the case of Dict
, they can be returned in different order. But keys(a)
, values(a)
and pairs(a)
iterate over 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
#
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 of the element, and x = A[i]
. It is identical to pairs(A)
, except that the index style can be selected independently. It is also similar to enumerate(A)
, except that i
is a valid index for A
, while `enumerate' always counts from 1 regardless of the indexes of `A'.
When specifying IndexLinear()
i
is guaranteed to be an integer; when specified IndexCartesian()'
`i is guaranteed to be Base.CartesianIndex
; when specifying IndexStyle(A)
, any style defined as the custom indexing style for array A
is selected.
When the boundaries of the base array are changed, this iterator becomes invalid.
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 the description IndexStyle
and axes
.
pairs(collection)
Returns an iterator over the pairs key => value
for any collection that maps a set of keys to a set of values. These include arrays in which the keys are array indexes. If the elements are stored in a hash table, as in the case of Dict
, they can be returned in different order. But keys(a)
, values(a)
and pairs(a)
iterate over a
and return the elements in the same order.
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
#
Base.merge
— Function
merge(initial::Face, others::Face...)
Combines the properties of the font initial
and others
, with the latter taking precedence.
merge(d::AbstractDict, others::AbstractDict...)
Creates a combined collection based on the specified collections. If necessary, the types of the resulting collection are promoted so that the types of the combined collections are placed in them. If the same key exists in another collection, the value of this key will be its value in the last collection from the list. For instructions on custom processing of values with the same keys, see the description mergewith
.
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
merge(a::NamedTuple, bs::NamedTuple...)
Creates a new named tuple by combining two or more existing tuples (with left-to-right associativity). The union is performed from left to right for pairs of named tuples, with the order of the fields in the leftmost and rightmost named tuples matching the order in the leftmost named tuple. However, the values are taken from the corresponding fields in the rightmost named tuple that contains such a field. Fields that are contained only in the rightmost named tuple of the pair are joined at the end. For the case when only one named tuple is provided, there is a backup option with the signature merge(a::NamedTuple)
.
Compatibility: Julia 1.1
To combine three or more |
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,))
merge(a::NamedTuple, iterable)
Interprets iterated key-value pairs as a named tuple and performs the union.
julia> merge((a=1, b=2, c=3), [:b=>4, :d=>5])
(a = 1, b = 4, c = 3, d = 5)
#
Base.mergewith
— Function
mergewith(combine, d::AbstractDict, others::AbstractDict...)
mergewith(combine)
merge(combine, d::AbstractDict, others::AbstractDict...)
Creates a combined collection based on the specified collections. If necessary, the types of the resulting collection are promoted so that the types of the combined collections are placed in them. Values with the same key will be combined using the combiner function. The curried form mergewith(combine)
returns the functions (args...) -> mergewith(combine, args...)
.
The +merge(combine) method::Union{Function,Type}, args…)+`as an alias
+mergewith(combine, args…)+` is still available for backward compatibility.
Compatibility: Julia 1.5
Mergewith requires a Julia version of 1.5 or higher. |
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
#
Base.merge!
— Function
merge!(d::AbstractDict, others::AbstractDict...)
Updates a collection using pairs from other collections. See also the description 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
#
Base.mergewith!
— Function
mergewith!(combine, d::AbstractDict, others::AbstractDict...) -> d
mergewith!(combine)
merge!(combine, d::AbstractDict, others::AbstractDict...) -> d
Updates a collection using pairs from other collections. Values with the same key will be combined using the combiner function. Curried form of mergewith!(combine)
returns functions`(args...) -> mergewith!(combine, args...)`.
The +merge!' method(combine::Union{Function,Type}, args…)+`as an alias
+mergewith!(combine, args…)+` is still available for backward compatibility.
Compatibility: Julia 1.5
For |
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
#
Base.sizehint!
— Function
sizehint!(s, n; first::Bool=false, shrink::Bool=true) -> s
Suggests reserving capacity for at least n
items in the s
collection. That is, if you expect to have to send a lot of values to s
, you can avoid the cost of additional reallocation by doing it once in advance. This can improve performance.
If first
is true
, any additional space is reserved before starting the collection. This allows you to speed up subsequent calls to pushfirst!
(instead of push!
). Using this named argument may result in an error if the collection is not ordered or pushfirst!
not supported for her.
With `shrink=true' (default), the collection capacity can be reduced if its current capacity is greater than `n'.
See also the description resize!
.
Notes on the performance model
For types that support sizehint!
,
-
push!' methods
and `append! in general, they can (but not necessarily) pre-allocate additional storage. For types implemented in `Base', this is usually done using a heuristic mechanism optimized for standard scenarios. -
sizehint!
can control such pre-allocation. Again, this is usually done for types in the `Base'. -
empty!
is practically free (O(1)) for types that support such preallocation.
Compatibility: Julia 1.11
The arguments |
#
Base.keytype
— Function
keytype(T::Type{<:AbstractArray})
keytype(A::AbstractArray)
Returns the key type of the array. This is equivalent to eltype
of the result keys(...)
and is provided mainly for the purpose of ensuring compatibility with the dictionary interface.
Examples
julia> keytype([1, 2, 3]) == Int
true
julia> keytype([1 2; 3 4])
CartesianIndex{2}
Compatibility: Julia 1.2
In the case of arrays, this function requires a Julia version of at least 1.2. |
keytype(type)
Gets the key type for the dictionary type. It works similarly eltype
.
Examples
julia> keytype(Dict(Int32(1) => "foo"))
Int32
#
Base.valtype
— Function
valtype(T::Type{<:AbstractArray})
valtype(A::AbstractArray)
Returns the value type for the array. It’s identical 'eltype` and is provided mainly for the purposes of compatibility with the dictionary interface.
Examples
julia> valtype(["one", "two", "three"])
String
Compatibility: Julia 1.2
In the case of arrays, this function requires a Julia version of at least 1.2. |
valtype(type)
Gets the value type for the dictionary type. It works similarly eltype
.
Examples
julia> valtype(Dict(Int32(1) => "foo"))
String
It is fully implemented by the following types:
Partially implemented by the following types:
Collections like sets
#
Base.Set
— Type
Set{T} <: AbstractSet{T}
Set
sets are mutable containers that provide fast membership testing.
Set effectively implements set operations such as 'in`, union
, and intersect'. The elements in a `Set
are unique according to the definition of isequal' for elements. The order of the elements in the `Set
is just an implementation feature, and cannot be relied upon.
Examples
julia> s = Set("aaBca")
Set{Char} with 3 elements:
'a'
'c'
'B'
julia> push!(s, 'b')
Set{Char} with 4 elements:
'a'
'b'
'B'
'c'
julia> s = Set([NaN, 0.0, 1.0, 2.0]);
julia> -0.0 in s # isequal(0.0, -0.0) имеет значение false
false
julia> NaN in s # isequal(NaN, NaN) имеет значение true
true
#
Base.BitSet
— Type
BitSet([itr])
Creates a sorted set of Int
type elements generated by a given iterable object, or an empty set. It is implemented as a bit string and, thus, is oriented towards dense sets of integers. If the set is sparse (for example, it will contain only a few very large integers), use instead Set
.
#
Base.IdSet
— Type
IdSet{T}([itr])
IdSet()
IdSet{T}() creates a set (see Set
), using ===
as the equality operator, with values like `T'.
In the example below, all values are isequal
, so they are overwritten in a regular Set
. 'IdSet` performs the comparison using `===', so three different values are stored.
Examples
julia> Set(Any[true, 1, 1.0])
Set{Any} with 1 element:
1.0
julia> IdSet{Any}(Any[true, 1, 1.0])
IdSet{Any} with 3 elements:
1.0
1
true
#
Base.union
— Function
union(s, itrs...)
∪(s, itrs...)
Creates an object that contains all the unique elements from all the arguments.
The first argument determines which type of container will be returned. If it is an array, it retains the original order of the elements.
The Unicode character ∪
can be entered by typing \cup
and then pressing the TAB key in REPL Julia, as well as in many other editors. This is an infix operator that allows `s ∪ itr'.
See also the description unique
, intersect
, isdisjoint
, vcat
, 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
#
Base.union!
— Function
union!(s::Union{AbstractSet,AbstractVector}, itrs...)
Creates union
of the passed sets and overwrites s
with the result. The order is preserved using arrays.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
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
#
Base.intersect
— Function
intersect(s, itrs...)
∩(s, itrs...)
Creates a set containing such elements that occur in all arguments.
The first argument determines which type of container will be returned. If it is an array, it retains the original order of the elements.
The Unicode character ∩
can be entered by typing \cap
and then pressing the TAB key in REPL Julia, as well as in many other editors. This is an infix operator that allows `s ∩ itr'.
See also the description setdiff
, isdisjoint
, issubset
and issetequal
.
Compatibility: Julia 1.8
Starting with Julia 1.8, intersect returns a result with the element type corresponding to the advanced element types of the two input objects. |
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
#
Base.setdiff
— Function
setdiff(s, itrs...)
Creates a set of elements included in s
, but not included in any of the iterable collections in `itrs'. The order is preserved using arrays.
Examples
julia> setdiff([1,2,3], [3,4,5])
2-element Vector{Int64}:
1
2
#
Base.setdiff!
— Function
setdiff!(s, itrs...)
Removes from the set of s
(in place) all the elements included in the iterable collections in `itrs'. The order is preserved using arrays.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
Examples
julia> a = Set([1, 3, 4, 5]);
julia> setdiff!(a, 1:2:6);
julia> a
Set{Int64} with 1 element:
4
#
Base.symdiff
— Function
symdiff(s, itrs...)
Performs the construction of a symmetric difference of elements in the transmitted sets. If s
is not an 'AbstractSet', the order is preserved.
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])
Int64[]
#
Base.symdiff!
— Function
symdiff!(s::Union{AbstractSet,AbstractVector}, itrs...)
Builds the symmetric difference of the transmitted sets and overwrites s
with the result. If 's` is an array, the order is preserved. Note that in this case, the multiplicity of elements matters.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
#
Base.intersect!
— Function
intersect!(s::Union{AbstractSet,AbstractVector}, itrs...)
Combines all passed sets by intersection and overwrites s
with the result. The order is preserved using arrays.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
#
Base.in!
— Function
in!(x, s::AbstractSet) -> Bool
If x
is included in s
, it returns true'. Otherwise, it puts `x
in s
and returns false
. Is this equivalent to in(x, s)' ? true : (push!(s, x); false)
, but may have a more efficient implementation.
Compatibility: Julia 1.11
This feature requires a version of Julia at least 1.11. |
Examples
julia> s = Set{Any}([1, 2, 3]); in!(4, s)
false
julia> length(s)
4
julia> in!(0x04, s)
true
julia> s
Set{Any} with 4 elements:
4
2
3
1
#
Base.issetequal
— Function
issetequal(a, b) -> Bool
Determines whether a
and b
contain the same elements. It is equivalent to a ⊆ b && b ⊆ a
, but it may be more effective.
See also the description isdisjoint
, union
.
Examples
julia> issetequal([1, 2], [1, 2, 3])
false
julia> issetequal([1, 2], [2, 1])
true
issetequal(x)
Creates a function whose argument is compared to x
via issetequal
, i.e. a function equivalent to y -> issetequal(y, x)
. The returned function is of type Base.Fix2{typeof(issetequal)}
and can be used to implement specialized methods.
Compatibility: Julia 1.11
This feature requires a version of Julia at least 1.11. |
#
Base.isdisjoint
— Function
isdisjoint(a, b) -> Bool
Determines whether collections a
and b
are disjoint. It is equivalent to `isempty(a ∩ b)', but it may be more efficient.
See also the description intersect
, isempty
, issetequal
.
Compatibility: Julia 1.5
This feature requires a Julia version of 1.5 or higher. |
Examples
julia> isdisjoint([1, 2], [2, 3, 4])
false
julia> isdisjoint([3, 1], [2, 4])
true
isdisjoint(x)
Creates a function whose argument is compared to x
via 'isdisjoint`, i.e. a function equivalent to y -> isdisjoint(y, x)
. The returned function is of type Base.Fix2{typeof(isdisjoint)}
and can be used to implement specialized methods.
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
It is fully implemented by the following types:
Partially implemented by the following types:
Two-way queues
#
Base.push!
— Function
push!(collection, items...) -> collection
Inserts one or more items
into a collection'. If the `collection
is an ordered container, the items are inserted at the end (in the specified order).
Examples
julia> push!([1, 2, 3], 4, 5, 6)
6-element Vector{Int64}:
1
2
3
4
5
6
If the collection
is ordered, use append!
to add all the elements of another collection to it. The result in the previous example is equivalent to append!([1, 2, 3], [4, 5, 6])
. For AbstractSet
objects, you can use union!
.
For notes on the performance model, see sizehint!
.
See also the description pushfirst!
.
#
Base.pop!
— Function
pop!(collection) -> item
Deletes an item in the collection
and returns it. If the collection
is an ordered container, the last element is returned; in the case of unordered containers, an arbitrary element is returned.
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
pop!(collection, key[, default])
Deletes and returns the mapping for key' if it exists in `collection
, otherwise it returns default
or returns an error if the default
value is not set.
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
#
Base.popat!
— Function
popat!(a::Vector, i::Integer, [default])
Deletes the element by the specified i
and returns it. Subsequent elements are shifted to fill the resulting gap. If i
is not a valid index for a
, default
is returned, or an error occurs if default
is not specified.
Compatibility: Julia 1.5
This feature was first implemented in 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]
[...]
#
Base.pushfirst!
— Function
pushfirst!(collection, items...) -> collection
Inserts one or more items
elements at the beginning of the collection
.
In many other programming languages, this function is called `unshift'.
Examples
julia> pushfirst!([1, 2, 3, 4], 5, 6)
6-element Vector{Int64}:
5
6
1
2
3
4
#
Base.popfirst!
— Function
popfirst!(collection) -> item
Deletes the first item
element from the collection
.
In many other programming languages, this function is called `shift'.
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
#
Base.insert!
— Function
insert!(a::Vector, index::Integer, item)
Inserts the element item
into a
by the index index
. index
is the index of the item
element in the resulting `a'.
Examples
julia> insert!(Any[1:6;], 3, "here")
7-element Vector{Any}:
1
2
"here"
3
4
5
6
#
Base.deleteat!
— Function
deleteat!(a::Vector, i::Integer)
Deletes the element at the specified index i
and returns the modified array a
. Subsequent elements are shifted to fill the resulting gap.
Examples
julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
5-element Vector{Int64}:
6
4
3
2
1
deleteat!(a::Vector, inds)
Deletes elements by the indexes specified in `inds' and returns the modified array `a'. Subsequent elements are shifted to fill the resulting gap.
inds
can be an iterator or a collection of sorted unique integer indexes, or a logical vector of the same length as a
, where true
indicates the elements to be deleted.
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:
[...]
#
Base.keepat!
— Function
keepat!(a::Vector, inds)
keepat!(a::BitVector, inds)
Deletes elements by all indexes that are not specified in inds
, and returns the modified array `a'. The saved elements are shifted to fill the resulting gap.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
inds
must be an iterator of sorted and unique integer indexes. See also the description deleteat!
.
Compatibility: Julia 1.7
This feature was first implemented in Julia 1.7. |
Examples
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
3-element Vector{Int64}:
6
4
2
keepat!(a::Vector, m::AbstractVector{Bool}) keepat!(a::BitVector, m::AbstractVector{Bool})
The on-site version of logical indexing is a = a[m]
. That is, the call keepat!(a, m)
for vectors of the same length a
and m
removes all elements from a
for which false
is found at the corresponding index in m
.
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
#
Base.splice!
— Function
splice!(a::Vector, index::Integer, [replacement]) -> item
Deletes an item at the specified index and returns the deleted item. Subsequent elements are shifted to the left to fill the resulting gap. If replacement values from the ordered collection are specified, they are inserted instead of the deleted element.
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 a replacement
before the index n
without deleting the elements, use splice!(collection, n:n-1, replacement)
.
splice!(a::Vector, indices, [replacement]) -> items
Deletes the items at the specified indexes and returns the collection containing the deleted items. Subsequent elements are shifted to the left to fill the resulting gaps. If replacement values from an ordered collection are specified, they are inserted instead of deleted items; in this case, indexes
should be of type `AbstractUnitRange'.
To insert a replacement
before the index n
without deleting the elements, use splice!(collection, n:n-1, replacement)
.
If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected. |
Compatibility: Julia 1.5
In versions prior to Julia 1.5, the |
Compatibility: Julia 1.8
In versions prior to Julia 1.8, when inserting replacement values, the |
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
#
Base.resize!
— Function
resize!(a::Vector, n::Integer) -> Vector
Resizes the collection a
so that it contains n
items. If n
is less than the current length of the collection, the first n
elements are saved. If n
is greater, initialization of new elements is not guaranteed.
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
#
Base.append!
— Function
append!(collection, collections...) -> collection.
For an ordered container, a collection
adds the elements of each collection to the `collections' at the end.
Compatibility: Julia 1.6
To specify multiple collections that you want to attach, you need a Julia version of at least 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!
to add individual items to a collection' that are not yet included in another collection. The result in the previous example is equivalent to `push!([1, 2, 3], 4, 5, 6)
.
For notes on the performance model, see sizehint!
.
See also 'vcat` for vectors, union!
for sets and prepend!
and pushfirst!
(reverse order).
#
Base.prepend!
— Function
prepend!(a::Vector, collections...) -> collection
Inserts items from each collection in `collections' at the beginning of `a'.
If multiple collections are specified in collections
, the order is preserved: the elements of collections[1]
will be the leftmost in a
, and so on.
Compatibility: Julia 1.6
To specify multiple collections that you want to attach at the beginning, you need a Julia version at least 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
It is fully implemented by the following types:
Useful collections
#
Core.Pair
— Type
Pair(x, y)
x => y
Creates a Pair' object of the `Pair' type{typeof(x), typeof(y)}
. The elements are stored in the first
and second
fields. They can also be accessed through iteration (but Pair
is treated as a single "scalar" type for translation operations).
See also the description 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
julia> replace.(["xops", "oxps"], "x" => "o")
2-element Vector{String}:
"oops"
"oops"
#
Base.Pairs
— Type
Base.Pairs(values, keys) <: AbstractDict{eltype(keys), eltype(values)}
Converts an indexed container into a dictionary representation for the same data. Due to changes in the key space of the underlying data, this object may become invalid.