Ways of defining a function

question

#1

Most julia functions are defined like this:

function f(x)
    # some code
end

However a few packages use the following style

f(x) = begin
    # some code
end

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


#2
f(x) = ...

is just shorthand for

function f(x)
    ...
end

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


#3

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?

#4

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.


#5

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.


#6

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


#7

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.


#8

<unsolicitedopinion>

Can we please not promote this style

f(x) = begin
    # multiline code
end

</unsolicitedopinion>


#9

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