Question: Why `for n in 10 @show n end` is valid rather than getting error

  • When I study Julia with respect to for loop syntax as an exercise, some wired things happen.
    Consider this julia code:
for i in 1:10
    @show i
end

Of course it will output with i=1, i=2, …, i=10 as a result. More precisely

julia> for i in 1:10
          @show i
       end
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

But, how about removing 1: from for i in 1:10? Due to my trivial typo, things often happens. Namely for n in 10 @show n end. I would expect it will get error like Python

Python 3.7.4 (default, Oct 13 2019, 23:07:44)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> for i in 10:
...     print(i)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

On the other hand, our language Julia outputs 10

               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.3.1 (2019-12-30)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> versioninfo()
Julia Version 1.3.1
Commit 2d5741174c (2019-12-30 21:36 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.6.0)
  CPU: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, skylake)
Environment:
  JULIA_EDITOR = subl

julia> for n in 10 @show n end
n = 10

Similar things happen for n is 1.2

julia> for n in 1.2 @show i end
n = 1.2
  • I would like to know wether this feature is intentionally designed or not. If yes, why ?
    (Maybe I’m asking a stupid question :sob: )

Thank you.

It is intentional, but it is unclear (in my view) if the same choice would be made (making numbers iterable) if Julia was remade from scratch. Having iterable numbers is sometimes nice and sometimes not nice (like in your example)… There has been a lot of discussions about that, see for example make numbers non-iterable? · Issue #7903 · JuliaLang/julia · GitHub.

4 Likes

Thank you for your quick response!
I will check out this issue :+1: