; three string exercises

(define (take n xs)
  (let loop ((n n) (xs xs) (ys '()))
    (if (or (zero? n) (null? xs))
        (reverse ys)
        (loop (- n 1) (cdr xs)
              (cons (car xs) ys)))))

(define (drop n xs)
  (let loop ((n n) (xs xs))
    (if (or (zero? n) (null? xs)) xs
      (loop (- n 1) (cdr xs)))))

(define (len str)
  (let loop ((cs (string->list str)) (len 0))
    (if (null? cs) len (loop (cdr cs) (+ len 1)))))

(display (len "hello")) (newline)
(display (len "")) (newline)

(define (instr c str . args)
  (let ((start (if (pair? args) (car args) 0))
        (len (string-length str)))
    (let loop ((k start))
      (cond ((<= len k) #f)
            ((char=? (string-ref str k) c) k)
            (else (loop (+ k 1)))))))

(display (instr #\e "hello")) (newline)
(display (instr #\e "hello" 2)) (newline)
(display (instr #\e "")) (newline)
(display (instr #\e "" 2)) (newline)

(define (substr str start end)
  (list->string
    (take (- end start)
      (drop start
        (string->list str)))))

(display (substr "hello" 1 3)) (newline)
(display (substr "hello" 1 10)) (newline)
(display (substr "hello" 10 20)) (newline)