fork(1) download
  1. ; three string exercises
  2.  
  3. (define (take n xs)
  4. (let loop ((n n) (xs xs) (ys '()))
  5. (if (or (zero? n) (null? xs))
  6. (reverse ys)
  7. (loop (- n 1) (cdr xs)
  8. (cons (car xs) ys)))))
  9.  
  10. (define (drop n xs)
  11. (let loop ((n n) (xs xs))
  12. (if (or (zero? n) (null? xs)) xs
  13. (loop (- n 1) (cdr xs)))))
  14.  
  15. (define (len str)
  16. (let loop ((cs (string->list str)) (len 0))
  17. (if (null? cs) len (loop (cdr cs) (+ len 1)))))
  18.  
  19. (display (len "hello")) (newline)
  20. (display (len "")) (newline)
  21.  
  22. (define (instr c str . args)
  23. (let ((start (if (pair? args) (car args) 0))
  24. (len (string-length str)))
  25. (let loop ((k start))
  26. (cond ((<= len k) #f)
  27. ((char=? (string-ref str k) c) k)
  28. (else (loop (+ k 1)))))))
  29.  
  30. (display (instr #\e "hello")) (newline)
  31. (display (instr #\e "hello" 2)) (newline)
  32. (display (instr #\e "")) (newline)
  33. (display (instr #\e "" 2)) (newline)
  34.  
  35. (define (substr str start end)
  36. (list->string
  37. (take (- end start)
  38. (drop start
  39. (string->list str)))))
  40.  
  41. (display (substr "hello" 1 3)) (newline)
  42. (display (substr "hello" 1 10)) (newline)
  43. (display (substr "hello" 10 20)) (newline)
Success #stdin #stdout 0.03s 8792KB
stdin
Standard input is empty
stdout
5
0
1
#f
#f
#f
el
ello