nim-lang / RFCs

A repository for your Nim proposals.
136 stars 23 forks source link

`let`, `var`, and `const` for for-loop variables #358

Closed n0bra1n3r closed 3 years ago

n0bra1n3r commented 3 years ago

Today, we use the mitems iterator to allow mutating a sequence while looping over it. To present another weird idea of mine, what if we could do this:

for var element in collection:
  element += 1

We could extend this to const:

for const constant in (1, 2, 3).fields:
  echo $constant

Using let would result in a normal for-loop:

for let element in collection:
  # element += 1 # error
  discard

There would be the issue of how mpairs would interact with this, unsure how this could be solved:

for var (i, element) in collection:
  i += 1 # what?!
konsumlamm commented 3 years ago

Today, we use the mitems iterator to allow mutating a sequence while looping over it. To present another weird idea of mine, what if we could do this:

What advantages does this have over mitems? You'd still need to write multiple iterators (the mutability requirements of the arguments might be different).

We could extend this to const:

for const constant in (1, 2, 3).fields:
  echo $constant

If the iteration should be at compile time (which I assume is what you mean here), why not just use static:?

Using let would result in a normal for-loop:

for let element in collection:
  # element += 1 # error
  discard

This would be a breaking change, so highly unlikely to be implemented (unless you want to keep the old syntax, but in that case, why should anyone switch to the new syntax?).

There would be the issue of how mpairs would interact with this, unsure how this could be solved:

for var (i, element) in collection:
  i += 1 # what?!

Fwiw, the mpairs/pairs iterators where the first element is the index (for arrays, seqs, ...) are supposed to be eventually replaced by enumerate anyway. But this would indeed be confusing, since the i should not be mutable.

n0bra1n3r commented 3 years ago

You make (very) good points @konsumlamm. In fact, I am now convinced this is a bad idea 🤣. This idea was strictly a cosmetic one, and I understand cosmetic changes are extremely low priority -- especially in Nim where you can do so much with metaprogramming -- unless there is good reason. And this idea probably doesn't have a good reason to be implemented 😂.