Processing math: 100%
Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Mathematics LibreTexts

4.4: Variable Number of arguments

( \newcommand{\kernel}{\mathrm{null}\,}\)

From the last exercise, it would be unfortunate if we have to write different functions for different number of arguments. We can write a variable number of arguments with a ... trailing the last argument. The following is a generalized version of the mean: 

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

function theMean(x::Number...) 
  local sum=0
  for val in x
    sum += val 
  end
  sum/length(x)
end
function theMean(x::Number...) 
  local sum=0
  for val in x
    sum += val 
  end
  sum/length(x)
end
 

which uses a for loop that we will discuss later. This function will now find the mean using any number of arguments.

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

theMean(1,2,3,4)
theMean(1,2,3,4)
 

Also, note that the argument x with the ... is a tuple, (see section 3.9). An alternative way to access the individual elements of x would be to use brackets. For example, x[3] would be the third argument.

Exercise

Try the following (replace the code in the above code block) and notice the resulting type:

  • theMean(11//2,5//6,1//9)
  • theMean(1.0,2.0,3.0,4.0,5.0)

 You should see that each of these return a floating point number. This is because division / with any other number returns a floating point. 

Multiple Return Values

A very nice feature of Julia functions is that of multiple return values. Instead of only being able to return a single number (or requiring to send an array or structural type), you can return more than 1 number (or other data type). For example.

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

h(x,y) = x+y,x-y
h(x,y) = x+y,x-y
 

and we call this in the same manner.  For example,

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

h(3,5)
h(3,5)
 

We can store the results of any function that returns multiple arguments in the following example:

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

p,q = h(3,5)
p,q = h(3,5)
 

the p will take on the value 8 and q will take on the value of -2.

The result of this function is a tuple as we saw in section XXXX. Although in that section we used parentheses around the tuple, it is not necessary and generally isn’t used to return a tuple in a function. We will use this for the result of the quadratic formula in Chapter XXXX.


4.4: Variable Number of arguments is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

Support Center

How can we help?