Skip to content

Commit a9e3709

Browse files
mcabbottAmit Shirodkar
authored andcommitted
Add get for numbers (JuliaLang#41032)
1 parent 3a401f9 commit a9e3709

File tree

4 files changed

+27
-0
lines changed

4 files changed

+27
-0
lines changed

base/array.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -816,6 +816,8 @@ iterate(A::Array, i=1) = (@_inline_meta; (i % UInt) - 1 < length(A) ? (@inbounds
816816
Retrieve the value(s) stored at the given key or index within a collection. The syntax
817817
`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`.
818818
819+
See also [`get`](@ref), [`keys`](@ref), [`eachindex`](@ref).
820+
819821
# Examples
820822
```jldoctest
821823
julia> A = Dict("a" => 1, "b" => 2)

base/dict.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,9 @@ end
488488
Return the value stored for the given key, or the given default value if no mapping for the
489489
key is present.
490490
491+
!!! compat "Julia 1.7"
492+
For tuples and numbers, this function requires at least Julia 1.7.
493+
491494
# Examples
492495
```jldoctest
493496
julia> d = Dict("a"=>1, "b"=>2);

base/number.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ function getindex(x::Number, I::Integer...)
103103
@boundscheck all(isone, I) || throw(BoundsError())
104104
x
105105
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+
106111
first(x::Number) = x
107112
last(x::Number) = x
108113
copy(x::Number) = x # some code treats numbers as collection-like

test/numbers.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2307,6 +2307,23 @@ end
23072307
@test_throws BoundsError getindex(x, 1, 0)
23082308
end
23092309
end
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
23102327
@testset "copysign and flipsign" begin
23112328
# copysign(x::Real, y::Real) = ifelse(signbit(x)!=signbit(y), -x, x)
23122329
# flipsign(x::Real, y::Real) = ifelse(signbit(y), -x, x)

0 commit comments

Comments
 (0)