Ways of defining a function

Most julia functions are defined like this:

function f(x)
    # some code

However a few packages use the following style

f(x) = begin
    # some code

Is there a semantic difference between the two or are they exactly the same?

f(x) = ...

is just shorthand for

function f(x)

That said, using the shorthand with a begin ... end block just defeats its purpose. Use it when your code is short (one-liners).


Ok do I get this right:

  • function f(x) ... end
  • f(x) = begin ... end
  • f(x) = let ... end
  • f(x) = ...
    are all lowered to exactly the same thing? Analogous for more complicated signatures like f(x::Int,y::T; kw...) where T?

let has different scoping behavior, but other than that, yes. Note that the answer to your question is in the documentation, so please try to read that.

1 Like

Some authors may be influenced by the Scala style guide, which suggests that pure functions be written with the Scala equivalent of f(x) = ..., and impure functions be written as function f(x) ... end regardless of how many lines ... requires. Since this style is clear and useful, despite not being prevalent, I would personally suggest that it’s up to you whether to use begin ... end.

1 Like

Can you give an example, when
f(x) = begin ... end
f(x) = let ... end

The function definition already introduces hard scope, so in this case they don’t differ. My point was about let in general; I only use it when I want its specific scoping behavior, but in your example it does not make a difference.


Can we please not promote this style

f(x) = begin
    # multiline code



i do like this style. primarily because

1, i don’t like that there are two syntaxes for the same thing

2, i often find myself changing back and force between a one liner and a few liner, or ? vs if, as the code develops. it is a hassle to restructure.

so i usually just use f() = … exclusively

1 Like