集合和数据结构

迭代

序列迭代由 iterate 实现 广义的 for 循环

  1. for i in iter # or "for i = iter"
  2. # body
  3. end

被转换成

  1. next = iterate(iter)
  2. while next !== nothing
  3. (i, state) = next
  4. # body
  5. next = iterate(iter, state)
  6. end

state 对象可以是任何对象,并且对于每个可迭代类型应该选择合适的 state 对象。 请参照 帮助文档接口的迭代小节 来获取关于定义一个常见迭代类型的更多细节。

Base.iterate — Function

  1. iterate(iter [, state]) -> Union{Nothing, Tuple{Any, Any}}

Advance the iterator to obtain the next element. If no elements remain, nothing should be returned. Otherwise, a 2-tuple of the next element and the new iteration state should be returned.

source

Base.IteratorSize — Type

  1. IteratorSize(itertype::Type) -> IteratorSize

Given the type of an iterator, return one of the following values:

  • SizeUnknown() if the length (number of elements) cannot be determined in advance.
  • HasLength() if there is a fixed, finite length.
  • HasShape{N}() if there is a known length plus a notion of multidimensional shape (as for an array). In this case N should give the number of dimensions, and the axes function is valid for the iterator.
  • IsInfinite() if the iterator yields values forever.

The default value (for iterators that do not define this function) is HasLength(). This means that most iterators are assumed to implement length.

This trait is generally used to select between algorithms that pre-allocate space for their result, and algorithms that resize their result incrementally.

  1. julia> Base.IteratorSize(1:5)
  2. Base.HasShape{1}()
  3. julia> Base.IteratorSize((2,3))
  4. Base.HasLength()

source

Base.IteratorEltype — Type

  1. IteratorEltype(itertype::Type) -> IteratorEltype

Given the type of an iterator, return one of the following values:

  • EltypeUnknown() if the type of elements yielded by the iterator is not known in advance.
  • HasEltype() if the element type is known, and eltype would return a meaningful value.

HasEltype() is the default, since iterators are assumed to implement eltype.

This trait is generally used to select between algorithms that pre-allocate a specific type of result, and algorithms that pick a result type based on the types of yielded values.

  1. julia> Base.IteratorEltype(1:5)
  2. Base.HasEltype()

source

以下类型均完全实现了上述函数:

构造函数和类型

Base.AbstractRange — Type

  1. AbstractRange{T}

Supertype for ranges with elements of type T. UnitRange and other types are subtypes of this.

source

Base.OrdinalRange — Type

  1. OrdinalRange{T, S} <: AbstractRange{T}

Supertype for ordinal ranges with elements of type T with spacing(s) of type S. The steps should be always-exact multiples of oneunit, and T should be a “discrete” type, which cannot have values smaller than oneunit. For example, Integer or Date types would qualify, whereas Float64 would not (since this type can represent values smaller than oneunit(Float64). UnitRange, StepRange, and other types are subtypes of this.

source

Base.AbstractUnitRange — Type

  1. AbstractUnitRange{T} <: OrdinalRange{T, T}

Supertype for ranges with a step size of oneunit(T) with elements of type T. UnitRange and other types are subtypes of this.

source

Base.StepRange — Type

  1. StepRange{T, S} <: OrdinalRange{T, S}

Ranges with elements of type T with spacing of type S. The step between each element is constant, and the range is defined in terms of a start and stop of type T and a step of type S. Neither T nor S should be floating point types. The syntax a:b:c with b > 1 and a, b, and c all integers creates a StepRange.

Examples

  1. julia> collect(StepRange(1, Int8(2), 10))
  2. 5-element Vector{Int64}:
  3. 1
  4. 3
  5. 5
  6. 7
  7. 9
  8. julia> typeof(StepRange(1, Int8(2), 10))
  9. StepRange{Int64, Int8}
  10. julia> typeof(1:3:6)
  11. StepRange{Int64, Int64}

source

Base.UnitRange — Type

  1. UnitRange{T<:Real}

A range parameterized by a start and stop of type T, filled with elements spaced by 1 from start until stop is exceeded. The syntax a:b with a and b both Integers creates a UnitRange.

Examples

  1. julia> collect(UnitRange(2.3, 5.2))
  2. 3-element Vector{Float64}:
  3. 2.3
  4. 3.3
  5. 4.3
  6. julia> typeof(1:10)
  7. UnitRange{Int64}

source

Base.LinRange — Type

  1. LinRange{T,L}

A range with len linearly spaced elements between its start and stop. The size of the spacing is controlled by len, which must be an Integer.

Examples

  1. julia> LinRange(1.5, 5.5, 9)
  2. 9-element LinRange{Float64, Int64}:
  3. 1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0,5.5

Compared to using range, directly constructing a LinRange should have less overhead but won’t try to correct for floating point errors:

  1. julia> collect(range(-0.1, 0.3, length=5))
  2. 5-element Array{Float64,1}:
  3. -0.1
  4. 0.0
  5. 0.1
  6. 0.2
  7. 0.3
  8. julia> collect(LinRange(-0.1, 0.3, 5))
  9. 5-element Array{Float64,1}:
  10. -0.1
  11. -1.3877787807814457e-17
  12. 0.09999999999999999
  13. 0.19999999999999998
  14. 0.3

source

通用集合

Base.isempty — Function

  1. isempty(collection) -> Bool

Determine whether a collection is empty (has no elements).

Examples

  1. julia> isempty([])
  2. true
  3. julia> isempty([1 2 3])
  4. false

source

  1. isempty(condition)

Return true if no tasks are waiting on the condition, false otherwise.

source

Base.empty! — Function

  1. empty!(collection) -> collection

Remove all elements from a collection.

Examples

  1. julia> A = Dict("a" => 1, "b" => 2)
  2. Dict{String, Int64} with 2 entries:
  3. "b" => 2
  4. "a" => 1
  5. julia> empty!(A);
  6. julia> A
  7. Dict{String, Int64}()

source

Base.length — Function

  1. length(collection) -> Integer

Return the number of elements in the collection.

Use lastindex to get the last valid index of an indexable collection.

See also: size, ndims, eachindex.

Examples

  1. julia> length(1:5)
  2. 5
  3. julia> length([1, 2, 3, 4])
  4. 4
  5. julia> length([1 2; 3 4])
  6. 4

source

Base.checked_length — Function

  1. Base.checked_length(r)

Calculates length(r), but may check for overflow errors where applicable when the result doesn’t fit into Union{Integer(eltype(r)),Int}.

source

以下类型均完全实现了上述函数:

可迭代集合

Base.in — Function

  1. in(item, collection) -> Bool
  2. ∈(item, collection) -> Bool

Determine whether an item is in the given collection, in the sense that it is \== to one of the values generated by iterating over the collection. Returns a Bool value, except if item is missing or collection contains missing but not item, in which case missing is returned (three-valued logic, matching the behavior of any and \==).

Some collections follow a slightly different definition. For example, Sets check whether the item isequal to one of the elements. Dicts look for key=>value pairs, and the key is compared using isequal. To test for the presence of a key in a dictionary, use haskey or k in keys(dict). For these collections, the result is always a Bool and never missing.

To determine whether an item is not in a given collection, see :∉. You may also negate the in by doing !(a in b) which is logically similar to “not in”.

When broadcasting with in.(items, collection) or items .∈ collection, both item and collection are broadcasted over, which is often not what is intended. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each value in collection items is in the value at the corresponding position in collection. To get a vector indicating whether each value in items is in collection, wrap collection in a tuple or a Ref like this: in.(items, Ref(collection)) or items .∈ Ref(collection).

Examples

  1. julia> a = 1:3:20
  2. 1:3:19
  3. julia> 4 in a
  4. true
  5. julia> 5 in a
  6. false
  7. julia> missing in [1, 2]
  8. missing
  9. julia> 1 in [2, missing]
  10. missing
  11. julia> 1 in [1, missing]
  12. true
  13. julia> missing in Set([1, 2])
  14. false
  15. julia> !(21 in a)
  16. true
  17. julia> !(19 in a)
  18. false
  19. julia> [1, 2] .∈ [2, 3]
  20. 2-element BitVector:
  21. 0
  22. 0
  23. julia> [1, 2] .∈ ([2, 3],)
  24. 2-element BitVector:
  25. 0
  26. 1

See also: insorted, contains, occursin, issubset.

source

Base.:∉ — Function

  1. ∉(item, collection) -> Bool
  2. ∌(collection, item) -> Bool

Negation of and , i.e. checks that item is not in collection.

When broadcasting with items .∉ collection, both item and collection are broadcasted over, which is often not what is intended. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each value in collection items is not in the value at the corresponding position in collection. To get a vector indicating whether each value in items is not in collection, wrap collection in a tuple or a Ref like this: items .∉ Ref(collection).

Examples

  1. julia> 1 2:4
  2. true
  3. julia> 1 1:3
  4. false
  5. julia> [1, 2] .∉ [2, 3]
  6. 2-element BitVector:
  7. 1
  8. 1
  9. julia> [1, 2] .∉ ([2, 3],)
  10. 2-element BitVector:
  11. 1
  12. 0

source

Base.eltype — Function

  1. eltype(type)

Determine the type of the elements generated by iterating a collection of the given type. For dictionary types, this will be a Pair{KeyType,ValType}. The definition eltype(x) = eltype(typeof(x)) is provided for convenience so that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types.

See also: keytype, typeof.

Examples

  1. julia> eltype(fill(1f0, (2,2)))
  2. Float32
  3. julia> eltype(fill(0x1, (2,2)))
  4. UInt8

source

Base.indexin — Function

  1. indexin(a, b)

Return an array containing the first index in b for each value in a that is a member of b. The output array contains nothing wherever a is not a member of b.

See also: sortperm, findfirst.

Examples

  1. julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
  2. julia> b = ['a', 'b', 'c'];
  3. julia> indexin(a, b)
  4. 6-element Vector{Union{Nothing, Int64}}:
  5. 1
  6. 2
  7. 3
  8. 2
  9. nothing
  10. 1
  11. julia> indexin(b, a)
  12. 3-element Vector{Union{Nothing, Int64}}:
  13. 1
  14. 2
  15. 3

source

Base.unique — Function

  1. unique(itr)

Return an array containing only the unique elements of collection itr, as determined by isequal, in the order that the first of each set of equivalent elements originally appears. The element type of the input is preserved.

See also: unique!, allunique.

Examples

  1. julia> unique([1, 2, 6, 2])
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 6
  6. julia> unique(Real[1, 1.0, 2])
  7. 2-element Vector{Real}:
  8. 1
  9. 2

source

  1. unique(f, itr)

Returns an array containing one value from itr for each unique value produced by f applied to elements of itr.

Examples

  1. julia> unique(x -> x^2, [1, -1, 3, -3, 4])
  2. 3-element Vector{Int64}:
  3. 1
  4. 3
  5. 4

source

  1. unique(A::AbstractArray; dims::Int)

Return unique regions of A along dimension dims.

Examples

  1. julia> A = map(isodd, reshape(Vector(1:8), (2,2,2)))
  2. 2×2×2 Array{Bool, 3}:
  3. [:, :, 1] =
  4. 1 1
  5. 0 0
  6. [:, :, 2] =
  7. 1 1
  8. 0 0
  9. julia> unique(A)
  10. 2-element Vector{Bool}:
  11. 1
  12. 0
  13. julia> unique(A, dims=2)
  14. 2×1×2 Array{Bool, 3}:
  15. [:, :, 1] =
  16. 1
  17. 0
  18. [:, :, 2] =
  19. 1
  20. 0
  21. julia> unique(A, dims=3)
  22. 2×2×1 Array{Bool, 3}:
  23. [:, :, 1] =
  24. 1 1
  25. 0 0

source

Base.unique! — Function

  1. unique!(f, A::AbstractVector)

Selects one value from A for each unique value produced by f applied to elements of A, then return the modified A.

Julia 1.1

This method is available as of Julia 1.1.

Examples

  1. julia> unique!(x -> x^2, [1, -1, 3, -3, 4])
  2. 3-element Vector{Int64}:
  3. 1
  4. 3
  5. 4
  6. julia> unique!(n -> n%3, [5, 1, 8, 9, 3, 4, 10, 7, 2, 6])
  7. 3-element Vector{Int64}:
  8. 5
  9. 1
  10. 9
  11. julia> unique!(iseven, [2, 3, 5, 7, 9])
  12. 2-element Vector{Int64}:
  13. 2
  14. 3

source

  1. unique!(A::AbstractVector)

Remove duplicate items as determined by isequal, then return the modified A. unique! will return the elements of A in the order that they occur. If you do not care about the order of the returned data, then calling (sort!(A); unique!(A)) will be much more efficient as long as the elements of A can be sorted.

Examples

  1. julia> unique!([1, 1, 1])
  2. 1-element Vector{Int64}:
  3. 1
  4. julia> A = [7, 3, 2, 3, 7, 5];
  5. julia> unique!(A)
  6. 4-element Vector{Int64}:
  7. 7
  8. 3
  9. 2
  10. 5
  11. julia> B = [7, 6, 42, 6, 7, 42];
  12. julia> sort!(B); # unique! is able to process sorted data much more efficiently.
  13. julia> unique!(B)
  14. 3-element Vector{Int64}:
  15. 6
  16. 7
  17. 42

source

Base.allunique — Function

  1. allunique(itr) -> Bool

Return true if all values from itr are distinct when compared with isequal.

See also: unique, issorted.

Examples

  1. julia> a = [1; 2; 3]
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. julia> allunique(a)
  7. true
  8. julia> allunique([a, a])
  9. false

source

Base.reduce — Method

  1. reduce(op, itr; [init])

Reduce the given collection itr with the given binary operator op. If provided, the initial value init must be a neutral element for op that will be returned for empty collections. It is unspecified whether init is used for non-empty collections.

For empty collections, providing init will be necessary, except for some special cases (e.g. when op is one of +, *, max, min, &, |) when Julia can determine the neutral element of op.

Reductions for certain commonly-used operators may have special implementations, and should be used instead: maximum(itr), minimum(itr), sum(itr), prod(itr), any(itr), all(itr).

The associativity of the reduction is implementation dependent. This means that you can’t use non-associative operations like - because it is undefined whether reduce(-,[1,2,3]) should be evaluated as (1-2)-3 or 1-(2-3). Use foldl or foldr instead for guaranteed left or right associativity.

Some operations accumulate error. Parallelism will be easier if the reduction can be executed in groups. Future versions of Julia might change the algorithm. Note that the elements are not reordered if you use an ordered collection.

Examples

  1. julia> reduce(*, [2; 3; 4])
  2. 24
  3. julia> reduce(*, [2; 3; 4]; init=-1)
  4. -24

source

Base.foldl — Method

  1. foldl(op, itr; [init])

Like reduce, but with guaranteed left associativity. If provided, the keyword argument init will be used exactly once. In general, it will be necessary to provide init to work with empty collections.

Examples

  1. julia> foldl(=>, 1:4)
  2. ((1 => 2) => 3) => 4
  3. julia> foldl(=>, 1:4; init=0)
  4. (((0 => 1) => 2) => 3) => 4

source

Base.foldr — Method

  1. foldr(op, itr; [init])

Like reduce, but with guaranteed right associativity. If provided, the keyword argument init will be used exactly once. In general, it will be necessary to provide init to work with empty collections.

Examples

  1. julia> foldr(=>, 1:4)
  2. 1 => (2 => (3 => 4))
  3. julia> foldr(=>, 1:4; init=0)
  4. 1 => (2 => (3 => (4 => 0)))

source

Base.maximum — Function

  1. maximum(f, itr; [init])

Returns the largest result of calling function f on each element of itr.

The value returned for empty itr can be specified by init. It must be a neutral element for max (i.e. which is less than or equal to any other element) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

Examples

  1. julia> maximum(length, ["Julion", "Julia", "Jule"])
  2. 6
  3. julia> maximum(length, []; init=-1)
  4. -1
  5. julia> maximum(sin, Real[]; init=-1.0) # good, since output of sin is >= -1
  6. -1.0

source

  1. maximum(itr; [init])

Returns the largest element in a collection.

The value returned for empty itr can be specified by init. It must be a neutral element for max (i.e. which is less than or equal to any other element) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

Examples

  1. julia> maximum(-20.5:10)
  2. 9.5
  3. julia> maximum([1,2,3])
  4. 3
  5. julia> maximum(())
  6. ERROR: ArgumentError: reducing over an empty collection is not allowed
  7. Stacktrace:
  8. [...]
  9. julia> maximum((); init=-Inf)
  10. -Inf

source

  1. maximum(A::AbstractArray; dims)

Compute the maximum value of an array over the given dimensions. See also the max(a,b) function to take the maximum of two or more arguments, which can be applied elementwise to arrays via max.(a,b).

See also: maximum!, extrema, findmax, argmax.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> maximum(A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 3 4
  8. julia> maximum(A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 2
  11. 4

source

  1. maximum(f, A::AbstractArray; dims)

Compute the maximum value by calling the function f on each element of an array over the given dimensions.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> maximum(abs2, A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 9 16
  8. julia> maximum(abs2, A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 4
  11. 16

source

Base.maximum! — Function

  1. maximum!(r, A)

Compute the maximum value of A over the singleton dimensions of r, and write results to r.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> maximum!([1; 1], A)
  6. 2-element Vector{Int64}:
  7. 2
  8. 4
  9. julia> maximum!([1 1], A)
  10. 1×2 Matrix{Int64}:
  11. 3 4

source

Base.minimum — Function

  1. minimum(f, itr; [init])

Returns the smallest result of calling function f on each element of itr.

The value returned for empty itr can be specified by init. It must be a neutral element for min (i.e. which is greater than or equal to any other element) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

Examples

  1. julia> minimum(length, ["Julion", "Julia", "Jule"])
  2. 4
  3. julia> minimum(length, []; init=typemax(Int64))
  4. 9223372036854775807
  5. julia> minimum(sin, Real[]; init=1.0) # good, since output of sin is <= 1
  6. 1.0

source

  1. minimum(itr; [init])

Returns the smallest element in a collection.

The value returned for empty itr can be specified by init. It must be a neutral element for min (i.e. which is greater than or equal to any other element) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

Examples

  1. julia> minimum(-20.5:10)
  2. -20.5
  3. julia> minimum([1,2,3])
  4. 1
  5. julia> minimum([])
  6. ERROR: ArgumentError: reducing over an empty collection is not allowed
  7. Stacktrace:
  8. [...]
  9. julia> minimum([]; init=Inf)
  10. Inf

source

  1. minimum(A::AbstractArray; dims)

Compute the minimum value of an array over the given dimensions. See also the min(a,b) function to take the minimum of two or more arguments, which can be applied elementwise to arrays via min.(a,b).

See also: minimum!, extrema, findmin, argmin.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> minimum(A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 1 2
  8. julia> minimum(A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 1
  11. 3

source

  1. minimum(f, A::AbstractArray; dims)

Compute the minimum value by calling the function f on each element of an array over the given dimensions.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> minimum(abs2, A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 1 4
  8. julia> minimum(abs2, A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 1
  11. 9

source

Base.minimum! — Function

  1. minimum!(r, A)

Compute the minimum value of A over the singleton dimensions of r, and write results to r.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> minimum!([1; 1], A)
  6. 2-element Vector{Int64}:
  7. 1
  8. 3
  9. julia> minimum!([1 1], A)
  10. 1×2 Matrix{Int64}:
  11. 1 2

source

Base.extrema — Function

  1. extrema(itr) -> Tuple

Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple.

Examples

  1. julia> extrema(2:10)
  2. (2, 10)
  3. julia> extrema([9,pi,4.5])
  4. (3.141592653589793, 9.0)

source

  1. extrema(f, itr) -> Tuple

Compute both the minimum and maximum of f applied to each element in itr and return them as a 2-tuple. Only one pass is made over itr.

Julia 1.2

This method requires Julia 1.2 or later.

Examples

  1. julia> extrema(sin, 0:π)
  2. (0.0, 0.9092974268256817)

source

  1. extrema(A::AbstractArray; dims) -> Array{Tuple}

Compute the minimum and maximum elements of an array over the given dimensions.

Examples

  1. julia> A = reshape(Vector(1:2:16), (2,2,2))
  2. 2×2×2 Array{Int64, 3}:
  3. [:, :, 1] =
  4. 1 5
  5. 3 7
  6. [:, :, 2] =
  7. 9 13
  8. 11 15
  9. julia> extrema(A, dims = (1,2))
  10. 1×1×2 Array{Tuple{Int64, Int64}, 3}:
  11. [:, :, 1] =
  12. (1, 7)
  13. [:, :, 2] =
  14. (9, 15)

source

  1. extrema(f, A::AbstractArray; dims) -> Array{Tuple}

Compute the minimum and maximum of f applied to each element in the given dimensions of A.

Julia 1.2

This method requires Julia 1.2 or later.

source

Base.argmax — Function

  1. argmax(r::AbstractRange)

Ranges can have multiple maximal elements. In that case argmax will return a maximal index, but not necessarily the first one.

source

  1. argmax(f, domain)

Return a value x in the domain of f for which f(x) is maximised. If there are multiple maximal values for f(x) then the first one will be found.

domain must be a non-empty iterable.

Values are compared with isless.

Julia 1.7

This method requires Julia 1.7 or later.

Examples

  1. julia> argmax(abs, -10:5)
  2. -10
  3. julia> argmax(cos, 0:π/2:2π)
  4. 0.0

source

  1. argmax(itr)

Return the index or key of the maximal element in a collection. If there are multiple maximal elements, then the first one will be returned.

The collection must not be empty.

Values are compared with isless.

See also: argmin, findmax.

Examples

  1. julia> argmax([8, 0.1, -9, pi])
  2. 1
  3. julia> argmax([1, 7, 7, 6])
  4. 2
  5. julia> argmax([1, 7, 7, NaN])
  6. 4

source

  1. argmax(A; dims) -> indices

For an array input, return the indices of the maximum elements over the given dimensions. NaN is treated as greater than all other values except missing.

Examples

  1. julia> A = [1.0 2; 3 4]
  2. 2×2 Matrix{Float64}:
  3. 1.0 2.0
  4. 3.0 4.0
  5. julia> argmax(A, dims=1)
  6. 1×2 Matrix{CartesianIndex{2}}:
  7. CartesianIndex(2, 1) CartesianIndex(2, 2)
  8. julia> argmax(A, dims=2)
  9. 2×1 Matrix{CartesianIndex{2}}:
  10. CartesianIndex(1, 2)
  11. CartesianIndex(2, 2)

source

Base.argmin — Function

  1. argmin(r::AbstractRange)

Ranges can have multiple minimal elements. In that case argmin will return a minimal index, but not necessarily the first one.

source

  1. argmin(f, domain)

Return a value x in the domain of f for which f(x) is minimised. If there are multiple minimal values for f(x) then the first one will be found.

domain must be a non-empty iterable.

NaN is treated as less than all other values except missing.

Julia 1.7

This method requires Julia 1.7 or later.

Examples

  1. julia> argmin(sign, -10:5)
  2. -10
  3. julia> argmin(x -> -x^3 + x^2 - 10, -5:5)
  4. 5
  5. julia> argmin(acos, 0:0.1:1)
  6. 1.0

source

  1. argmin(itr)

Return the index or key of the minimal element in a collection. If there are multiple minimal elements, then the first one will be returned.

The collection must not be empty.

NaN is treated as less than all other values except missing.

See also: argmax, findmin.

Examples

  1. julia> argmin([8, 0.1, -9, pi])
  2. 3
  3. julia> argmin([7, 1, 1, 6])
  4. 2
  5. julia> argmin([7, 1, 1, NaN])
  6. 4

source

  1. argmin(A; dims) -> indices

For an array input, return the indices of the minimum elements over the given dimensions. NaN is treated as less than all other values except missing.

Examples

  1. julia> A = [1.0 2; 3 4]
  2. 2×2 Matrix{Float64}:
  3. 1.0 2.0
  4. 3.0 4.0
  5. julia> argmin(A, dims=1)
  6. 1×2 Matrix{CartesianIndex{2}}:
  7. CartesianIndex(1, 1) CartesianIndex(1, 2)
  8. julia> argmin(A, dims=2)
  9. 2×1 Matrix{CartesianIndex{2}}:
  10. CartesianIndex(1, 1)
  11. CartesianIndex(2, 1)

source

Base.findmax — Function

  1. findmax(f, domain) -> (f(x), index)

Returns a pair of a value in the codomain (outputs of f) and the index of the corresponding value in the domain (inputs to f) such that f(x) is maximised. If there are multiple maximal points, then the first one will be returned.

domain must be a non-empty iterable.

Values are compared with isless.

Julia 1.7

This method requires Julia 1.7 or later.

Examples

  1. julia> findmax(identity, 5:9)
  2. (9, 5)
  3. julia> findmax(-, 1:10)
  4. (-1, 1)
  5. julia> findmax(first, [(1, :a), (3, :b), (3, :c)])
  6. (3, 2)
  7. julia> findmax(cos, 0:π/2:2π)
  8. (1.0, 1)

source

  1. findmax(itr) -> (x, index)

Return the maximal element of the collection itr and its index or key. If there are multiple maximal elements, then the first one will be returned. Values are compared with isless.

See also: findmin, argmax, maximum.

Examples

  1. julia> findmax([8, 0.1, -9, pi])
  2. (8.0, 1)
  3. julia> findmax([1, 7, 7, 6])
  4. (7, 2)
  5. julia> findmax([1, 7, 7, NaN])
  6. (NaN, 4)

source

  1. findmax(A; dims) -> (maxval, index)

For an array input, returns the value and index of the maximum over the given dimensions. NaN is treated as greater than all other values except missing.

Examples

  1. julia> A = [1.0 2; 3 4]
  2. 2×2 Matrix{Float64}:
  3. 1.0 2.0
  4. 3.0 4.0
  5. julia> findmax(A, dims=1)
  6. ([3.0 4.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(2, 2)])
  7. julia> findmax(A, dims=2)
  8. ([2.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 2); CartesianIndex(2, 2);;])

source

Base.findmin — Function

  1. findmin(f, domain) -> (f(x), index)

Returns a pair of a value in the codomain (outputs of f) and the index of the corresponding value in the domain (inputs to f) such that f(x) is minimised. If there are multiple minimal points, then the first one will be returned.

domain must be a non-empty iterable.

NaN is treated as less than all other values except missing.

Julia 1.7

This method requires Julia 1.7 or later.

Examples

  1. julia> findmin(identity, 5:9)
  2. (5, 1)
  3. julia> findmin(-, 1:10)
  4. (-10, 10)
  5. julia> findmin(first, [(2, :a), (2, :b), (3, :c)])
  6. (2, 1)
  7. julia> findmin(cos, 0:π/2:2π)
  8. (-1.0, 3)

source

  1. findmin(itr) -> (x, index)

Return the minimal element of the collection itr and its index or key. If there are multiple minimal elements, then the first one will be returned. NaN is treated as less than all other values except missing.

See also: findmax, argmin, minimum.

Examples

  1. julia> findmin([8, 0.1, -9, pi])
  2. (-9.0, 3)
  3. julia> findmin([1, 7, 7, 6])
  4. (1, 1)
  5. julia> findmin([1, 7, 7, NaN])
  6. (NaN, 4)

source

  1. findmin(A; dims) -> (minval, index)

For an array input, returns the value and index of the minimum over the given dimensions. NaN is treated as less than all other values except missing.

Examples

  1. julia> A = [1.0 2; 3 4]
  2. 2×2 Matrix{Float64}:
  3. 1.0 2.0
  4. 3.0 4.0
  5. julia> findmin(A, dims=1)
  6. ([1.0 2.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(1, 2)])
  7. julia> findmin(A, dims=2)
  8. ([1.0; 3.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])

source

Base.findmax! — Function

  1. findmax!(rval, rind, A) -> (maxval, index)

Find the maximum of A and the corresponding linear index along singleton dimensions of rval and rind, and store the results in rval and rind. NaN is treated as greater than all other values except missing.

source

Base.findmin! — Function

  1. findmin!(rval, rind, A) -> (minval, index)

Find the minimum of A and the corresponding linear index along singleton dimensions of rval and rind, and store the results in rval and rind. NaN is treated as less than all other values except missing.

source

Base.sum — Function

  1. sum(f, itr; [init])

Sum the results of calling function f on each element of itr.

The return type is Int for signed integers of less than system word size, and UInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.

The value returned for empty itr can be specified by init. It must be the additive identity (i.e. zero) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

Examples

  1. julia> sum(abs2, [2; 3; 4])
  2. 29

Note the important difference between sum(A) and reduce(+, A) for arrays with small integer eltype:

  1. julia> sum(Int8[100, 28])
  2. 128
  3. julia> reduce(+, Int8[100, 28])
  4. -128

In the former case, the integers are widened to system word size and therefore the result is 128. In the latter case, no such widening happens and integer overflow results in -128.

source

  1. sum(itr; [init])

Returns the sum of all elements in a collection.

The return type is Int for signed integers of less than system word size, and UInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.

The value returned for empty itr can be specified by init. It must be the additive identity (i.e. zero) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

See also: reduce, mapreduce, count, union.

Examples

  1. julia> sum(1:20)
  2. 210
  3. julia> sum(1:20; init = 0.0)
  4. 210.0

source

  1. sum(A::AbstractArray; dims)

Sum elements of an array over the given dimensions.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> sum(A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 4 6
  8. julia> sum(A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 3
  11. 7

source

  1. sum(f, A::AbstractArray; dims)

Sum the results of calling function f on each element of an array over the given dimensions.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> sum(abs2, A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 10 20
  8. julia> sum(abs2, A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 5
  11. 25

source

Base.sum! — Function

  1. sum!(r, A)

Sum elements of A over the singleton dimensions of r, and write results to r.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> sum!([1; 1], A)
  6. 2-element Vector{Int64}:
  7. 3
  8. 7
  9. julia> sum!([1 1], A)
  10. 1×2 Matrix{Int64}:
  11. 4 6

source

Base.prod — Function

  1. prod(f, itr; [init])

Returns the product of f applied to each element of itr.

The return type is Int for signed integers of less than system word size, and UInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.

The value returned for empty itr can be specified by init. It must be the multiplicative identity (i.e. one) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

Examples

  1. julia> prod(abs2, [2; 3; 4])
  2. 576

source

  1. prod(itr; [init])

Returns the product of all elements of a collection.

The return type is Int for signed integers of less than system word size, and UInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.

The value returned for empty itr can be specified by init. It must be the multiplicative identity (i.e. one) as it is unspecified whether init is used for non-empty collections.

Julia 1.6

Keyword argument init requires Julia 1.6 or later.

See also: reduce, cumprod, any.

Examples

  1. julia> prod(1:5)
  2. 120
  3. julia> prod(1:5; init = 1.0)
  4. 120.0

source

  1. prod(A::AbstractArray; dims)

Multiply elements of an array over the given dimensions.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> prod(A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 3 8
  8. julia> prod(A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 2
  11. 12

source

  1. prod(f, A::AbstractArray; dims)

Multiply the results of calling the function f on each element of an array over the given dimensions.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> prod(abs2, A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 9 64
  8. julia> prod(abs2, A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 4
  11. 144

source

Base.prod! — Function

  1. prod!(r, A)

Multiply elements of A over the singleton dimensions of r, and write results to r.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> prod!([1; 1], A)
  6. 2-element Vector{Int64}:
  7. 2
  8. 12
  9. julia> prod!([1 1], A)
  10. 1×2 Matrix{Int64}:
  11. 3 8

source

Base.any — Method

  1. any(itr) -> Bool

Test whether any elements of a boolean collection are true, returning true as soon as the first true value in itr is encountered (short-circuiting). To short-circuit on false, use all.

If the input contains missing values, return missing if all non-missing values are false (or equivalently, if the input contains no true value), following three-valued logic.

See also: all, count, sum, |, , ||.

Examples

  1. julia> a = [true,false,false,true]
  2. 4-element Vector{Bool}:
  3. 1
  4. 0
  5. 0
  6. 1
  7. julia> any(a)
  8. true
  9. julia> any((println(i); v) for (i, v) in enumerate(a))
  10. 1
  11. true
  12. julia> any([missing, true])
  13. true
  14. julia> any([false, missing])
  15. missing

source

Base.any — Method

  1. any(p, itr) -> Bool

Determine whether predicate p returns true for any elements of itr, returning true as soon as the first item in itr for which p returns true is encountered (short-circuiting). To short-circuit on false, use all.

If the input contains missing values, return missing if all non-missing values are false (or equivalently, if the input contains no true value), following three-valued logic.

Examples

  1. julia> any(i->(4<=i<=6), [3,5,7])
  2. true
  3. julia> any(i -> (println(i); i > 3), 1:10)
  4. 1
  5. 2
  6. 3
  7. 4
  8. true
  9. julia> any(i -> i > 0, [1, missing])
  10. true
  11. julia> any(i -> i > 0, [-1, missing])
  12. missing
  13. julia> any(i -> i > 0, [-1, 0])
  14. false

source

Base.any! — Function

  1. any!(r, A)

Test whether any values in A along the singleton dimensions of r are true, and write results to r.

Examples

  1. julia> A = [true false; true false]
  2. 2×2 Matrix{Bool}:
  3. 1 0
  4. 1 0
  5. julia> any!([1; 1], A)
  6. 2-element Vector{Int64}:
  7. 1
  8. 1
  9. julia> any!([1 1], A)
  10. 1×2 Matrix{Int64}:
  11. 1 0

source

Base.all — Method

  1. all(itr) -> Bool

Test whether all elements of a boolean collection are true, returning false as soon as the first false value in itr is encountered (short-circuiting). To short-circuit on true, use any.

If the input contains missing values, return missing if all non-missing values are true (or equivalently, if the input contains no false value), following three-valued logic.

See also: all!, any, count, &, , &&, allunique.

Examples

  1. julia> a = [true,false,false,true]
  2. 4-element Vector{Bool}:
  3. 1
  4. 0
  5. 0
  6. 1
  7. julia> all(a)
  8. false
  9. julia> all((println(i); v) for (i, v) in enumerate(a))
  10. 1
  11. 2
  12. false
  13. julia> all([missing, false])
  14. false
  15. julia> all([true, missing])
  16. missing

source

Base.all — Method

  1. all(p, itr) -> Bool

Determine whether predicate p returns true for all elements of itr, returning false as soon as the first item in itr for which p returns false is encountered (short-circuiting). To short-circuit on true, use any.

If the input contains missing values, return missing if all non-missing values are true (or equivalently, if the input contains no false value), following three-valued logic.

Examples

  1. julia> all(i->(4<=i<=6), [4,5,6])
  2. true
  3. julia> all(i -> (println(i); i < 3), 1:10)
  4. 1
  5. 2
  6. 3
  7. false
  8. julia> all(i -> i > 0, [1, missing])
  9. missing
  10. julia> all(i -> i > 0, [-1, missing])
  11. false
  12. julia> all(i -> i > 0, [1, 2])
  13. true

source

Base.all! — Function

  1. all!(r, A)

Test whether all values in A along the singleton dimensions of r are true, and write results to r.

Examples

  1. julia> A = [true false; true false]
  2. 2×2 Matrix{Bool}:
  3. 1 0
  4. 1 0
  5. julia> all!([1; 1], A)
  6. 2-element Vector{Int64}:
  7. 0
  8. 0
  9. julia> all!([1 1], A)
  10. 1×2 Matrix{Int64}:
  11. 1 0

source

Base.count — Function

  1. count([f=identity,] itr; init=0) -> Integer

Count the number of elements in itr for which the function f returns true. If f is omitted, count the number of true elements in itr (which should be a collection of boolean values). init optionally specifies the value to start counting from and therefore also determines the output type.

Julia 1.6

init keyword was added in Julia 1.6.

See also: any, sum.

Examples

  1. julia> count(i->(4<=i<=6), [2,3,4,5,6])
  2. 3
  3. julia> count([true, false, true, true])
  4. 3
  5. julia> count(>(3), 1:7, init=0x03)
  6. 0x07

source

  1. count(
  2. pattern::Union{AbstractChar,AbstractString,AbstractPattern},
  3. string::AbstractString;
  4. overlap::Bool = false,
  5. )

Return the number of matches for pattern in string. This is equivalent to calling length(findall(pattern, string)) but more efficient.

If overlap=true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from disjoint character ranges.

Julia 1.3

This method requires at least Julia 1.3.

Julia 1.7

Using a character as the pattern requires at least Julia 1.7.

source

  1. count([f=identity,] A::AbstractArray; dims=:)

Count the number of elements in A for which f returns true over the given dimensions.

Julia 1.5

dims keyword was added in Julia 1.5.

Julia 1.6

init keyword was added in Julia 1.6.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> count(<=(2), A, dims=1)
  6. 1×2 Matrix{Int64}:
  7. 1 1
  8. julia> count(<=(2), A, dims=2)
  9. 2×1 Matrix{Int64}:
  10. 2
  11. 0

source

Base.any — Method

  1. any(p, itr) -> Bool

Determine whether predicate p returns true for any elements of itr, returning true as soon as the first item in itr for which p returns true is encountered (short-circuiting). To short-circuit on false, use all.

If the input contains missing values, return missing if all non-missing values are false (or equivalently, if the input contains no true value), following three-valued logic.

Examples

  1. julia> any(i->(4<=i<=6), [3,5,7])
  2. true
  3. julia> any(i -> (println(i); i > 3), 1:10)
  4. 1
  5. 2
  6. 3
  7. 4
  8. true
  9. julia> any(i -> i > 0, [1, missing])
  10. true
  11. julia> any(i -> i > 0, [-1, missing])
  12. missing
  13. julia> any(i -> i > 0, [-1, 0])
  14. false

source

Base.all — Method

  1. all(p, itr) -> Bool

Determine whether predicate p returns true for all elements of itr, returning false as soon as the first item in itr for which p returns false is encountered (short-circuiting). To short-circuit on true, use any.

If the input contains missing values, return missing if all non-missing values are true (or equivalently, if the input contains no false value), following three-valued logic.

Examples

  1. julia> all(i->(4<=i<=6), [4,5,6])
  2. true
  3. julia> all(i -> (println(i); i < 3), 1:10)
  4. 1
  5. 2
  6. 3
  7. false
  8. julia> all(i -> i > 0, [1, missing])
  9. missing
  10. julia> all(i -> i > 0, [-1, missing])
  11. false
  12. julia> all(i -> i > 0, [1, 2])
  13. true

source

Base.foreach — Function

  1. foreach(f, c...) -> Nothing

Call function f on each element of iterable c. For multiple iterable arguments, f is called elementwise, and iteration stops when any iterator is finished.

foreach should be used instead of map when the results of f are not needed, for example in foreach(println, array).

Examples

  1. julia> tri = 1:3:7; res = Int[];
  2. julia> foreach(x -> push!(res, x^2), tri)
  3. julia> res
  4. 3-element Vector{Int64}:
  5. 1
  6. 16
  7. 49
  8. julia> foreach((x, y) -> println(x, " with ", y), tri, 'a':'z')
  9. 1 with a
  10. 4 with b
  11. 7 with c

source

Base.map — Function

  1. map(f, c...) -> collection

Transform collection c by applying f to each element. For multiple collection arguments, apply f elementwise, and stop when when any of them is exhausted.

See also map!, foreach, mapreduce, mapslices, zip, Iterators.map.

Examples

  1. julia> map(x -> x * 2, [1, 2, 3])
  2. 3-element Vector{Int64}:
  3. 2
  4. 4
  5. 6
  6. julia> map(+, [1, 2, 3], [10, 20, 30, 400, 5000])
  7. 3-element Vector{Int64}:
  8. 11
  9. 22
  10. 33

source

Base.map! — Function

  1. map!(function, destination, collection...)

Like map, but stores the result in destination rather than a new collection. destination must be at least as large as the smallest collection.

See also: map, foreach, zip, copyto!.

Examples

  1. julia> a = zeros(3);
  2. julia> map!(x -> x * 2, a, [1, 2, 3]);
  3. julia> a
  4. 3-element Vector{Float64}:
  5. 2.0
  6. 4.0
  7. 6.0
  8. julia> map!(+, zeros(Int, 5), 100:999, 1:3)
  9. 5-element Vector{Int64}:
  10. 101
  11. 103
  12. 105
  13. 0
  14. 0

source

  1. map!(f, values(dict::AbstractDict))

Modifies dict by transforming each value from val to f(val). Note that the type of dict cannot be changed: if f(val) is not an instance of the value type of dict then it will be converted to the value type if possible and otherwise raise an error.

Julia 1.2

map!(f, values(dict::AbstractDict)) requires Julia 1.2 or later.

Examples

  1. julia> d = Dict(:a => 1, :b => 2)
  2. Dict{Symbol, Int64} with 2 entries:
  3. :a => 1
  4. :b => 2
  5. julia> map!(v -> v-1, values(d))
  6. ValueIterator for a Dict{Symbol, Int64} with 2 entries. Values:
  7. 0
  8. 1

source

Base.mapreduce — Method

  1. mapreduce(f, op, itrs...; [init])

Apply function f to each element(s) in itrs, and then reduce the result using the binary function op. If provided, init must be a neutral element for op that will be returned for empty collections. It is unspecified whether init is used for non-empty collections. In general, it will be necessary to provide init to work with empty collections.

mapreduce is functionally equivalent to calling reduce(op, map(f, itr); init=init), but will in general execute faster since no intermediate collection needs to be created. See documentation for reduce and map.

Julia 1.2

mapreduce with multiple iterators requires Julia 1.2 or later.

Examples

  1. julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9
  2. 14

The associativity of the reduction is implementation-dependent. Additionally, some implementations may reuse the return value of f for elements that appear multiple times in itr. Use mapfoldl or mapfoldr instead for guaranteed left or right associativity and invocation of f for every value.

source

Base.mapfoldl — Method

  1. mapfoldl(f, op, itr; [init])

Like mapreduce, but with guaranteed left associativity, as in foldl. If provided, the keyword argument init will be used exactly once. In general, it will be necessary to provide init to work with empty collections.

source

Base.mapfoldr — Method

  1. mapfoldr(f, op, itr; [init])

Like mapreduce, but with guaranteed right associativity, as in foldr. If provided, the keyword argument init will be used exactly once. In general, it will be necessary to provide init to work with empty collections.

source

Base.first — Function

  1. first(coll)

Get the first element of an iterable collection. Return the start point of an AbstractRange even if it is empty.

See also: only, firstindex, last.

Examples

  1. julia> first(2:2:10)
  2. 2
  3. julia> first([1; 2; 3; 4])
  4. 1

source

  1. first(itr, n::Integer)

Get the first n elements of the iterable collection itr, or fewer elements if itr is not long enough.

See also: startswith, Iterators.take.

Julia 1.6

This method requires at least Julia 1.6.

Examples

  1. julia> first(["foo", "bar", "qux"], 2)
  2. 2-element Vector{String}:
  3. "foo"
  4. "bar"
  5. julia> first(1:6, 10)
  6. 1:6
  7. julia> first(Bool[], 1)
  8. Bool[]

source

  1. first(s::AbstractString, n::Integer)

Get a string consisting of the first n characters of s.

Examples

  1. julia> first("∀ϵ≠0: ϵ²>0", 0)
  2. ""
  3. julia> first("∀ϵ≠0: ϵ²>0", 1)
  4. "∀"
  5. julia> first("∀ϵ≠0: ϵ²>0", 3)
  6. "∀ϵ≠"

source

Base.last — Function

  1. last(coll)

Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling lastindex to get the last index. Return the end point of an AbstractRange even if it is empty.

See also first, endswith.

Examples

  1. julia> last(1:2:10)
  2. 9
  3. julia> last([1; 2; 3; 4])
  4. 4

source

  1. last(itr, n::Integer)

Get the last n elements of the iterable collection itr, or fewer elements if itr is not long enough.

Julia 1.6

This method requires at least Julia 1.6.

Examples

  1. julia> last(["foo", "bar", "qux"], 2)
  2. 2-element Vector{String}:
  3. "bar"
  4. "qux"
  5. julia> last(1:6, 10)
  6. 1:6
  7. julia> last(Float64[], 1)
  8. Float64[]

source

  1. last(s::AbstractString, n::Integer)

Get a string consisting of the last n characters of s.

Examples

  1. julia> last("∀ϵ≠0: ϵ²>0", 0)
  2. ""
  3. julia> last("∀ϵ≠0: ϵ²>0", 1)
  4. "0"
  5. julia> last("∀ϵ≠0: ϵ²>0", 3)
  6. "²>0"

source

Base.front — Function

  1. front(x::Tuple)::Tuple

Return a Tuple consisting of all but the last component of x.

See also: first, tail.

Examples

  1. julia> Base.front((1,2,3))
  2. (1, 2)
  3. julia> Base.front(())
  4. ERROR: ArgumentError: Cannot call front on an empty tuple.

source

Base.tail — Function

  1. tail(x::Tuple)::Tuple

Return a Tuple consisting of all but the first component of x.

See also: front, rest, first, Iterators.peel.

Examples

  1. julia> Base.tail((1,2,3))
  2. (2, 3)
  3. julia> Base.tail(())
  4. ERROR: ArgumentError: Cannot call tail on an empty tuple.

source

Base.step — Function

  1. step(r)

Get the step size of an AbstractRange object.

Examples

  1. julia> step(1:10)
  2. 1
  3. julia> step(1:2:10)
  4. 2
  5. julia> step(2.5:0.3:10.9)
  6. 0.3
  7. julia> step(range(2.5, stop=10.9, length=85))
  8. 0.1

source

Base.collect — Method

  1. collect(collection)

Return an Array of all items in a collection or iterator. For dictionaries, returns Pair{KeyType, ValType}. If the argument is array-like or is an iterator with the HasShape trait, the result will have the same shape and number of dimensions as the argument.

Used by comprehensions to turn a generator into an Array.

Examples

  1. julia> collect(1:2:13)
  2. 7-element Vector{Int64}:
  3. 1
  4. 3
  5. 5
  6. 7
  7. 9
  8. 11
  9. 13
  10. julia> [x^2 for x in 1:8 if isodd(x)]
  11. 4-element Vector{Int64}:
  12. 1
  13. 9
  14. 25
  15. 49

source

Base.collect — Method

  1. collect(element_type, collection)

Return an Array with the given element type of all items in a collection or iterable. The result has the same shape and number of dimensions as collection.

Examples

  1. julia> collect(Float64, 1:2:5)
  2. 3-element Vector{Float64}:
  3. 1.0
  4. 3.0
  5. 5.0

source

Base.filter — Function

  1. filter(f, a)

Return a copy of collection a, removing elements for which f is false. The function f is passed one argument.

Julia 1.4

Support for a as a tuple requires at least Julia 1.4.

See also: filter!, Iterators.filter.

Examples

  1. julia> a = 1:10
  2. 1:10
  3. julia> filter(isodd, a)
  4. 5-element Vector{Int64}:
  5. 1
  6. 3
  7. 5
  8. 7
  9. 9

source

  1. filter(f, d::AbstractDict)

Return a copy of d, removing elements for which f is false. The function f is passed key=>value pairs.

Examples

  1. julia> d = Dict(1=>"a", 2=>"b")
  2. Dict{Int64, String} with 2 entries:
  3. 2 => "b"
  4. 1 => "a"
  5. julia> filter(p->isodd(p.first), d)
  6. Dict{Int64, String} with 1 entry:
  7. 1 => "a"

source

  1. filter(f, itr::SkipMissing{<:AbstractArray})

Return a vector similar to the array wrapped by the given SkipMissing iterator but with all missing elements and those for which f returns false removed.

Julia 1.2

This method requires Julia 1.2 or later.

Examples

  1. julia> x = [1 2; missing 4]
  2. 2×2 Matrix{Union{Missing, Int64}}:
  3. 1 2
  4. missing 4
  5. julia> filter(isodd, skipmissing(x))
  6. 1-element Vector{Int64}:
  7. 1

source

Base.filter! — Function

  1. filter!(f, a)

Update collection a, removing elements for which f is false. The function f is passed one argument.

Examples

  1. julia> filter!(isodd, Vector(1:10))
  2. 5-element Vector{Int64}:
  3. 1
  4. 3
  5. 5
  6. 7
  7. 9

source

  1. filter!(f, d::AbstractDict)

Update d, removing elements for which f is false. The function f is passed key=>value pairs.

Example

  1. julia> d = Dict(1=>"a", 2=>"b", 3=>"c")
  2. Dict{Int64, String} with 3 entries:
  3. 2 => "b"
  4. 3 => "c"
  5. 1 => "a"
  6. julia> filter!(p->isodd(p.first), d)
  7. Dict{Int64, String} with 2 entries:
  8. 3 => "c"
  9. 1 => "a"

source

Base.replace — Method

  1. replace(A, old_new::Pair...; [count::Integer])

Return a copy of collection A where, for each pair old=>new in old_new, all occurrences of old are replaced by new. Equality is determined using isequal. If count is specified, then replace at most count occurrences in total.

The element type of the result is chosen using promotion (see promote_type) based on the element type of A and on the types of the new values in pairs. If count is omitted and the element type of A is a Union, the element type of the result will not include singleton types which are replaced with values of a different type: for example, Union{T,Missing} will become T if missing is replaced.

See also replace!, splice!, delete!, insert!.

Julia 1.7

Version 1.7 is required to replace elements of a Tuple.

Examples

  1. julia> replace([1, 2, 1, 3], 1=>0, 2=>4, count=2)
  2. 4-element Vector{Int64}:
  3. 0
  4. 4
  5. 1
  6. 3
  7. julia> replace([1, missing], missing=>0)
  8. 2-element Vector{Int64}:
  9. 1
  10. 0

source

Base.replace — Method

  1. replace(new::Function, A; [count::Integer])

Return a copy of A where each value x in A is replaced by new(x). If count is specified, then replace at most count values in total (replacements being defined as new(x) !== x).

Julia 1.7

Version 1.7 is required to replace elements of a Tuple.

Examples

  1. julia> replace(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
  2. 4-element Vector{Int64}:
  3. 2
  4. 2
  5. 6
  6. 4
  7. julia> replace(Dict(1=>2, 3=>4)) do kv
  8. first(kv) < 3 ? first(kv)=>3 : kv
  9. end
  10. Dict{Int64, Int64} with 2 entries:
  11. 3 => 4
  12. 1 => 3

source

Base.replace! — Function

  1. replace!(A, old_new::Pair...; [count::Integer])

For each pair old=>new in old_new, replace all occurrences of old in collection A by new. Equality is determined using isequal. If count is specified, then replace at most count occurrences in total. See also replace.

Examples

  1. julia> replace!([1, 2, 1, 3], 1=>0, 2=>4, count=2)
  2. 4-element Vector{Int64}:
  3. 0
  4. 4
  5. 1
  6. 3
  7. julia> replace!(Set([1, 2, 3]), 1=>0)
  8. Set{Int64} with 3 elements:
  9. 0
  10. 2
  11. 3

source

  1. replace!(new::Function, A; [count::Integer])

Replace each element x in collection A by new(x). If count is specified, then replace at most count values in total (replacements being defined as new(x) !== x).

Examples

  1. julia> replace!(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
  2. 4-element Vector{Int64}:
  3. 2
  4. 2
  5. 6
  6. 4
  7. julia> replace!(Dict(1=>2, 3=>4)) do kv
  8. first(kv) < 3 ? first(kv)=>3 : kv
  9. end
  10. Dict{Int64, Int64} with 2 entries:
  11. 3 => 4
  12. 1 => 3
  13. julia> replace!(x->2x, Set([3, 6]))
  14. Set{Int64} with 2 elements:
  15. 6
  16. 12

source

Base.rest — Function

  1. Base.rest(collection[, itr_state])

Generic function for taking the tail of collection, starting from a specific iteration state itr_state. Return a Tuple, if collection itself is a Tuple, a subtype of AbstractVector, if collection is an AbstractArray, a subtype of AbstractString if collection is an AbstractString, and an arbitrary iterator, falling back to Iterators.rest(collection[, itr_state]), otherwise.

Can be overloaded for user-defined collection types to customize the behavior of slurping in assignments, like a, b... = collection.

Julia 1.6

Base.rest requires at least Julia 1.6.

See also: first, Iterators.rest.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> first, state = iterate(a)
  6. (1, 2)
  7. julia> first, Base.rest(a, state)
  8. (1, [3, 2, 4])

source

可索引集合

Base.getindex — Function

  1. getindex(collection, key...)

Retrieve the value(s) stored at the given key or index within a collection. The syntax a[i,j,...] is converted by the compiler to getindex(a, i, j, ...).

See also get, keys, eachindex.

Examples

  1. julia> A = Dict("a" => 1, "b" => 2)
  2. Dict{String, Int64} with 2 entries:
  3. "b" => 2
  4. "a" => 1
  5. julia> getindex(A, "a")
  6. 1

source

Base.setindex! — Function

  1. setindex!(collection, value, key...)

Store the given value at the given key or index within a collection. The syntax a[i,j,...] = x is converted by the compiler to (setindex!(a, x, i, j, ...); x).

source

Base.firstindex — Function

  1. firstindex(collection) -> Integer
  2. firstindex(collection, d) -> Integer

Return the first index of collection. If d is given, return the first index of collection along dimension d.

The syntaxes A[begin] and A[1, begin] lower to A[firstindex(A)] and A[1, firstindex(A, 2)], respectively.

See also: first, axes, lastindex, nextind.

Examples

  1. julia> firstindex([1,2,4])
  2. 1
  3. julia> firstindex(rand(3,4,5), 2)
  4. 1

source

Base.lastindex — Function

  1. lastindex(collection) -> Integer
  2. lastindex(collection, d) -> Integer

Return the last index of collection. If d is given, return the last index of collection along dimension d.

The syntaxes A[end] and A[end, end] lower to A[lastindex(A)] and A[lastindex(A, 1), lastindex(A, 2)], respectively.

See also: axes, firstindex, eachindex, prevind.

Examples

  1. julia> lastindex([1,2,4])
  2. 3
  3. julia> lastindex(rand(3,4,5), 2)
  4. 4

source

以下类型均完全实现了上述函数:

以下类型仅实现了部分上述函数:

字典

Dict 是一个标准字典。其实现利用了 hash 作为键的哈希函数和 isequal 来决定是否相等。对于自定义类型,可以定义这两个函数来重载它们在哈希表内的存储方式。

IdDict 是一种特殊的哈希表,在里面键始终是对象标识符。

WeakKeyDict 是一个哈希表的实现,里面键是对象的弱引用, 所以即使键在哈希表中被引用也有可能被垃圾回收。 它像 Dict 一样使用 hash 来做哈希和 isequal 来做相等判断, 但是它不会在插入时转换键,这点不像 Dict

Dicts 可以由传递含有 => 的成对对象给 Dict 的构造函数来被创建:Dict("A"=>1, "B"=>2)。 这个调用会尝试从键值对中推到类型信息(比如这个例子创造了一个 Dict{String, Int64})。 为了显式指定类型,请使用语法 Dict{KeyType,ValueType}(...)。例如:Dict{String,Int32}("A"=>1, "B"=>2)

字典也可以用生成器创建。例如:Dict(i => f(i) for i = 1:10)

对于字典 D,若键 x 的值存在,则语法 D[x] 返回 x 的值;否则抛出一个错误。 D[x] = y 存储键值对 x => yD 中,会覆盖键 x 的已有的值。 多个参数传入D[...] 会被转化成元组; 例如:语法 D[x,y] 等于 D[(x,y)],也就是说,它指向键为元组 (x,y) 的值。

Base.AbstractDict — Type

  1. AbstractDict{K, V}

Supertype for dictionary-like types with keys of type K and values of type V. Dict, IdDict and other types are subtypes of this. An AbstractDict{K, V} should be an iterator of Pair{K, V}.

source

Base.Dict — Type

  1. Dict([itr])

Dict{K,V}() constructs a hash table with keys of type K and values of type V. Keys are compared with isequal and hashed with hash.

Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.

Examples

  1. julia> Dict([("A", 1), ("B", 2)])
  2. Dict{String, Int64} with 2 entries:
  3. "B" => 2
  4. "A" => 1

Alternatively, a sequence of pair arguments may be passed.

  1. julia> Dict("A"=>1, "B"=>2)
  2. Dict{String, Int64} with 2 entries:
  3. "B" => 2
  4. "A" => 1

source

Base.IdDict — Type

  1. IdDict([itr])

IdDict{K,V}() constructs a hash table using objectid as hash and === as equality with keys of type K and values of type V.

See Dict for further help. In the example below, The Dict keys are all isequal and therefore get hashed the same, so they get overwritten. The IdDict hashes by object-id, and thus preserves the 3 different keys.

Examples

  1. julia> Dict(true => "yes", 1 => "no", 1.0 => "maybe")
  2. Dict{Real, String} with 1 entry:
  3. 1.0 => "maybe"
  4. julia> IdDict(true => "yes", 1 => "no", 1.0 => "maybe")
  5. IdDict{Any, String} with 3 entries:
  6. true => "yes"
  7. 1.0 => "maybe"
  8. 1 => "no"

source

Base.WeakKeyDict — Type

  1. WeakKeyDict([itr])

WeakKeyDict() constructs a hash table where the keys are weak references to objects which may be garbage collected even when referenced in a hash table.

See Dict for further help. Note, unlike Dict, WeakKeyDict does not convert keys on insertion, as this would imply the key object was unreferenced anywhere before insertion.

source

Base.ImmutableDict — Type

  1. ImmutableDict

ImmutableDict is a dictionary implemented as an immutable linked list, which is optimal for small dictionaries that are constructed over many individual insertions. Note that it is not possible to remove a value, although it can be partially overridden and hidden by inserting a new value with the same key.

  1. ImmutableDict(KV::Pair)

Create a new entry in the ImmutableDict for a key => value pair

  • use (key => value) in dict to see if this particular combination is in the properties set
  • use get(dict, key, default) to retrieve the most recent value for a particular key

source

Base.haskey — Function

  1. haskey(collection, key) -> Bool

Determine whether a collection has a mapping for a given key.

Examples

  1. julia> D = Dict('a'=>2, 'b'=>3)
  2. Dict{Char, Int64} with 2 entries:
  3. 'a' => 2
  4. 'b' => 3
  5. julia> haskey(D, 'a')
  6. true
  7. julia> haskey(D, 'c')
  8. false

source

Base.get — Function

  1. get(collection, key, default)

Return the value stored for the given key, or the given default value if no mapping for the key is present.

Julia 1.7

For tuples and numbers, this function requires at least Julia 1.7.

Examples

  1. julia> d = Dict("a"=>1, "b"=>2);
  2. julia> get(d, "a", 3)
  3. 1
  4. julia> get(d, "c", 3)
  5. 3

source

  1. get(f::Function, collection, key)

Return the value stored for the given key, or if no mapping for the key is present, return f(). Use get! to also store the default value in the dictionary.

This is intended to be called using do block syntax

  1. get(dict, key) do
  2. # default value calculated here
  3. time()
  4. end

source

Base.get! — Function

  1. get!(collection, key, default)

Return the value stored for the given key, or if no mapping for the key is present, store key => default, and return default.

Examples

  1. julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
  2. julia> get!(d, "a", 5)
  3. 1
  4. julia> get!(d, "d", 4)
  5. 4
  6. julia> d
  7. Dict{String, Int64} with 4 entries:
  8. "c" => 3
  9. "b" => 2
  10. "a" => 1
  11. "d" => 4

source

  1. get!(f::Function, collection, key)

Return the value stored for the given key, or if no mapping for the key is present, store key => f(), and return f().

This is intended to be called using do block syntax.

Examples

  1. julia> squares = Dict{Int, Int}();
  2. julia> function get_square!(d, i)
  3. get!(d, i) do
  4. i^2
  5. end
  6. end
  7. get_square! (generic function with 1 method)
  8. julia> get_square!(squares, 2)
  9. 4
  10. julia> squares
  11. Dict{Int64, Int64} with 1 entry:
  12. 2 => 4

source

Base.getkey — Function

  1. getkey(collection, key, default)

Return the key matching argument key if one exists in collection, otherwise return default.

Examples

  1. julia> D = Dict('a'=>2, 'b'=>3)
  2. Dict{Char, Int64} with 2 entries:
  3. 'a' => 2
  4. 'b' => 3
  5. julia> getkey(D, 'a', 1)
  6. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  7. julia> getkey(D, 'd', 'a')
  8. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

source

Base.delete! — Function

  1. delete!(collection, key)

Delete the mapping for the given key in a collection, if any, and return the collection.

Examples

  1. julia> d = Dict("a"=>1, "b"=>2)
  2. Dict{String, Int64} with 2 entries:
  3. "b" => 2
  4. "a" => 1
  5. julia> delete!(d, "b")
  6. Dict{String, Int64} with 1 entry:
  7. "a" => 1
  8. julia> delete!(d, "b") # d is left unchanged
  9. Dict{String, Int64} with 1 entry:
  10. "a" => 1

source

Base.pop! — Method

  1. pop!(collection, key[, default])

Delete and return the mapping for key if it exists in collection, otherwise return default, or throw an error if default is not specified.

Examples

  1. julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
  2. julia> pop!(d, "a")
  3. 1
  4. julia> pop!(d, "d")
  5. ERROR: KeyError: key "d" not found
  6. Stacktrace:
  7. [...]
  8. julia> pop!(d, "e", 4)
  9. 4

source

Base.keys — Function

  1. keys(iterator)

For an iterator or collection that has keys and values (e.g. arrays and dictionaries), return an iterator over the keys.

source

Base.values — Function

  1. values(iterator)

For an iterator or collection that has keys and values, return an iterator over the values. This function simply returns its argument by default, since the elements of a general iterator are normally considered its “values”.

Examples

  1. julia> d = Dict("a"=>1, "b"=>2);
  2. julia> values(d)
  3. ValueIterator for a Dict{String, Int64} with 2 entries. Values:
  4. 2
  5. 1
  6. julia> values([2])
  7. 1-element Vector{Int64}:
  8. 2

source

  1. values(a::AbstractDict)

Return an iterator over all values in a collection. collect(values(a)) returns an array of values. When the values are stored internally in a hash table, as is the case for Dict, the order in which they are returned may vary. But keys(a) and values(a) both iterate a and return the elements in the same order.

Examples

  1. julia> D = Dict('a'=>2, 'b'=>3)
  2. Dict{Char, Int64} with 2 entries:
  3. 'a' => 2
  4. 'b' => 3
  5. julia> collect(values(D))
  6. 2-element Vector{Int64}:
  7. 2
  8. 3

source

Base.pairs — Function

  1. pairs(IndexLinear(), A)
  2. pairs(IndexCartesian(), A)
  3. pairs(IndexStyle(A), A)

An iterator that accesses each element of the array A, returning i => x, where i is the index for the element and x = A[i]. Identical to pairs(A), except that the style of index can be selected. Also similar to enumerate(A), except i will be a valid index for A, while enumerate always counts from 1 regardless of the indices of A.

Specifying IndexLinear() ensures that i will be an integer; specifying IndexCartesian() ensures that i will be a CartesianIndex; specifying IndexStyle(A) chooses whichever has been defined as the native indexing style for array A.

Mutation of the bounds of the underlying array will invalidate this iterator.

Examples

  1. julia> A = ["a" "d"; "b" "e"; "c" "f"];
  2. julia> for (index, value) in pairs(IndexStyle(A), A)
  3. println("$index $value")
  4. end
  5. 1 a
  6. 2 b
  7. 3 c
  8. 4 d
  9. 5 e
  10. 6 f
  11. julia> S = view(A, 1:2, :);
  12. julia> for (index, value) in pairs(IndexStyle(S), S)
  13. println("$index $value")
  14. end
  15. CartesianIndex(1, 1) a
  16. CartesianIndex(2, 1) b
  17. CartesianIndex(1, 2) d
  18. CartesianIndex(2, 2) e

See also IndexStyle, axes.

source

  1. pairs(collection)

Return an iterator over key => value pairs for any collection that maps a set of keys to a set of values. This includes arrays, where the keys are the array indices.

source

Base.merge — Function

  1. merge(d::AbstractDict, others::AbstractDict...)

Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed. See also mergewith for custom handling of values with the same key.

Examples

  1. julia> a = Dict("foo" => 0.0, "bar" => 42.0)
  2. Dict{String, Float64} with 2 entries:
  3. "bar" => 42.0
  4. "foo" => 0.0
  5. julia> b = Dict("baz" => 17, "bar" => 4711)
  6. Dict{String, Int64} with 2 entries:
  7. "bar" => 4711
  8. "baz" => 17
  9. julia> merge(a, b)
  10. Dict{String, Float64} with 3 entries:
  11. "bar" => 4711.0
  12. "baz" => 17.0
  13. "foo" => 0.0
  14. julia> merge(b, a)
  15. Dict{String, Float64} with 3 entries:
  16. "bar" => 42.0
  17. "baz" => 17.0
  18. "foo" => 0.0

source

  1. merge(a::NamedTuple, bs::NamedTuple...)

Construct a new named tuple by merging two or more existing ones, in a left-associative manner. Merging proceeds left-to-right, between pairs of named tuples, and so the order of fields present in both the leftmost and rightmost named tuples take the same position as they are found in the leftmost named tuple. However, values are taken from matching fields in the rightmost named tuple that contains that field. Fields present in only the rightmost named tuple of a pair are appended at the end. A fallback is implemented for when only a single named tuple is supplied, with signature merge(a::NamedTuple).

Julia 1.1

Merging 3 or more NamedTuple requires at least Julia 1.1.

Examples

  1. julia> merge((a=1, b=2, c=3), (b=4, d=5))
  2. (a = 1, b = 4, c = 3, d = 5)
  1. julia> merge((a=1, b=2), (b=3, c=(d=1,)), (c=(d=2,),))
  2. (a = 1, b = 3, c = (d = 2,))

source

  1. merge(a::NamedTuple, iterable)

Interpret an iterable of key-value pairs as a named tuple, and perform a merge.

  1. julia> merge((a=1, b=2, c=3), [:b=>4, :d=>5])
  2. (a = 1, b = 4, c = 3, d = 5)

source

Base.mergewith — Function

  1. mergewith(combine, d::AbstractDict, others::AbstractDict...)
  2. mergewith(combine)
  3. merge(combine, d::AbstractDict, others::AbstractDict...)

Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. Values with the same key will be combined using the combiner function. The curried form mergewith(combine) returns the function (args...) -> mergewith(combine, args...).

Method merge(combine::Union{Function,Type}, args...) as an alias of mergewith(combine, args...) is still available for backward compatibility.

Julia 1.5

mergewith requires Julia 1.5 or later.

Examples

  1. julia> a = Dict("foo" => 0.0, "bar" => 42.0)
  2. Dict{String, Float64} with 2 entries:
  3. "bar" => 42.0
  4. "foo" => 0.0
  5. julia> b = Dict("baz" => 17, "bar" => 4711)
  6. Dict{String, Int64} with 2 entries:
  7. "bar" => 4711
  8. "baz" => 17
  9. julia> mergewith(+, a, b)
  10. Dict{String, Float64} with 3 entries:
  11. "bar" => 4753.0
  12. "baz" => 17.0
  13. "foo" => 0.0
  14. julia> ans == mergewith(+)(a, b)
  15. true

source

Base.merge! — Function

  1. merge!(d::AbstractDict, others::AbstractDict...)

Update collection with pairs from the other collections. See also merge.

Examples

  1. julia> d1 = Dict(1 => 2, 3 => 4);
  2. julia> d2 = Dict(1 => 4, 4 => 5);
  3. julia> merge!(d1, d2);
  4. julia> d1
  5. Dict{Int64, Int64} with 3 entries:
  6. 4 => 5
  7. 3 => 4
  8. 1 => 4

source

Base.mergewith! — Function

  1. mergewith!(combine, d::AbstractDict, others::AbstractDict...) -> d
  2. mergewith!(combine)
  3. merge!(combine, d::AbstractDict, others::AbstractDict...) -> d

Update collection with pairs from the other collections. Values with the same key will be combined using the combiner function. The curried form mergewith!(combine) returns the function (args...) -> mergewith!(combine, args...).

Method merge!(combine::Union{Function,Type}, args...) as an alias of mergewith!(combine, args...) is still available for backward compatibility.

Julia 1.5

mergewith! requires Julia 1.5 or later.

Examples

  1. julia> d1 = Dict(1 => 2, 3 => 4);
  2. julia> d2 = Dict(1 => 4, 4 => 5);
  3. julia> mergewith!(+, d1, d2);
  4. julia> d1
  5. Dict{Int64, Int64} with 3 entries:
  6. 4 => 5
  7. 3 => 4
  8. 1 => 6
  9. julia> mergewith!(-, d1, d1);
  10. julia> d1
  11. Dict{Int64, Int64} with 3 entries:
  12. 4 => 0
  13. 3 => 0
  14. 1 => 0
  15. julia> foldl(mergewith!(+), [d1, d2]; init=Dict{Int64, Int64}())
  16. Dict{Int64, Int64} with 3 entries:
  17. 4 => 5
  18. 3 => 0
  19. 1 => 4

source

Base.sizehint! — Function

  1. sizehint!(s, n)

Suggest that collection s reserve capacity for at least n elements. This can improve performance.

Notes on the performance model

For types that support sizehint!,

  1. push! and append! methods generally may (but are not required to) preallocate extra storage. For types implemented in Base, they typically do, using a heuristic optimized for a general use case.

  2. sizehint! may control this preallocation. Again, it typically does this for types in Base.

  3. empty! is nearly costless (and O(1)) for types that support this kind of preallocation.

source

Base.keytype — Function

  1. keytype(T::Type{<:AbstractArray})
  2. keytype(A::AbstractArray)

Return the key type of an array. This is equal to the eltype of the result of keys(...), and is provided mainly for compatibility with the dictionary interface.

Examples

  1. julia> keytype([1, 2, 3]) == Int
  2. true
  3. julia> keytype([1 2; 3 4])
  4. CartesianIndex{2}

Julia 1.2

For arrays, this function requires at least Julia 1.2.

source

  1. keytype(type)

Get the key type of a dictionary type. Behaves similarly to eltype.

Examples

  1. julia> keytype(Dict(Int32(1) => "foo"))
  2. Int32

source

Base.valtype — Function

  1. valtype(T::Type{<:AbstractArray})
  2. valtype(A::AbstractArray)

Return the value type of an array. This is identical to eltype and is provided mainly for compatibility with the dictionary interface.

Examples

  1. julia> valtype(["one", "two", "three"])
  2. String

Julia 1.2

For arrays, this function requires at least Julia 1.2.

source

  1. valtype(type)

Get the value type of a dictionary type. Behaves similarly to eltype.

Examples

  1. julia> valtype(Dict(Int32(1) => "foo"))
  2. String

source

以下类型均完全实现了上述函数:

以下类型仅实现了部分上述函数:

类似 Set 的集合

Base.AbstractSet — Type

  1. AbstractSet{T}

Supertype for set-like types whose elements are of type T. Set, BitSet and other types are subtypes of this.

source

Base.Set — Type

  1. Set([itr])

Construct a Set of the values generated by the given iterable object, or an empty set. Should be used instead of BitSet for sparse integer sets, or for sets of arbitrary objects.

See also: push!, empty!, union!, in.

source

Base.BitSet — Type

  1. BitSet([itr])

Construct a sorted set of Ints generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. If the set will be sparse (for example, holding a few very large integers), use Set instead.

source

Base.union — Function

  1. union(s, itrs...)
  2. ∪(s, itrs...)

Construct the union of sets. Maintain order with arrays.

See also: intersect, isdisjoint, vcat, Iterators.flatten.

Examples

  1. julia> union([1, 2], [3, 4])
  2. 4-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. julia> union([1, 2], [2, 4])
  8. 3-element Vector{Int64}:
  9. 1
  10. 2
  11. 4
  12. julia> union([4, 2], 1:2)
  13. 3-element Vector{Int64}:
  14. 4
  15. 2
  16. 1
  17. julia> union(Set([1, 2]), 2:3)
  18. Set{Int64} with 3 elements:
  19. 2
  20. 3
  21. 1

source

Base.union! — Function

  1. union!(s::Union{AbstractSet,AbstractVector}, itrs...)

Construct the union of passed in sets and overwrite s with the result. Maintain order with arrays.

Examples

  1. julia> a = Set([1, 3, 4, 5]);
  2. julia> union!(a, 1:2:8);
  3. julia> a
  4. Set{Int64} with 5 elements:
  5. 5
  6. 4
  7. 7
  8. 3
  9. 1

source

Base.intersect — Function

  1. intersect(s, itrs...)
  2. ∩(s, itrs...)

Construct the intersection of sets. Maintain order with arrays.

See also: setdiff, isdisjoint, issubset, issetequal.

Examples

  1. julia> intersect([1, 2, 3], [3, 4, 5])
  2. 1-element Vector{Int64}:
  3. 3
  4. julia> intersect([1, 4, 4, 5, 6], [4, 6, 6, 7, 8])
  5. 2-element Vector{Int64}:
  6. 4
  7. 6
  8. julia> intersect(Set([1, 2]), BitSet([2, 3]))
  9. Set{Int64} with 1 element:
  10. 2

source

Base.setdiff — Function

  1. setdiff(s, itrs...)

Construct the set of elements in s but not in any of the iterables in itrs. Maintain order with arrays.

See also setdiff!, union and intersect.

Examples

  1. julia> setdiff([1,2,3], [3,4,5])
  2. 2-element Vector{Int64}:
  3. 1
  4. 2

source

Base.setdiff! — Function

  1. setdiff!(s, itrs...)

Remove from set s (in-place) each element of each iterable from itrs. Maintain order with arrays.

Examples

  1. julia> a = Set([1, 3, 4, 5]);
  2. julia> setdiff!(a, 1:2:6);
  3. julia> a
  4. Set{Int64} with 1 element:
  5. 4

source

Base.symdiff — Function

  1. symdiff(s, itrs...)

Construct the symmetric difference of elements in the passed in sets. When s is not an AbstractSet, the order is maintained. Note that in this case the multiplicity of elements matters.

See also symdiff!, setdiff, union and intersect.

Examples

  1. julia> symdiff([1,2,3], [3,4,5], [4,5,6])
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 6
  6. julia> symdiff([1,2,1], [2, 1, 2])
  7. 2-element Vector{Int64}:
  8. 1
  9. 2
  10. julia> symdiff(unique([1,2,1]), unique([2, 1, 2]))
  11. Int64[]

source

Base.symdiff! — Function

  1. symdiff!(s::Union{AbstractSet,AbstractVector}, itrs...)

Construct the symmetric difference of the passed in sets, and overwrite s with the result. When s is an array, the order is maintained. Note that in this case the multiplicity of elements matters.

source

Base.intersect! — Function

  1. intersect!(s::Union{AbstractSet,AbstractVector}, itrs...)

Intersect all passed in sets and overwrite s with the result. Maintain order with arrays.

source

Base.issubset — Function

  1. issubset(a, b) -> Bool
  2. ⊆(a, b) -> Bool
  3. ⊇(b, a) -> Bool

Determine whether every element of a is also in b, using in.

See also , , , , contains.

Examples

  1. julia> issubset([1, 2], [1, 2, 3])
  2. true
  3. julia> [1, 2, 3] [1, 2]
  4. false
  5. julia> [1, 2, 3] [1, 2]
  6. true

source

Base.:⊈ — Function

  1. ⊈(a, b) -> Bool
  2. ⊉(b, a) -> Bool

Negation of and , i.e. checks that a is not a subset of b.

See also issubset (), .

Examples

  1. julia> (1, 2) (2, 3)
  2. true
  3. julia> (1, 2) (1, 2, 3)
  4. false

source

Base.:⊊ — Function

  1. ⊊(a, b) -> Bool
  2. ⊋(b, a) -> Bool

Determines if a is a subset of, but not equal to, b.

See also issubset (), .

Examples

  1. julia> (1, 2) (1, 2, 3)
  2. true
  3. julia> (1, 2) (1, 2)
  4. false

source

Base.issetequal — Function

  1. issetequal(a, b) -> Bool

Determine whether a and b have the same elements. Equivalent to a ⊆ b && b ⊆ a but more efficient when possible.

See also: isdisjoint, union.

Examples

  1. julia> issetequal([1, 2], [1, 2, 3])
  2. false
  3. julia> issetequal([1, 2], [2, 1])
  4. true

source

Base.isdisjoint — Function

  1. isdisjoint(v1, v2) -> Bool

Return whether the collections v1 and v2 are disjoint, i.e. whether their intersection is empty.

See also: issetequal, intersect.

Julia 1.5

This function requires at least Julia 1.5.

source

以下类型均完全实现了上述函数:

以下类型仅实现了部分上述函数:

双端队列

Base.push! — Function

  1. push!(collection, items...) -> collection

Insert one or more items in collection. If collection is an ordered container, the items are inserted at the end (in the given order).

Examples

  1. julia> push!([1, 2, 3], 4, 5, 6)
  2. 6-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6

If collection is ordered, use append! to add all the elements of another collection to it. The result of the preceding example is equivalent to append!([1, 2, 3], [4, 5, 6]). For AbstractSet objects, union! can be used instead.

See sizehint! for notes about the performance model.

See also pushfirst!.

source

Base.pop! — Function

  1. pop!(collection) -> item

Remove an item in collection and return it. If collection is an ordered container, the last item is returned; for unordered containers, an arbitrary element is returned.

See also: popfirst!, popat!, delete!, deleteat!, splice!, and push!.

Examples

  1. julia> A=[1, 2, 3]
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. julia> pop!(A)
  7. 3
  8. julia> A
  9. 2-element Vector{Int64}:
  10. 1
  11. 2
  12. julia> S = Set([1, 2])
  13. Set{Int64} with 2 elements:
  14. 2
  15. 1
  16. julia> pop!(S)
  17. 2
  18. julia> S
  19. Set{Int64} with 1 element:
  20. 1
  21. julia> pop!(Dict(1=>2))
  22. 1 => 2

source

  1. pop!(collection, key[, default])

Delete and return the mapping for key if it exists in collection, otherwise return default, or throw an error if default is not specified.

Examples

  1. julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
  2. julia> pop!(d, "a")
  3. 1
  4. julia> pop!(d, "d")
  5. ERROR: KeyError: key "d" not found
  6. Stacktrace:
  7. [...]
  8. julia> pop!(d, "e", 4)
  9. 4

source

Base.popat! — Function

  1. popat!(a::Vector, i::Integer, [default])

Remove the item at the given i and return it. Subsequent items are shifted to fill the resulting gap. When i is not a valid index for a, return default, or throw an error if default is not specified.

See also: pop!, popfirst!, deleteat!, splice!.

Julia 1.5

This function is available as of Julia 1.5.

Examples

  1. julia> a = [4, 3, 2, 1]; popat!(a, 2)
  2. 3
  3. julia> a
  4. 3-element Vector{Int64}:
  5. 4
  6. 2
  7. 1
  8. julia> popat!(a, 4, missing)
  9. missing
  10. julia> popat!(a, 4)
  11. ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [4]
  12. [...]

source

Base.pushfirst! — Function

  1. pushfirst!(collection, items...) -> collection

Insert one or more items at the beginning of collection.

This function is called unshift in many other programming languages.

Examples

  1. julia> pushfirst!([1, 2, 3, 4], 5, 6)
  2. 6-element Vector{Int64}:
  3. 5
  4. 6
  5. 1
  6. 2
  7. 3
  8. 4

source

Base.popfirst! — Function

  1. popfirst!(collection) -> item

Remove the first item from collection.

This function is called shift in many other programming languages.

See also: pop!, popat!, delete!.

Examples

  1. julia> A = [1, 2, 3, 4, 5, 6]
  2. 6-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. julia> popfirst!(A)
  10. 1
  11. julia> A
  12. 5-element Vector{Int64}:
  13. 2
  14. 3
  15. 4
  16. 5
  17. 6

source

Base.insert! — Function

  1. insert!(a::Vector, index::Integer, item)

Insert an item into a at the given index. index is the index of item in the resulting a.

See also: push!, replace, popat!, splice!.

Examples

  1. julia> insert!([6, 5, 4, 2, 1], 4, 3)
  2. 6-element Vector{Int64}:
  3. 6
  4. 5
  5. 4
  6. 3
  7. 2
  8. 1

source

Base.deleteat! — Function

  1. deleteat!(a::Vector, i::Integer)

Remove the item at the given i and return the modified a. Subsequent items are shifted to fill the resulting gap.

See also: delete!, popat!, splice!.

Examples

  1. julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
  2. 5-element Vector{Int64}:
  3. 6
  4. 4
  5. 3
  6. 2
  7. 1

source

  1. deleteat!(a::Vector, inds)

Remove the items at the indices given by inds, and return the modified a. Subsequent items are shifted to fill the resulting gap.

inds can be either an iterator or a collection of sorted and unique integer indices, or a boolean vector of the same length as a with true indicating entries to delete.

Examples

  1. julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)
  2. 3-element Vector{Int64}:
  3. 5
  4. 3
  5. 1
  6. julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])
  7. 3-element Vector{Int64}:
  8. 5
  9. 3
  10. 1
  11. julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
  12. ERROR: ArgumentError: indices must be unique and sorted
  13. Stacktrace:
  14. [...]

source

Base.keepat! — Function

  1. keepat!(a::Vector, inds)

Remove the items at all the indices which are not given by inds, and return the modified a. Items which are kept are shifted to fill the resulting gaps.

inds must be an iterator of sorted and unique integer indices. See also deleteat!.

Julia 1.7

This function is available as of Julia 1.7.

Examples

  1. julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
  2. 3-element Vector{Int64}:
  3. 6
  4. 4
  5. 2

source

  1. keepat!(a::Vector, m::AbstractVector{Bool})

The in-place version of logical indexing a = a[m]. That is, keepat!(a, m) on vectors of equal length a and m will remove all elements from a for which m at the corresponding index is false.

Examples

  1. julia> a = [:a, :b, :c];
  2. julia> keepat!(a, [true, false, true])
  3. 2-element Vector{Symbol}:
  4. :a
  5. :c
  6. julia> a
  7. 2-element Vector{Symbol}:
  8. :a
  9. :c

source

Base.splice! — Function

  1. splice!(a::Vector, index::Integer, [replacement]) -> item

Remove the item at the given index, and return the removed item. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.

See also: replace, delete!, deleteat!, pop!, popat!.

Examples

  1. julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
  2. 2
  3. julia> A
  4. 5-element Vector{Int64}:
  5. 6
  6. 5
  7. 4
  8. 3
  9. 1
  10. julia> splice!(A, 5, -1)
  11. 1
  12. julia> A
  13. 5-element Vector{Int64}:
  14. 6
  15. 5
  16. 4
  17. 3
  18. -1
  19. julia> splice!(A, 1, [-1, -2, -3])
  20. 6
  21. julia> A
  22. 7-element Vector{Int64}:
  23. -1
  24. -2
  25. -3
  26. 5
  27. 4
  28. 3
  29. -1

To insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).

source

  1. splice!(a::Vector, indices, [replacement]) -> items

Remove items at specified indices, and return a collection containing the removed items. Subsequent items are shifted left to fill the resulting gaps. If specified, replacement values from an ordered collection will be spliced in place of the removed items; in this case, indices must be a UnitRange.

To insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).

Julia 1.5

Prior to Julia 1.5, indices must always be a UnitRange.

Examples

  1. julia> A = [-1, -2, -3, 5, 4, 3, -1]; splice!(A, 4:3, 2)
  2. Int64[]
  3. julia> A
  4. 8-element Vector{Int64}:
  5. -1
  6. -2
  7. -3
  8. 2
  9. 5
  10. 4
  11. 3
  12. -1

source

Base.resize! — Function

  1. resize!(a::Vector, n::Integer) -> Vector

Resize a to contain n elements. If n is smaller than the current collection length, the first n elements will be retained. If n is larger, the new elements are not guaranteed to be initialized.

Examples

  1. julia> resize!([6, 5, 4, 3, 2, 1], 3)
  2. 3-element Vector{Int64}:
  3. 6
  4. 5
  5. 4
  6. julia> a = resize!([6, 5, 4, 3, 2, 1], 8);
  7. julia> length(a)
  8. 8
  9. julia> a[1:6]
  10. 6-element Vector{Int64}:
  11. 6
  12. 5
  13. 4
  14. 3
  15. 2
  16. 1

source

Base.append! — Function

  1. append!(collection, collections...) -> collection.

For an ordered container collection, add the elements of each collections to the end of it.

Julia 1.6

Specifying multiple collections to be appended requires at least Julia 1.6.

Examples

  1. julia> append!([1], [2, 3])
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. julia> append!([1, 2, 3], [4, 5], [6])
  7. 6-element Vector{Int64}:
  8. 1
  9. 2
  10. 3
  11. 4
  12. 5
  13. 6

Use push! to add individual items to collection which are not already themselves in another collection. The result of the preceding example is equivalent to push!([1, 2, 3], 4, 5, 6).

See sizehint! for notes about the performance model.

See also vcat for vectors, union! for sets, and prepend! and pushfirst! for the opposite order.

source

Base.prepend! — Function

  1. prepend!(a::Vector, collections...) -> collection

Insert the elements of each collections to the beginning of a.

When collections specifies multiple collections, order is maintained: elements of collections[1] will appear leftmost in a, and so on.

Julia 1.6

Specifying multiple collections to be prepended requires at least Julia 1.6.

Examples

  1. julia> prepend!([3], [1, 2])
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. julia> prepend!([6], [1, 2], [3, 4, 5])
  7. 6-element Vector{Int64}:
  8. 1
  9. 2
  10. 3
  11. 4
  12. 5
  13. 6

source

以下类型均完全实现了上述函数:

  • Vector (a.k.a. 1-dimensional Array)
  • BitVector (a.k.a. 1-dimensional BitArray)

集合相关的实用工具

Core.Pair — Type

  1. Pair(x, y)
  2. x => y

Construct a Pair object with type Pair{typeof(x), typeof(y)}. The elements are stored in the fields first and second. They can also be accessed via iteration (but a Pair is treated as a single “scalar” for broadcasting operations).

See also Dict.

Examples

  1. julia> p = "foo" => 7
  2. "foo" => 7
  3. julia> typeof(p)
  4. Pair{String, Int64}
  5. julia> p.first
  6. "foo"
  7. julia> for x in p
  8. println(x)
  9. end
  10. foo
  11. 7

source

Base.Pairs — Type

  1. Iterators.Pairs(values, keys) <: AbstractDict{eltype(keys), eltype(values)}

Transforms an indexable container into a Dictionary-view of the same data. Modifying the key-space of the underlying data may invalidate this object.

source