Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

for loop surprises #1717

Closed
vtjnash opened this issue Dec 10, 2012 · 2 comments
Closed

for loop surprises #1717

vtjnash opened this issue Dec 10, 2012 · 2 comments
Assignees
Labels
kind:bug Indicates an unexpected problem or unintended behavior

Comments

@vtjnash
Copy link
Sponsor Member

vtjnash commented Dec 10, 2012

In porting code from MATLAB, this one caught me by surprise. Would it be possible (worthwhile) to generate a warning if an inner anonymous function shadows a local array (variable)? The scope of the length(x) call also surprised me, although I can't think of an example where this would matter in real code.

In MATLAB:

x = zeros(10,1)
for i = 1:length(x)
    x(i) = 1;
end

In Julia:

julia> x=zeros(10,1)

julia> for i = 1:length(x)
                  x(i) = 1
              end
in anonymous: x not defined
 in anonymous at no file

julia> for i = 1:10
                  x(i) = 1
              end

julia> x==zeros(10,1)
true

julia> for i = 1:10
                  x[i] = 1
              end

julia> x==ones(10,1)
true
@JeffBezanson
Copy link
Sponsor Member

That's unexpected. I don't believe I intended function definitions to behave differently in this way.

@ghost ghost assigned JeffBezanson Dec 10, 2012
@toivoh
Copy link
Contributor

toivoh commented Dec 10, 2012

@JeffBezanson: I take it that the unexpected part is that the function definition creates a new binding x instead of refusing to add a method to the old binding?

I've gradually been feeling more and more that method definitions should probably not be done with =, since it's too easy to confuse them with assignment. (In the case above, and others.) I think that

f(x) := x^2

would make a nice alternate syntax.

Of course, that would be a breaking change of epic proportions. The old syntax could be kept alongside for a pretty long time to ease the transition. I do think that it would allow julia to be more consistent, and possibly open up for more powerful syntax by making the distinction between assignment and method definition cleaner. As a toy example, consider

(x::MyType)[i::Int] := ...

to define a ref method for MyType. (That doesn't generalize to assign, though... )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind:bug Indicates an unexpected problem or unintended behavior
Projects
None yet
Development

No branches or pull requests

3 participants