Idiomatic nested loop in racket / circuit

Has anyone understood which idiomatic nested loop method for numbers within a range is in Racket / Scheme? In Python, we have:

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

What will be the equivalent in Racket / Scheme?

+4
source share
1 answer

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

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

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

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

Another option: using explicit recursion and the name 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: SICP in the Nested Mappings section 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)) 
+11
source

Source: https://habr.com/ru/post/1481556/


All Articles