The same name for a function and a variable

julia> function dis(x, y)
       return dis =  sqrt(x^2 + y^2)
       end
dis (generic function with 1 method)

julia> a = dis(1, 2)
2.23606797749979

julia> dis = dis(1,2)
ERROR: invalid redefinition of constant dis
Stacktrace:
 [1] top-level scope
   @ REPL[5]:1

It seems that it is ok to have a variable of the same name with a function inside the function, but not outside the function.

This is somehow inconvenient, as I want a function for generating some variable, and for the sake of my memory, I want to name the function and the variable the same, so that I can call the function like

distance = distance(x, y)

Remember what I said earlier today? Assignments in local scopes do not reassign global variables by default. A function is a “hard scope”, so that rule doesn’t change in the REPL either. So, dis = sqrt... made a new local variable; 2 scopes, 2 different variables. However, dis = dis(...) in the global scope does attempt to reassign a global variable; 1 scope cannot have 2 different variables with the same name. Global functions are protected by implicit const declarations, meaning that variable cannot be reassigned. If dis wasn’t const, you lose access to the function, for example:

let
  function f(x) # f is local variable, cannot be const
    f = x
  end
  f(1) # call reassigns f
  f(1) # fails because f is not assigned to a function anymore
end

In any language, It’s bad practice to use the same name for 2 different variables in nested scopes. Use different names for different meanings; dis should not refer to a function and a possible output.

2 Likes

A thousand times, this. You will save yourself so many headaches later on if you follow this advice.

One suggestion if you’re the one writing the function is to add a verb to your function names to make it clear that they’re functions. And you can always add articles to variables to make it clear. Eg getdistance() for a function and a_distance or thedistance for variables.

3 Likes