I am looking on how to translate this pseudocode to idiomatic scheme:
for c in range(1, 1000):
for b in range(1, c):
for a in range(1, b):
do something if condition is true
Your pseudocode is translated into Scheme straightforwardly enough as a sequence of nested named let
s, as
(let loopc ((c 1)) ; start the top loop with c = 1,
(if (> c 1000) ; if `c > 1000`,
#f ; exit the top loop ; or else,
(let loopb ((b 1)) ; start the first-nested loop with b = 1,
(if (> b c) ; if `b > c`,
(loopc (+ c 1)) ; end the first-nested loop, and
; continue the top loop with c := c+1 ; or else,
(let loopa ((a 1)) ; start the second-nested loop with a = 1,
(if (> a b) ; if `a > b`,
(loopb (+ b 1)) ; end the second-nested loop, and
; continue the first-nested loop with b := b+1
(begin ; or else,
(if condition ; if condition holds,
(do_some a b c) ; do something with a, b, c,
#f) ; and then,
(loopa (+ a 1)) ; continue the second-nested loop with a := a+1
)))))))
Of course it's a bit involved and error prone. On the other hand it is easy to shortcut the innermost loop (on a
s) and restart the top one (on c
s) directly, by calling loopc
from within loopa
(always in tail position, NB !), should the need arise.
For example, the above code is directly applicable to the problem which you state in the comments, of finding a Pythagorean triplet which sums to 1000. Moreover, when you've hit upon the solution, you can directly call (loopc 1001)
to immediately exit the whole threefold nested loops construction.
As a side note,
for c in range(3, 1000):
for b in range(2, c):
for a in range(1, b):
if a**2 + b**2 == c**2 and a + b + c == 1000:
print(a * b * c)
is not the most efficient solution. That would be, at least, first,
for c in range(3, 1000):
for b in range(2, 1000-c-1):
for a in range(1, 1000-c-b):
if a**2 + b**2 == c**2 and a + b + c == 1000:
print(a * b * c)
and furthermore,
for c in range(3, 1000):
c2 = c**2
for b in range(2, 1000-c-1):
a = 1000-c-b
if a**2 + b**2 == c2:
print(a * b * c)
# exit the loops