when should a function in Julia have a return statement using the return keyword and when should it just return by having the variable I want to return at the end of the function?
I was reading the Julia docs and it seems like there's quite a bit of literature on the subject found here.
My understanding is that the convention is to always use return
if you are trying to break out of the function and to otherwise just have the variable you want to return at the end of the function.
Is my understanding correct or am I missing something here?
'return' keyword in Julia is used to return the last computed value to the caller function. This keyword will cause the enclosing function to exit once the value is returned. return keyword will make the function to exit immediately and the expressions after the return statement will not be executed.
A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.
In Julia, one returns a tuple of values to simulate returning multiple values. [...] Yes, it works! I tried to get the values of m and s using this code: x = [1,2,3] and (av, sd) = stat(x), but I wonder what if x was an m by n matrix, how can someone get the results for each column n that is populated by m entries?
The Blue Style guide recommends always using return
in long-form functions definitions.
I like the consistency and clarity of that convention.
It is a matter of taste, but I strongly prefer explicit return
statements in multi-line functions.
I always do a double take and get confused for a second-and-a-half whenever I see a lone variable or expression dangling on its own on the last line. I find it weird and inelegant.
Explicit return
statements improve readability a lot, imho.
Technically speaking, you do have to use the return
keyword if returning CodeInfo
from a @generated
function. Due to a long standing bug https://github.com/JuliaLang/julia/issues/25678
Which comes up if you are trying to implement Cassette style complier passed or similar (see a blog post I wrote on that)
With that said, this is so incredibly obscure that I really hesitate to make this answer. For all but dozen or so people who will ever try and do that kinda thing, The presence of return or not in the last statement is purely a mater of style.
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