Hello Everyone,
I am quite new to Nim and solve puzzles of Advent of Code 2021 using Nim. 🙂 I enjoy the flexibility, compactness and elegance of the language. Tanks for Nim. 🙏
I ran into a unexpected behavior. The for loop
for i in 1..3: echo i
would iterate over the 3 numbers and print them. However, the loop
for i in 3..1: echo i
does nothing. For me this was completely unexpected (and wasted much of valuable time in the competition 😉 )
Can anyone explain what is concept behind this asymmetry?
What is the right way to iterate from a .. b if it is unknown, whether a<=b or a>b ?
Thanks.
iterator count[T: SomeInteger](x, y: T): T =
if x < y:
for n in countup(x, y): yield n
else:
for n in countdown(x, y): yield n
This is what I used. This retains the direction.
Can anyone explain what is the concept behind this asymmetry?
in practice, you know the direction of iteration in 99.9% of cases and terminating behaviour (1..sequence.high) is useful far more often.
What is the right way to iterate from a .. b if it is unknown, whether a<=b or a>b ?
if
The alternative "design" makes no sense, that's why:
let a = stdin.readLine.parseInt
let b = stdin.readLine.parseInt
for i in a..b:
echo "so the iteration order depends on the input? Terrible..."
No other programming language that I know of does this either, but my memory of other programming languages is fading quickly as I only use Nim. :P
Can anyone explain what is the concept behind this asymmetry?
What does for n in range(3, 1): print(n) print in Python?
(Spoiler: Also nothing, just like Nim)
Hi Folks, Thanks for your answers. I already enjoy this community. 🙂
Some years ago I taught youngsters programming and realized that newbies have marvelous ideas on how programming could be. Okay, I know, this is not the case. 😀
@Zoom Thanks for your handy iterator.
@SolitudeSF @Araq @miran Thanks for the explanation on the design. You are right, countdown does not work, even on the Commodore 64. 🙂 I checked: (see pic)
https://drive.google.com/file/d/1clRLLd4CzA-5x6keqBLECxyD2wnUhEWH/view?usp=sharing
@freeflow You are right. I am catched by Nim’s is intuitiveness and flexibility and explore freely with minimal reading of the manual. I know it is unprofessional but works most of the cases, which is the merit of the language indeed. 🙂