Lecture: 10-24-2012 (solutions)

posted Oct 24, 2012, 12:56 PM by Samuel Konstantinovich   [ updated Nov 20, 2012, 5:42 AM ]
;GOAL: Go over miscelaneous list functions
;How do we delete/insert values to a list?


;WHY DO MY FUNCTIONS HAVE periods in them?

;base case causes a dotted pair error
(define (makeWrong x)
  (cond
    ((= x 0) 0)
    (else (cons x (makeWrong (- x 1))))))

;better base case:
(define (makeSumthin x)
  (cond
    ((= x 0) '(0))
    (else (cons x (makeSumthin (- x 1))))))


;-------------------
;SOLUTIONS FROM CLASS:

;StripZero L
(define (stripZero L)
  (cond
    ( (null? L) L)
    ( (= 0 (car L))   (stripZero (cdr L)))
    ( else   (cons (car L) (stripZero (cdr L)))))) 
;   ( else  (append (list (car L)) (stripZero (cdr L)))))) 
;   ( else  (append (cons (car L) '() ) (stripZero (cdr L)))))) 


;-------------------
;Delete L n
(define (delete L n)
  (cond
   ((null? L) L)
   ((= n 0)  (cdr L))
   (else (cons (car L) (delete (cdr L) (- n 1))))))

;-------------------
;Insert L v n

(define (insert L v n)
  (cond
   ((null? L) (list v))
   ;((null? L)  (cons v L)) ;alternate way is same as when n=0...
   ((= n 0)  (cons v L))
   (else (cons (car L) (insert (cdr L) v (- n 1))))))

;ALTERNATE SOLUTION
;to simplify things we can combine the base cases:
(define (insert L v n)
  (cond
   ((or(null? L)(= n 0))  (cons v L))
   (else (cons (car L) (insert (cdr L) v (- n 1))))))

Comments