functions 5: Returning Values
Lets say you have a mathematical function \(f(x) = 2x + 3\), you expect \(f(5)\) to return \(13\). In fact functions in programming like in mathematics are designed to return something. Julia functions returns the output of the last statement by default. Let’s see an example, type the example below and execute it:
function add(a, b) a + b end sum = add(5, 3) println(sum)
In the above example,
println(sum) prints 8, but how? Because
sum is assigned to this
add(5, 3), that means
add(5, 3) seems to have done something and returned it out. Now let’s look at the definition of
function add(a, b) a + b end
So it just consists of one statement
a + b and that’s the last statement in the function, so the computed value of
a + b must have been returned out which would have been stored in
sum and that’s what gets printed.
This is in fact amazing thing. As we have seen few blogs before, going to a hotel and ordering a dish abstracts many things. You are served a dish, but behind it a cook works on it, before that a farmer would have produced something, before that a factory would have produced seeds fertilizers, animal feed, machinery etc, all of these are been abstracted away by a simple order where you say I want such and such a dish. Functions gives you that mighty power.
You could also specify the keyword
return in a function to return any thing. In the example below:
function add_with_return(a, b) return a + b end sum = add_with_return(5, 3) println(sum)
we explicitly specify
return a + b so that the
a + b gets returned. Now it does not mean its only at the last statement you must return something. Look at the code below:
function add_with_wrong_return(a, b) return 0 return a + b end sum = add_with_wrong_return(5, 3) println(sum)
in it we have returned 0 using
return 0 before
return a + b, so no matter what ever you do, say
add(1, 2) or what ever, it will return
0. Once a function has returned something the execution of the function will stop, the code after return wont be executed, so in the above case
return a + b is a unreachable code. In some IDE’s and tooling environments,it would warn of possible unreachable code thus making you to code better.
The Jupyter notebook for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/functions.ipynb.