Julia: Passing keyword arguments to function throu

2019-04-09 12:40发布

问题:

I am trying to use map() to apply the function quandl on an array of (n x 1) strings. (http://quandljl.readthedocs.io/en/latest/get_data.html)

However, I wish to pass on more than just the strings as arguments to the function, such as from = Date1 and to = Date2. I cannot seem to find a way to have map() apply the function on the array of strings while also passing the keyword arguments to download data from Date1 to Date2.

The more general question is: how can I use map() to apply a function on several elements while also passing additional arguments to this function?

回答1:

You'll want to create an anonymous function that calls quandl with the appropriate arguments and map that over your data. Since I'm a little unclear on how you want to call quandl, I'll just use a made up example. Suppose f takes two positional arguments and a keyword k; suppose you want to apply it to each value of v with 2 as the second argument and k = "abc". You would do this like so:

map(x -> f(x, 2, k = "abc"), v)

If the anonymous function body is large or complicated, you may want to use Julia's do-block syntax and write the computation like this instead:

map(v) do x
    f(x, 2, k = "abc")
end

In this example, this doesn't make much sense, but if the anonymous function is multiple lines of code, then this can be preferable.