Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named arguments without natural defaults in Julia

The question is about 'best practice' in Julia. I have read this and this. I have a function

function discount_rate(n, fv, pmt, pv; pmt_type = 0)
...
end

The problem right now is I have to call the method like so

discount_rate( 10, 10, 10, -10 )

It's not clear what these arguments mean -- even I forget. What I'd love to do is write

discount_rate( n = 10, fv = 10, pmt = 10, pv = -10 )

That's clearer: easier to read and understand. But I can't define my method by making these arguments keywords arguments or optional arguments because they don't have natural defaults. From the point of view of design, is there a recommended way around this?

like image 559
vathymut Avatar asked Oct 19 '14 06:10

vathymut


People also ask

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

What are optional function arguments and default values?

A Python optional argument is an argument with a default value. You can specify a default value for an argument using the assignment operator. There is no need to specify a value for an optional argument when you call a function. This is because the default value will be used if one is not specified.

What is multiple dispatch Julia?

Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.

What is the type of a function in Julia?

Method Tables Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table.


1 Answers

Could do the following:

function discount_rate(;n=nothing,fv=nothing,pmt=nothing,pv=nothing,pmt_type=0)
    if n == nothing || fv == nothing || pmt == nothing || pv == nothing
        error("Must provide all arguments")
    end
    discount_rate(n,fv,pmt,pv,pmt_type=pmt_type)
end

function discount_rate(n, fv, pmt, pv; pmt_type = 0)
    #...
end
like image 166
IainDunning Avatar answered Oct 26 '22 16:10

IainDunning