S6. Final list practice problems + Solutions

posted Nov 8, 2012, 6:16 AM by Samuel Konstantinovich   [ updated Nov 15, 2012, 5:13 AM ]
1. Write a function (duplicate L) that makes a second copy of every item of the list. (assume no sublists)
Example: 
(duplicate '(1 3 9 2 4)) -> (1 1 3 3 9 9 2 2 4 4)

2. Write a function (addAllPos L) that calculates the sum of all the values of a list of integers L, but add the positive value of a  number if it is negative. This should work if L has sublists.
Examples: 
(addAllPos '(-1 1)) is 2   
(addAllPos '(-3 (-4 -5) 3)) is 15

3. Write a function (countEmpty L) that counts the number of empty lists are contained in a list L which may have sublists.
(countEmpty '( 3 2  ( ) ( ) ) is 2
(countEmpty '( 2 (9 ( ) ( ) ) ( ) ) ) is 3
(countEmpty '() ) is 0


4. Write a function (clear L x) that deletes all of the elements of a list L that are smaller than x. This should work if L has sublists.
;Example:
;(clear '(3 9 2 4 (1 9 4)) 5)  is (9 (9))
;(clear ;(1 2 (5 6) (1 2) 6) 4) is (( 5 6)()6)

SOLUTIONS:

(define (duplicate L)
  (if (null? L)   ;you can use if or cond
      L 
      (cons (car L)(cons (car L) (duplicate (cdr L))))))

(define (addAllPos L)
  (cond
    ((null? L) 0)
    ((list? (car L)) (+ (addAllPos (car L))(addAllPos (cdr L))))
    (else (+ (abs (car L))(addAllPos(cdr L))))))

(define (countEmpty L)
  (cond
    ((null? L) 0)
    ((null? (car L))(+ 1 (countEmpty (cdr L))))
    ((list? (car L))(+ (countEmpty (car L))(countEmpty (cdr L))))
    (else (countEmpty (cdr L)))))

;EDIT:  changed > to  >= 
(define (clear L x)
  (cond 
    ((null? L) L)
    ((list? (car L)) (cons (clear (car L) x)(clear (cdr L) x)))
    ((>=(car L) x) (cons (car L) (clear (cdr L) x)))
    (else (clear (cdr L) x))))


Comments