convex icon indicating copy to clipboard operation
convex copied to clipboard

`for`-like looping

Open helins opened this issue 3 years ago • 3 comments

Akin to for loops found in many C-like languages, the following is experimentally supported:

(for-loop [i 0 (< i 10) (inc i)]
  (do-something i))

I get the intent, it's commonly need. However I would probably favor regular loop and recur.

Comparison:

(loop [i 0]
  (when (< i 10)
    (do
     (do-something i)
     (recur (inc i)))))

a) Boilerplate saved by for-loop is actually very small b) Seems more appropriate for side-effects, so scope is very limited for a language that is mostly functional

I would say that having a special construct given (a) and (b) is not worth it. It is better to promote loop which, at the expense of barely more boilerplate, is a lot more flexible (truly generic).

Clojure's ranges are a very good idea but we can't have that since Convex is not lazy. However, could we envision something in-between current for-loop and ranges?

helins avatar Sep 19 '21 09:09 helins

I personally find for-loop pretty useful. It's definitely easier for people to use than loop / recur where it is quite easy to make "off by one" errors.

Open to other suggestions but currently minded to keep it.

mikera avatar Sep 20 '21 07:09 mikera

I see there is also dotimes. Where does for-loop fit between for and dotimes?

jeroenvandijk avatar Jun 10 '22 06:06 jeroenvandijk

dotimes is basically a simple for-loop where the index goes from 0 to n-1.

That's a pretty common pattern in general, though we don't seem to need it so much in smart contract code - perhaps because it isn't common to need to execute code n times for side effects. map is probably more useful, where you need to work with every element of some source collection.

for-loop is roughly equivalent to the C or Java for statement, where you have a an index with an initial value, a termination condition and some form of increment. It can be useful for various forms of iteration and sometimes more convenient that doing things explicitly with loop / recur.

Note that for-loop isn't constrained to use of a numerical index: you could iterate through elements of a linked list style data structure for example.

mikera avatar Aug 23 '22 12:08 mikera