Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Nested looping in racket/scheme

Has anyone got any idea what the idiomatic method for nested looping on numbers within a range is in Racket/Scheme? In Python we have:

for i in range(numb1):
    for j in range(numb2):

What would be the equivalent in Racket/Scheme?

like image 245
cobie Avatar asked Dec 15 '22 10:12

cobie


1 Answers

In Racket it's as simple as this, using Iterations and Comprehensions:

(for* ([i (in-range numb1)]
       [j (in-range numb2)])
  <body of iteration>)

The above will only work in Racket. By comparison, the following snippets will work in any standard RxRS interpreter - for instance, using a pair of nested do:

(do ((i 0 (+ i 1))) ((= i numb1))
  (do ((j 0 (+ j 1))) ((= j numb2))
    <body of iteration>))

Yet another option: using explicit recursion and named let:

(let loop1 ((i 0))
  (cond ((< i numb1)
         (let loop2 ((j 0))
           (cond ((< j numb2)
                  <body of iteration>
                  (loop2 (+ j 1)))))
         (loop1 (+ i 1)))))

Finally, you can always do something like the following, refer to SICP under the section "Nested Mappings" for details:

(define (range start stop)
  (let loop ((i (- stop 1))
             (acc '()))
    (if (< i start)
        acc
        (loop (- i 1) (cons i acc)))))

(for-each
 (lambda (i)
   (for-each
    (lambda (j)
      <body of iteration>)
    (range 0 numb2)))
 (range 0 numb1))
like image 62
Óscar López Avatar answered Feb 11 '23 05:02

Óscar López