Thanks, that's a good point regarding the scope and not a "side effect" I 
would want.

If I understand the keyword part correctly, I would have to explicitly 
state all the variables in the function definition to be able to use them 
locally which, as you write, can become verbose (very verbose for many of 
my functions, actually). In addition, the Dict that I call the function 
with is longer "preserved" (correct?) as a variable. I want to supply that 
Dict to many other functions at various levels below the function I first 
call. So that will not work. I guess explicitly using the Dict is the best 
way forward. That's the way I do with structs in Matlab, but with a 
somewhat more compact notation, so I can live with that.

Regards, m

On Monday, February 16, 2015 at 12:01:24 PM UTC+1, Michael Hatherly wrote:
>
> One thing to note about using @eval as mentioned in Sean’s reply is that 
> eval (and by extension @eval) does not evaluate expressions in a 
> function’s scope, but rather in the global scope of the module.
> This might have unexpected results:
>
> julia> function f(d)
>            for (k, v) in d
>                @eval $k = $v
>            end
>        end
> f (generic function with 1 method)
>
> julia> x
> ERROR: UndefVarError: x not defined
>
> julia> f(Dict(:x => 1))
>
> julia> x
> 1
>
> You could instead use a function with keyword arguments and pass it a 
> dictionary:
>
> julia> g(; x = error("provide x"), args...) = nothing
> g (generic function with 1 method)
>
> where args... discards any variables you don’t want to handle. x could 
> also be given a default value rather than throwing an error when not 
> provided.
> You’d then call it like so:
>
> julia> g(; Dict(:x => 1, :y => 2)...)
>
> Although it’s slightly more verbose, this way won’t result in side-effects 
> caused by using eval.
>
> — Mike
> On Monday, 16 February 2015 00:17:54 UTC+2, Martin Johansson wrote:
>>
>> Is there a way to "assign" the values of a Dict to the corresponding keys 
>> such that I get "variables" (symbols?) with names given by the keys? Let's 
>> assume the keys are for example strings which would work as variables.
>>
>> The reason for why I would want to do this is to have functions where 
>> explicit variables are used rather than Dicts, primarily for readability. 
>> I'm suspecting that this is not a recommended way of doing things (since I 
>> couldn't find any info along these lines when searching), and if this is 
>> the case please set me straight.
>>
>> Regards, m
>>
>>
>>

Reply via email to