clarity-lang / reference

The Clarity Reference
146 stars 34 forks source link

Repeating items #52

Open njordhov opened 2 years ago

njordhov commented 2 years ago

A repeat function can generate a list of identical items repeated a given number of times.

Lists of explicitly repeated items are used in many Clarity contracts, typically with map and fold. For illustration, here is a function to increment integers in a list with an integer incremental `n':

(define-read-only (inc-many (items (list 20 int)) (n int)) 
  (map + items (list n n n n n n n n n n n n n n n n n n n n)))

Using repeat simplifies this to:

(define-read-only (inc-many (items (list 20 int)) (n int)) 
  (map + items (repeat 20 n)))

The cost of using repeat should be the same or less than having explicitly repeated items in the contract.

bgok commented 2 years ago

As an alternative, the map function could accept non-iterable parameters and pass them to each iteration.

(define-read-only (inc-many (items (list 20 uint))) 
  (map + items u1)
)

In this example, each time + is called, u1 is passed as the second parameter.

This change should also be applied to fold and filter.