04-scramble.scm 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. (import
  2. (except (rnrs base) let-values map)
  3. (only (guile)
  4. lambda* λ)
  5. (prerequisites))
  6. ;;; ========
  7. ;;; SCRAMBLE
  8. ;;; ========
  9. ;; The book defines a mysterious function named ~scramble~ and asks
  10. ;; the reader to figure out, what it does.
  11. (define scramble
  12. (λ (tup)
  13. (scramble-b tup '())))
  14. (define scramble-b
  15. (λ (tup rev-pre)
  16. (cond
  17. [(null? tup) '()]
  18. [else
  19. (cons
  20. (pick (car tup)
  21. ;; Here we artificially make the reversed prefix longer by the
  22. ;; current element, so that pick will pick the correct element.
  23. (cons (car tup) rev-pre))
  24. (scramble-b (cdr tup)
  25. ;; We add the current element to the reversed prefix of the
  26. ;; next iteration.
  27. (cons (car tup) rev-pre)))])))
  28. ;; EXPLANATION: The ~scramble~ function looks at each number in the
  29. ;; tuple. The number at each position (position = index + 1, or
  30. ;; "distance from the start of the list") is substracted from its
  31. ;; position and the resulting value is the index of the value, which
  32. ;; shall be the final result for the number in the resulting tuple.
  33. ;; USAGE: Let us try it:
  34. (display
  35. (simple-format
  36. #f "(scramble '(1 2 3 1 2 3 4 1 8 2 10)) -> ~a\n"
  37. (scramble '(1 2 3 1 2 3 4 1 8 2 10))))