branch.scm

;;branch.scm
;;Exercise 17.14 from "Simply Scheme"
;;Second Edition
;;by Brian Harvey and Matthew Wright
;;copyright 1999
;;Exercise:
;;Write a procedure branch that takes as arguments
;;a list of numbers
;;and a nested list structure.  It should be the list-of-lists
;;equivalent of item, like this:
;;>(branch '(3) '((a b) (c d) (e f) (g h)))
;;>(E F)
;;>(branch '(3 2) '((a b) (c d) (e f) (g h)))
;;>F
;;>(branch '(2 3 1 2) '((a b)((c d)(e f)((g h)(i j)) k) (l m)))
;;>H
(define (branch nums-list nest-list)
  (cond
    ((null? nums-list) '())
    ((null? nest-list) '())
    ((null? (cdr nums-list)) (list-ref nest-list (- (car nums-list) 1)))
    (else
     (branch (cdr nums-list) (list-ref nest-list (- (car nums-list) 1))))))
;;tests of branch:
(branch '(3) '((a b) (c d) (e f) (g h)))
;;>(E F)
(branch '(3 2) '((a b) (c d) (e f) (g h)))
;;>F
(branch '(2 3 1 2) '((a b)((c d)(e f)((g h)(i j)) k) (l m)))
;;>H
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: