c-for.scm 927 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. ;; I double dog dare you to say this program name outloud.
  2. ;;
  3. ;; C's version of 4
  4. ;;
  5. ;; for (i = 0; i < 5; i++) {
  6. ;; printf ("Number is %d\n", i);
  7. ;; }
  8. ;;
  9. ;; Let's add a scheme for loop!
  10. ;; (for (i 0) (< i 5) (+ i 2)
  11. ;; (format #t "Number is ~a" i))
  12. ;; (for (i 0) (< i 5) (+ i 1)
  13. ;; (format #t "~a\n" i))
  14. (define-syntax-rule (for (i j-0) (comparison m k-5) (operator n l-1)
  15. body ...)
  16. (begin
  17. (define j-var j-0)
  18. (define k-var k-5)
  19. (define l-var l-1)
  20. (define (generator i)
  21. (define (loop k-var l-var)
  22. (cond ((comparison i k-5)
  23. (set! i (operator i l-1))
  24. body ...
  25. (loop k-5 l-1))
  26. (else '())))
  27. loop)
  28. (define run-for (generator j-var))
  29. (run-for k-5 l-1)))
  30. (for (i 0) (< i 5) (+ i 1)
  31. (display "i is: ")
  32. (format #t "~a\n" i))
  33. ;; Part 2: can you write this macro without using closures?