How does c++ for loop change to scheme

醉酒当歌 提交于 2019-12-13 04:40:53

问题


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....


回答1:


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.



来源:https://stackoverflow.com/questions/22867962/how-does-c-for-loop-change-to-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!