Lecture: 10-25-2012

posted Oct 25, 2012, 12:39 PM by Samuel Konstantinovich   [ updated Nov 20, 2012, 5:43 AM ]
;TODAY: Listception... lists within lists.. within lists

;Goal: To process lists that have sublists... that have sublists... etc.

;New function:
; (list? x)  is a built in function that is 
;true when x is a list, false otherwise.

;How do you know a list has a list inside it?
;
;When the car of the list is a list... in other words when (list? (car X)) is true.

;We will write a function that checks a list and returns 
;true if it has a list inside of it called   

;(hasSublists? L)
(define (hasSublists? L)
  (cond
    ( (null? L) #f)
    ( (list? (car L)) #t) 
    ( else (hasSublists? (cdr L)))))

;How you can test it:
(hasSublists? '( 2 3 4))
(hasSublists? '( 2 (3) 4))
(hasSublists? '( ))

;Now lets write a function that adds up all the integers in a list
;of integers that may have sublists.
(define (sumlist L)
  (cond
    ( (null? L) 0)
    ( (list? (car L)) (+(sumlist(car L))(sumlist (cdr L)))) 
    ( else (+ (car L) (sumlist (cdr L))))))

;How you can test it:
(sumlist '(1 1 (1 1 (1 1) 1)))
(sumlist '(3 1 (2 2) 2))
Comments