# Using macros

Hello, how can i write a macro that takes four argument , namely a Dict , a key ( of arbitaray type) , and two expressions such that if the Dict contains the key , its value is bound to the local variable it within the first experssion which is evaluated; if
the key cannot be found, the second expression is evaluated.

If I understand your question correctly, you just need a function like this:

``````f(d, key, a, b) = (key ∈ d) ? a : b
``````
3 Likes

Not sure I understand the question correctly either, but I’d rather think that this is the desired behavior:

``````function foo(dict, key, found, default)
haskey(dict, key) ? found(dict[key]) : default()
end
``````
``````julia> d = Dict(:x => 42)
Dict{Symbol,Int64} with 1 entry:
:x => 42

# If the value exists, double it; otherwise return 0
julia> foo(d, :x, val->2val, ()->0)
84

julia> foo(d, :y, val->2val, ()->0)
0
``````

If I’m correct and you’re indeed referring to anaphoric macros, I don’t think they are considered very idiomatic in Julia. In cases like these, I think the idiomatic solution would be to use anonymous functions like in the proposal above.

In an ideal world, the arguments to `foo` would be to ordered in such a way that it could be called with a `do` block. But this is only practical when there is only one argument that is a function (in which case this argument must be placed first). See for example the following method of `get`:
`get(f::Function, collection, key)`

1 Like

yea am referring to anaphoric macros

Anaphoric macros