Question

c++

int loop(int x, int y, int z) {
     int result = 0;
     for ( int i = x; i < y; i+=z ) { result += i; }
     return result; }

Just i try that by scheme

(letrec ((my-loop (lambda (a b c)
  (begin
    (let ((i a) (s 0))
    (if (< i b)
          (set! s (+ s i)) s))))))(my-loop (+ a c) b c))

please write correct code of scheme....

Was it helpful?

Solution

Here's a straightforward translation to a do loop:

(define (foo x y z)
  (do ((result 0 (+ result i))
       (i x (+ i z)))
      ((>= i y) result)))

However, many Schemers find do loops to be distasteful. So here's an identical loop that uses named let, which is in fact what the do is likely to expand to:

(define (foo x y z)
  (let loop ((result 0)
             (i x))
    (if (>= i y)
        result
        (loop (+ result i) (+ i z)))))

which is likely to expand to:

(define (foo x y z)
  ((rec (loop result i)
     (if (>= i y)
         result
         (loop (+ result i) (+ i z))))
   0 x))

which then expands to:

(define (foo x y z)
  ((letrec ((loop (lambda (result i)
                    (if (>= i y)
                        result
                        (loop (+ result i) (+ i z))))))
     loop)
   0 x))

Yay macros! Choose the version you like best; most Schemers I know prefer the second one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top