Concepts of Programming Languages

Scheme Loops

Instructor: Stefan Mitsch

Looping

  • Loop forever printing hello (press Control-C to quit)
    
    while (1) printf("hello\n");
                  
    
    (let loop ()
      (display "hello\n")
      (loop))
                  
  • With an incrementing counter argument n
    
    (let loop ([n 0])
      (display (string-append "hello " (number->string n) "\n"))
      (loop (+ n 1)))
                  
  • The name loop is not significant
  • Define global function and then invoke it
    
    (define (printHello m) 
      (display (string-append "hello " (number->string m) "\n"))
      (printHello (+ m 1)))
    (printHello 0)
                  

Variables

  • Define global variable at top level; set! to assign
    
    (define n 0)
    
    (let loop ()
      (display (string-append "hello " (number->string n) "\n"))
      (set! n (+ n 1))
      (loop))
                  
  • Define local variable scoped to let form; also set!
    
    (let ([m 0])
      (let loop ()
        (display (string-append "hello " (number->string m) "\n"))
        (set! m (+ m 1))
        (loop)))
                  

Translating While Loops

  • factorial function in C with while loop
    
    int factorial (int n) {
      int result = 1;
      while (n > 1) {
        result = result * n;
        n = n - 1;
      }
      return result;
    }
                  
  • Scheme version
    
    (define (factorial n) 
      (let ([result 1]) 
        (let loop ()
          (if (> n 1) 
              (begin
                (set! result (* result n)) 
                (set! n (- n 1))
                (loop))
              result))))
                  

Translating While Loops

  • factorial function in C with while loop
    
    int factorial (int n) {
      int result = 1;
      while (n > 1) {
        result = result * n;
        n = n - 1;
      }
      return result;
    }
                  
  • More idiomatic Scheme version
    
    (define (factorial n) 
      (let loop ([result 1] [n n])
        (if (> n 1) 
            (loop (* result n) (- n 1))
            result)))