Define function with begin or with let?

Consider these two functions

f(x) = begin
    x^2
end

g(x) = let
    x^2
end

using InteractiveUtils

@code_warntype f(1)
@code_warntype g(1)

The compiler seems to generate the same code for both functions. So my question is: is there any difference between these two?

1 Like

My question is why you would define your function this way instead of:

function f(x)
    x^2
end

You are basically using the single-line syntax to define a multi-line function using a block to avoid the function scope being ended by the first newline found. If your intent is saving some keystrokes you could as well use parenthesis instead of begin ... end or let ... end.

f(x) = (
    x^2
)

Probably there is no difference between the two forms, unless you actually use the let feature of allocating new bindings (by defining them in the same line as the let keyword).

3 Likes

Also, the compiler doesn’t care a little bit about syntax, the only thing matter is the scope. As long as the two version has identical scope behavior, which they do in this case and a slight generalization of this, they’ll be have the same.

5 Likes