; Problem 17.2
;
(define (f1 l1 l2)
  (list (append (cdr l1) (list (car l2)))))
(define (f2 l1 l2)
  (list (cdr l1) (cadr l2)))
(define (f3 l1 l2)
  (append l1 l1))
(define (f4 l1 l2)
  (list (list (car l1) (car l2))
        (append (cdr l1) (cdr l2))))

; Problem 17.4
;
(define (mystery lst)
  (mystery-helper lst '()))

(define (mystery-helper lst other)
  (if (null? lst)
      other
      (mystery-helper (cdr lst) (cons (car lst) other))))

; Mystery builds the reverse of the original list into
; other and then returns it after all of the elements
; of the list have been traversed.

; Problem 17.8
; 
(define (member e l)    ; is an element, l is a list
  (cond ((null? l) #f)  ; nothing is in an empty list
        ((equal? e (car l)) l)  ; car matched, return list
        (else (member e (cdr l)))))

; Problem 17.9
;
; Note that if the index is invalid (i.e., not between 0 and
; the length of the list minus one), this will produce an error.
; That's fine; real list-ref does as well.
(define (list-ref l i)  ; l is a list, i is an index
  (cond ((= i 0) (car l))
        (else (list-ref (cdr l) (- i 1)))))

; Problem 17.10
;
(define (length l)
  (cond ((null? l) 0)
        (else (+ 1 (length (cdr l))))))


; Problem 17.12
;
(define (flatten l)
  (cond ((null? l) l)
        ((list? (car l)) (append (flatten (car l))
                                 (flatten (cdr l))))
        (else (cons (car l) (flatten (cdr l))))))

; Problem 17.14
;
; Note that list-ref starts indexing at 0, not 1.  But the problem
; calls for the branch indexes to work like item, which starts at 1.
; The examples are consistent with indexing that starts at 1.
; So we subtract one to make list-ref work properly.
(define (branch index-list content-list)
  (cond ((null? index-list) content-list)
        (else (branch (cdr index-list)
                      (list-ref content-list (- (car index-list) 1))))))