fork(1) download
  1. ;; String chomp that copies behavior from Ruby. (2.00)
  2.  
  3. (define (chomp-suffix s pat)
  4. ;; Remove (pat) from the end of string.
  5. (let ((m (string-length pat))
  6. (n (string-suffix-length s pat)))
  7. (if (= m n)
  8. (string-drop-right s n)
  9. s)))
  10.  
  11. (define (chomp-return-or-newline s)
  12. ;; Remove one of (\r \n \r\n) from the end of string.
  13. (chomp-suffix (chomp-suffix s "\n") "\r"))
  14.  
  15. (define (chomp-all-newlines s)
  16. ;; Remove all of (\n \r\n) from the end of string.
  17. (let ((n (string-suffix-length s "\r\n")))
  18. (if (zero? n)
  19. s
  20. (chomp-all-newlines (string-drop-right s n)))))
  21.  
  22. ;; Chomp.
  23.  
  24. (define* (chomp s #:optional (pat '()))
  25. (cond
  26. ((null? pat)
  27. (chomp-return-or-newline s))
  28. ((string-null? pat)
  29. (chomp-all-newlines s))
  30. (else
  31. (chomp-suffix s pat))))
  32.  
  33. ;; Show.
  34.  
  35. (format #t "~S~%" (chomp "hello")) ;=> "hello"
  36. (format #t "~S~%" (chomp "hello\n")) ;=> "hello"
  37. (format #t "~S~%" (chomp "hello\r\n")) ;=> "hello"
  38. (format #t "~S~%" (chomp "hello\n\r")) ;=> "hello\n"
  39. (format #t "~S~%" (chomp "hello\r")) ;=> "hello"
  40. (format #t "~S~%" (chomp "hello \n there")) ;=> "hello \n there"
  41. (format #t "~S~%" (chomp "hello" "llo")) ;=> "he"
  42. (format #t "~S~%" (chomp "he-lo" "llo")) ;=> "he-lo"
  43. (format #t "~S~%" (chomp "hello\r\n\r\n\n" "")) ;=> "hello"
  44. (format #t "~S~%" (chomp "hello\r\n\r\r\n" "")) ;=> "hello\r\n\r"
Success #stdin #stdout 0.01s 10872KB
stdin
Standard input is empty
stdout
"hello"
"hello"
"hello"
"hello\n"
"hello"
"hello \n there"
"he"
"he-lo"
"hello"
"hello\r\n\r"