for-loop.scm 988 B

12345678910111213141516171819202122232425262728293031323334353637
  1. ;; The idea for this macro is taken from:
  2. ;; https://spritely.institute/static/papers/scheme-primer.html#fn.19
  3. ;; We want to achieve a syntax like the following:
  4. ;; (for ((i 0) (< i 10) (+ i 2))
  5. ;; (display (string-append "i is: " (number->string i) "\n")))
  6. ;; OK, GO!
  7. (import
  8. (except (rnrs base) let-values)
  9. (only (guile)
  10. lambda* λ))
  11. (define-syntax for
  12. (syntax-rules ()
  13. [(_ ((counter-var counter-init) condition counter-update)
  14. expr* ...)
  15. (let loop ([counter-var counter-init])
  16. (cond
  17. ;; Stop iterating, if the condition is no longer
  18. ;; true.
  19. [(not condition)
  20. ;; Nothing left to do, return the counter value.
  21. counter-var]
  22. ;; Do an interation. Run all body expressions and
  23. ;; then do a recursive call updating the counter.
  24. [else
  25. expr* ...
  26. (loop counter-update)]))]))
  27. (for ((i 0) (< i 10) (+ i 2))
  28. (display (string-append "i is: " (number->string i) "\n")))