2014-10-30 Lab

posted Oct 29, 2014, 7:55 PM by Samuel Konstantinovich   [ updated Oct 29, 2014, 7:55 PM ]
As per yesterday, you have to work on the "Practice Problems"

1. 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 '( 1  (2 ) ( ) -3 ) ) is  6
(addAllPos '(-3 (-4 -5) 3)) is 15

2. Write a function (sumAtoB a b) that takes two integers a and b such that a < b. The function adds all integers from a to b inclusive. 
(Do not use the math formula for this, because that will not help you practice recursion)
(sumAtoB 1 3) -> 6
(sumAtoB 1 4) -> 10
(sumAtoB 2 4) -> 9
(sumAtoB 10 12) -> 33
(sumAtoB -2 0) -> -3

2b. Make it better and allow for a<b  and a > b. You can modify the existing function, you don't need a 2nd copy.

3. Write a function (hasSublists? L) that returns true when any of the top level elements of L are lists. 

(hasSublists? '( 2 3 4))  -> #f
(hasSublists? '( 2 (3) 4)) -> #t
(hasSublists? '( )) -> #f
(hasSublists? '( () )) -> #t


4. 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

;5 Trace practice
;Assume L cannot be an empty list or contain any empty lists
(define (what L)
  (cond
    ;First two cases process sublist
    ((and (list? (car L)) (null?(cdr L)))   (what (car L)))
    ((list? (car L))   (max (what (car L)) (what (cdr L))))
    ;second two cases process non-sublists
    ((null?(cdr L))   (car L)) 
    (else      (max (car L) (what (cdr L))))))
;Trace through the following by showing the steps on paper:  (verify on a computer)
(what '( (12 9)(14  2) 13 ) )

Comments