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

Python-like else clause on for loops in Julia? #13026

Closed
kilminster opened this issue Sep 9, 2015 · 3 comments
Closed

Python-like else clause on for loops in Julia? #13026

kilminster opened this issue Sep 9, 2015 · 3 comments

Comments

@kilminster
Copy link

Python's for-else construct as described for example in section 4.4, here, is sometimes very useful. (The idea is that the else clause will be executed after the loop completes normally, but not if we break out of the loop.) Could something similar be added to Julia?

As an example, code like:

converged=true
for i=1:n
    if !isapprox(y[i],ynew[i])
        converged=false
        break
    end
end
if converged
    return y
end

could become:

for i=1:n
    if !isapprox(y[i],ynew[i])
        break
    end
else
    return y
end
@jiahao
Copy link
Member

jiahao commented Sep 9, 2015

Please try searching the existing issues before you open a new one.

Duplicate of #1289

@jiahao jiahao closed this as completed Sep 9, 2015
@kilminster
Copy link
Author

I'm sorry, I did try searching, obviously not well enough.

@jiahao
Copy link
Member

jiahao commented Sep 9, 2015

No worries, it can be hard to search for things on Github.

For your use case, you can write something like

for i=1:n
    if y[i]  ynew[i]
        @goto converged
    end
    y, ynew = ynew, computenewy(y, ynew)
end
error("Not converged")
@label converged
return y

which was what emerged from the discussion in that referenced issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants