octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Default value for arguments


From: CdeMills
Subject: Default value for arguments
Date: Wed, 15 Oct 2014 11:49:12 -0700 (PDT)

Hello,

While investigating with some function interface, I had an idea about using
default values for arguments.

In Octave, such values may be defined as 
function y = myfunc(var1, var2 = 2, var3='Hello')

This construct is Octave-specific. As I have to share my scripts with
students, sometimes they have MatLab and prefer to stay with it.I came with
the following construct:

function y = myfunc(var1, var2, var3)
if (nargin < 2) var2 = []; endif
if (isempty (var2)) var2 = 2; endif
if (nargin < 3) var3 = []; endif
if (isempty (var3)) var3 = 'Hello'; endif

This way:
1) the same default values are used as in function y = myfunc(var1, var2 =
2, var3='Hello')
2) if only part of the arguments must be initialised, an easy way is to call
it like:
result = myfunc(3, [], 'Bye')
The arguments for wihch default value has to be used are simply passed an
empty value. No need to care about the default, it will be used anyway.

This is less elegant and require more tests, but the default value is only
copied at one point in the code. Moreover, this approch does not break
compatibility with Matlab.

Comments about this framework ? Could it be adopted more widely ?

Regards

Pascal





--
View this message in context: 
http://octave.1599824.n4.nabble.com/Default-value-for-arguments-tp4666984.html
Sent from the Octave - Maintainers mailing list archive at Nabble.com.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]