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?
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 .
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.
Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With