berry icon indicating copy to clipboard operation
berry copied to clipboard

Support `..` shorthand for ranges with increment

Open sean-niemann opened this issue 1 year ago • 1 comments

The addition of range increments was a nice touch, although it does not seem to work with the .. shorthand. For simple ranges, we can write

for n : 0..9
  print(n)
end

However, with increments it seems that the range keyword is always needed. It would be nice to allow the .. shorthand for increments as well. eg:

for n : 0..9..3 # range(0, 9, 3)
  print(n)
end

sean-niemann avatar Jan 20 '24 21:01 sean-niemann

I'm not sure that the syntax 0..9..3 is intuitive enough. Using range with a specific increment is rare enough so using an explicit syntax with range() may not be a bad thing.

Actually I tend to avoid ranges at all in loops because it creates a new object. When using lots of loops, you end up adding pressure on the GC.

I often do (to take your example):

var i = 0
while i < 9
  print(n)
  i += 3
end

Not using a range is also good if you want to iterate over a list and potentially remove some elements (you can't do that with a range):

var mylist = [1, 2, "a", nil, true]

# remove any 
var i = 0
while i < size(mylist)
  if mylist[i] == nil
    mylist.remove(i)   # don't increment i
  else
    i += 1
  end
end

# mylist is now: [1, 2, 'a', true]

s-hadinger avatar Jan 21 '24 08:01 s-hadinger

Closing since there was no follow-up

s-hadinger avatar May 14 '24 15:05 s-hadinger