Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Add @get! #1764

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,24 @@ const _jl_secret_table_token = :__c782dbf1cf4d6a2e5e3865d7e95634f2e09b5902__
has(t::Associative, key) = !is(get(t, key, _jl_secret_table_token),
_jl_secret_table_token)

# @get! works like get, but evaluates the default value only if the key is not
# present; it then assigns the default value to the key and returns the
# (converted) value
macro get!(d, k, default)
quote
d::Associative, k = $(esc(d)), $(esc(k))
p, index = _assoc_keyindex(d, k)
V = valtype(d)
( p ? _get_at(d, index) : (d[k] = convert(V,$(esc(default)))) )::V
end
end

# Used by @get!.
# If you provide _assoc_keyindex for a type,
# you must provide a matching _get_at.
_assoc_keyindex(d::Associative, k) = (has(d, k), k)
_get_at(d::Associative, index) = d[index]

function show{K,V}(io, t::Associative{K,V})
if isempty(t)
print(io, typeof(t),"()")
Expand Down Expand Up @@ -423,6 +441,9 @@ function get{K,V}(h::Dict{K,V}, key, deflt)
return (index<0) ? deflt : h.vals[index]::V
end

_assoc_keyindex(d::Dict, k) = (i=ht_keyindex(d,k);(i<0) ? (false,0) : (true,i))
_get_at(d::Dict, index) = d.vals[index]

has(h::Dict, key) = (ht_keyindex(h, key) >= 0)

function key{K,V}(h::Dict{K,V}, key, deflt)
Expand Down
1 change: 1 addition & 0 deletions base/export.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,7 @@ export
unsetenv,

# Macros
@get!,
@v_str,
@unexpected,
@assert,
Expand Down
11 changes: 11 additions & 0 deletions test/corelib.jl
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,17 @@ d4[1001] = randstring(3)
@test !isequal({1 => 2}, {"dog" => "bone"})
@test isequal(Dict{Int, Int}(), Dict{String, String}())

#@get!
let
d = {8=>19}
def = {}
f = x->(push(def,x); x)
@test @get!(d, 8, f(5)) == 19
@test @get!(d, 19, f(2)) == 2
@test d == {8=>19, 19=>2}
@test def == [2]
end

# ############# end of dict tests #############

# #################### set ####################
Expand Down