escape-recursion.scm 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. (import (except (rnrs base))
  2. (only (guile)
  3. lambda* λ
  4. display
  5. simple-format))
  6. (define factorial-with-continuation
  7. (lambda* (n
  8. #:optional
  9. ;; Explicitly specifying an argument, which is a
  10. ;; continuation.
  11. ;; By default the continuation cont is merely
  12. ;; returning the value given. Identity
  13. ;; function. Not doing anything with the result.
  14. (cont (λ (x) x))
  15. ;; Using `remainder` only as an example.
  16. (test (λ (num) (= (remainder num 7) 0))))
  17. (let iter ([num° (- n 1)]
  18. [product° n])
  19. (cond
  20. ;; Base case of factorial.
  21. [(<= num° 1) product°]
  22. ;; Next a case with some condition, which, if true
  23. ;; means you want to exit.
  24. [(test num°)
  25. (cont product°)]
  26. ;; Otherwise normal iteration.
  27. [else
  28. (iter (- num° 1)
  29. (* product° num°))]))))
  30. (factorial-with-continuation 10)
  31. (factorial-with-continuation 10
  32. ;; A continuation, which merely
  33. ;; display something, but then
  34. ;; returns the value.
  35. (λ (num)
  36. (display (simple-format #f "~a\n" num))
  37. num)
  38. ;; Another weird condition.
  39. (λ (num) (= (remainder num 17) 0)))