Invalid iteration specification, what does it mean?

I would like to write a function in a .jl file, that can recursively produce polynomials for me. However I got the following error message: invalid iteration specification.

> function P(n)
    Pn(x)=1  ##if n==0 Pn(x)=1
    global  i=0 ##declare i for the for loop
    if n!=0
        Pn_1(x)=1
        Pn(x)=x
        seged(x)=x      ##declare the function for the for loop
        for global i in 1:n-1
            seged(x)=(((2*i+1)*x*Pn(x)-(i)*Pn_1(x))/(i+1)) ##the formula for the recursive function
            Pn_1(x)= P(x)
            Pn(x)=seged(x)
        end
    end
    return Pn(x)
end

Also I have come from Octave and this code run without errors back there.

Afaik this is not valid syntax in Julia. Just remove the global (why would you need it?)

2 Likes

The error is thrown when the text fails to parse to a valid Julia expression.

julia> :(for global i in iter end)
ERROR: syntax: invalid iteration specification
Stacktrace:
 [1] top-level scope
   @ none:1

It’s also redundant, you already had the global i declaration earlier. A for loop (or let block) header introduces a new local variable into their scope by default, so if you want to reassign a global variable, you could 1) rename the iteration variable e.g. for i2 in 1:n-1 and assign i = i2 in the body, or 2) specify for outer i in 1:n-1 to borrow i from the outer scope.

Mostly unrelated to the error, but expect more syntax and design differences in totally unrelated languages, this isn’t like Octave cloning MATLAB.

The closest syntax we have to this is the outer keyword. Julia is not a MATLAB or Octave emulator, so you should not expect syntax that works there to just work in Julia.

julia> i = 0
0

julia> function f()
           global i = 0
           for outer i in 1:10
           end
           return i
       end
f (generic function with 1 method)

julia> f()
10

julia> i
10

Our analysis of your code is that you probably do not need the make i global or use outer. If that is the case, then making it global will result in unnecessarily slow code.

1 Like