Le lundi 06 juin 2016 à 04:08 -0700, FANG Colin a écrit :
> I find myself often writing code like this when dealing pop! with a
> Dict{A, B}
>
>
> if !haskey(my_dict, key)
> do_something...
> end
>
> value = pop!(my_dict, key)
>
> do_something_else...
>
>
> The code above has an issue: it looks up the key in a dict twice
> unnecessary.
>
> I know I can opt for the alternative pattern:
>
>
> v = pop!(my_dict, key, nothing)
>
> if v == nothing
> do_something...
> end
>
> value::B = v
>
> do_something_else...
>
> Note this piece of code is also a bit annoying, as v is no longer
> type stable. I have to think of another name "value" and apply an
> assignment with type assert. (naming variables is hard)
>
>
> Probably I can extend `pop!` with pop!(f, key, v) so that I can do:
>
> value = pop!(my_dict, key) do
> do_something...
> end
>
> do_something_else...
>
> But using an anonymous function here seems an overkill with overhead?
>
> What do people do in such case?
I would say the do block syntax sounds like a good solution, and it
parallels the existing one for get() and get!().
Another solution would be to add a function which would always return a
Nullable. This has been discussed at
https://github.com/JuliaLang/julia/issues/13055
Regards