Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a function include an explicit return statement in Julia?

Tags:

julia

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?

like image 822
logankilpatrick Avatar asked Dec 20 '19 23:12

logankilpatrick


People also ask

How do you return a function in Julia?

'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.

How do functions work in Julia?

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.

Can Julia return multiple values?

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?


3 Answers

The Blue Style guide recommends always using return in long-form functions definitions.

I like the consistency and clarity of that convention.

like image 97
David Varela Avatar answered Nov 16 '22 04:11

David Varela


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.

like image 35
DNF Avatar answered Nov 16 '22 03:11

DNF


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.

like image 32
Lyndon White Avatar answered Nov 16 '22 04:11

Lyndon White