We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
get
1 parent 3a401f9 commit a9e3709Copy full SHA for a9e3709
base/array.jl
@@ -816,6 +816,8 @@ iterate(A::Array, i=1) = (@_inline_meta; (i % UInt) - 1 < length(A) ? (@inbounds
816
Retrieve the value(s) stored at the given key or index within a collection. The syntax
817
`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`.
818
819
+See also [`get`](@ref), [`keys`](@ref), [`eachindex`](@ref).
820
+
821
# Examples
822
```jldoctest
823
julia> A = Dict("a" => 1, "b" => 2)
base/dict.jl
@@ -488,6 +488,9 @@ end
488
Return the value stored for the given key, or the given default value if no mapping for the
489
key is present.
490
491
+!!! compat "Julia 1.7"
492
+ For tuples and numbers, this function requires at least Julia 1.7.
493
494
495
496
julia> d = Dict("a"=>1, "b"=>2);
base/number.jl
@@ -103,6 +103,11 @@ function getindex(x::Number, I::Integer...)
103
@boundscheck all(isone, I) || throw(BoundsError())
104
x
105
end
106
+get(x::Number, i::Integer, default) = isone(i) ? x : default
107
+get(x::Number, ind::Tuple, default) = all(isone, ind) ? x : default
108
+get(f::Callable, x::Number, i::Integer) = isone(i) ? x : f()
109
+get(f::Callable, x::Number, ind::Tuple) = all(isone, ind) ? x : f()
110
111
first(x::Number) = x
112
last(x::Number) = x
113
copy(x::Number) = x # some code treats numbers as collection-like
test/numbers.jl
@@ -2307,6 +2307,23 @@ end
2307
@test_throws BoundsError getindex(x, 1, 0)
2308
2309
2310
+@testset "get(x::Number, ...)" begin
2311
+ for x in [1.23, 7, ℯ, 4//5] #[FP, Int, Irrational, Rat]
2312
+ @test get(x, 1, 99) == x
2313
+ @test get(x, (), 99) == x
2314
+ @test get(x, (1,), 99) == x
2315
+ @test get(x, 2, 99) == 99
2316
+ @test get(x, 0, pi) == pi
2317
+ @test get(x, (1,2), pi) == pi
2318
+ c = Ref(0)
2319
+ @test get(() -> c[]+=1, x, 1) == x
2320
+ @test get(() -> c[]+=1, x, ()) == x
2321
+ @test get(() -> c[]+=1, x, (1,1,1)) == x
2322
+ @test get(() -> c[]+=1, x, 2) == 1
2323
+ @test get(() -> c[]+=1, x, -1) == 2
2324
+ @test get(() -> c[]+=1, x, (3,2,1)) == 3
2325
+ end
2326
+end
2327
@testset "copysign and flipsign" begin
2328
# copysign(x::Real, y::Real) = ifelse(signbit(x)!=signbit(y), -x, x)
2329
# flipsign(x::Real, y::Real) = ifelse(signbit(y), -x, x)
0 commit comments