functionjulialet

Difference between `function` and `let` blocks in Julia?


In Julia, is there any difference at all between these to two three ways of creating a function:

function g1(x)
   # compute something, store it in `result`
   return result # (return keyword is optional)
end
g2(x) = let
   # compute something, store it in `result`
   return result # (return keyword is optional)
end
g3(x) = begin
   # compute something, store it in `result`
   return result # (return keyword is optional)
end

The answer below is: these three definitions are exactly equivalent.

EDIT: clarify the question, and emphasis on the answer.


Solution

  • Note that the let variant also creates a function. Therefore you could also write:

    g2(x) = begin
       # compute something, store it in `result`
       result
    end
    

    to get the same effect.

    The reason is that all after = here is within g2 function scope, so no matter if you do begin-end or let-end the expression is in this scope. The let variant creates an extra hard scope, but it does not change anything as there is nothing in the function scope that is not in let scope in your example.

    let-end would make a difference from begin-end if it were in a global scope, but in your case you introduce it within function scope.