Le mardi 08 mars 2016 à 05:39 -0800, 'Tim Loderhose' via julia-users a écrit : > Hello everyone, > I started using Julia recently and am very pleased with the many > options I am given to write code. > Now I want to translate a toolbox I wrote in MATLAB to Julia (It's > about MRI reconstruction). > > There are often lots of options in my function arguments, something > which I handled in a quite ugly way in Matlab, for example: > A function which loads an image takes in a filename and varargin, > where varargin can be certain counters I need to construct a matrix > from binary data. > If no varargin is supplied, the function calls another function which > will load these counters from a seperate header file. > If they are supplied, it expects them to be correct and in the right > order to function. > > Now in Julia I have the option to specify all the variables needed in > the arguments, and give them default values. > The default, however, depends on the file which I am loading - if the > extra arguments are not supplied, I would call the other function > which gives me the defaults. > > Does anyone know an elegant way to handle this in Julia? > I thought of making keyword arguments which I could all set to 0. > Then I can check that at the beginning of the function and load the > defaults if necessary. But that seems ugly to me. > > I put some example code here: > https://gist.github.com/timlod/7bb82e4796dd6404ccfa The code in that gist uses optional positional arguments, not keyword arguments. The difference is that keyword arguments are specified using their names, so that you may e.g. skip the first one but still provide the second one.
Using 0 as a special value is fine. Even though it looks a bit weird, users do not necessarily need to see this technical detail: they can either supply the argument or not, without ever passing zero. Tom's solution is another possibility, which might look cleaner, but which has the drawback that you need to check yourself that all passed keyword arguments are valid and of the correct type. So personally I would only use it when you don't now in advance the list of possible arguments, or when there are too many of them. Regards > If this is too vague, I'll try to concretise it more :) > Thanks, > Tim > >
