fork(1) download
  1. ;; For loops.
  2.  
  3. (use-modules (srfi srfi-1))
  4.  
  5. (define-syntax for
  6. (syntax-rules (in .. .= by)
  7. ;; Integer range exclusive by step.
  8. ((for index in start .. end by step body ...)
  9. (do ((index start (+ index step))
  10. (n (ceiling-quotient (- end start) step) (- n 1)))
  11. ((<= n 0))
  12. body ...))
  13. ;; Integer range inclusive by step.
  14. ((for index in start .= end by step body ...)
  15. (for index in start .. (+ end (if (negative? step) -1 1)) by step
  16. body ...))
  17. ;; Integer range exclusive default step.
  18. ((for index in start .. end body ...)
  19. (for index in start .. end by 1
  20. body ...))
  21. ;; Integer range inclusive default step.
  22. ((for index in start .= end body ...)
  23. (for index in start .= end by 1
  24. body ...))
  25. ;; Iterate over a list.
  26. ((for item in list body ...)
  27. (for-each (lambda (item)
  28. body ...)
  29. list))))
  30.  
  31. ;; Main.
  32.  
  33. (define (print-range start end step)
  34. (for i in start .. end by step
  35. (format #t "~A " i))
  36. (newline)
  37. (for i in start .= end by step
  38. (format #t "~A " i))
  39. (newline)
  40. (let ((n (ceiling-quotient (- end start) step)))
  41. (for i in (iota (max n 0) start step)
  42. (format #t "~A " i)))
  43. (newline))
  44.  
  45. (print-range 1 5 1)
  46. (print-range 1 11 2)
  47. (print-range -11 -1 2)
  48. (print-range 5 1 -1)
  49. (print-range 11 1 -2)
  50. (print-range -1 -11 -2)
  51.  
  52. ;; Nested default step.
  53.  
  54. (for y in 0 .. 4
  55. (for x in 0 .. 4
  56. (format #t "[~A ~A] " x y))
  57. (newline))
Success #stdin #stdout 0.04s 11600KB
stdin
Standard input is empty
stdout
1 2 3 4 
1 2 3 4 5 
1 2 3 4 
1 3 5 7 9 
1 3 5 7 9 11 
1 3 5 7 9 
-11 -9 -7 -5 -3 
-11 -9 -7 -5 -3 -1 
-11 -9 -7 -5 -3 
5 4 3 2 
5 4 3 2 1 
5 4 3 2 
11 9 7 5 3 
11 9 7 5 3 1 
11 9 7 5 3 
-1 -3 -5 -7 -9 
-1 -3 -5 -7 -9 -11 
-1 -3 -5 -7 -9 
[0 0] [1 0] [2 0] [3 0] 
[0 1] [1 1] [2 1] [3 1] 
[0 2] [1 2] [2 2] [3 2] 
[0 3] [1 3] [2 3] [3 3]