Function at the beginning of a script or at the end?

x = rand(5)
x .=f.(x)

function f(x)
    return 2 * x 
end

This is a test script. In vs code, I got an error

/ERROR: AUndefVarError: `f` not definedn
Stacktrace:a
c o[1]n dtop-level scopea
/   @S cUntitled-3:5ri
julia> :/Anaconda/Scripts/activate

julia> DERROR: syntax: extra token "Anaconda" after end of expression
Stacktrace:
 [1] top-level scope
   @ none:1

julia> conda activate base
ERROR: syntax: extra token "activate" after end of expression
Stacktrace:
 [1] top-level scope
   @ none:1

A function must be defined at the beginning of a script?

1 Like

Not exactly, the definition needs to be evaluated to let the method exist before a call executes. Expressions in a source file are evaluated in order. MATLAB’s rule to put all function definitions at the end of a file doesn’t carry over to most languages. Note that calls nested in a function definition don’t execute immediately, so feel free to define their functions later, as long as the execution happens after it all:

function g()
  x = rand(5)
  x .=f.(x) # f doesn't execute at g's definition
  return x
end

function f(x)
    return 2 * x 
end

x = g() # now g, rand, f executes

I should probably elaborate that expression does not mean line; the Julia parser finds the beginning of an expression and reads text until that expression ends, then Julia evaluates the full expression. So, a syntax block will evaluate as one, not line by line. Still, executing the assignments and function calls within will occur in order. Keyword declarations like global and local go into effect when the expression is evaluated, prior to any execution. It’s good practice to write them at the beginning of their scopes to reflect this, but this is good to know in case you run into code that doesn’t, and to know that ordering them between assignments won’t actually switch a variable’s scope there at execution.

6 Likes

Have a look at: Working with Julia projects | Julia programming notes

I suggest to use first only the REPL and not VSCode. Or, use VSCode only as code editor to edit your scripts, but start Julia from a terminal (Terminal-> new Terminal in VSCode). This reduces the complexity.

1 Like