fork(1) download
  1. ; higher-order string functions
  2.  
  3. (define (string-map proc str)
  4. (let* ((len (string-length str))
  5. (out (make-string len)))
  6. (do ((i 0 (+ i 1)))
  7. ((= i len) out)
  8. (string-set! out i
  9. (proc (string-ref str i))))))
  10.  
  11. (define (shift c n)
  12. (cond ((char-upper-case? c)
  13. (integer->char (+ (modulo (+ (char->integer c) -65 n) 26) 65)))
  14. ((char-lower-case? c)
  15. (integer->char (+ (modulo (+ (char->integer c) -97 n) 26) 97)))
  16. (else c)))
  17.  
  18. (define (caesar n str)
  19. (string-map (lambda (c) (shift c n)) str))
  20.  
  21. (display (caesar 3 "PROGRAMMING praxis")) (newline)
  22. (display (caesar -3 "SURJUDPPLQJ sudalv")) (newline)
  23.  
  24. (define (string-for-each proc str)
  25. (do ((i 0 (+ i 1)))
  26. ((= i (string-length str)))
  27. (proc (string-ref str i))))
  28.  
  29. (string-for-each
  30. (lambda (c) (display (char->integer c)) (newline))
  31. "PRAXIS")
  32.  
  33. (define (string-fold proc base str)
  34. (let loop ((base base) (i 0))
  35. (if (= i (string-length str)) base
  36. (loop (proc (string-ref str i) base) (+ i 1)))))
  37.  
  38. (define (string-fold-right proc base str)
  39. (let loop ((base base) (i (- (string-length str) 1)))
  40. (if (negative? i) base
  41. (loop (proc (string-ref str i) base) (- i 1)))))
  42.  
  43. (display (string-fold cons '() "PRAXIS")) (newline)
  44.  
  45. (display (string-fold (lambda (c count)
  46. (if (char-lower-case? c)
  47. (+ count 1)
  48. count))
  49. 0 "Programming Praxis"))
  50. (newline)
  51.  
  52. (string-fold (lambda (c junk)
  53. (display (char->integer c)) (newline))
  54. 0 "PRAXIS")
  55.  
  56. (display (list->string ; double characters
  57. (string-fold-right (lambda (c base)
  58. (cons c (cons c base)))
  59. '() "PRAXIS")))
  60. (newline)
Success #stdin #stdout 0.04s 8744KB
stdin
Standard input is empty
stdout
SURJUDPPLQJ sudalv
PROGRAMMING praxis
80
82
65
88
73
83
(S I X A R P)
15
80
82
65
88
73
83
PPRRAAXXIISS