How to return anything with minuses in the scheme

I have a little problem with the assigned programming task on the Scheme. We were instructed to create a function that returns only values ​​in a pair that satisfy the requirements of this predicate. They should also be returned in the same pair structure, simply with deleting records. So far my code is as follows

(define (keep-if-all ia pred ls)
 (cond
  ((null? ls) null)
  ((pair? ls)
   (cons
    (keep-if-all pred (car ls))
    (keep-if-all pred (cdr ls))))
  ((pred ls) ls)
  (else null)))

The problem is that else returns null and thus replaces the value with null rather than deleting it.

for instance

(keep-if-all odd? (list 1 2 3 (cons 4 4) (list 1 2 3 4 5)))

returns

(1 () 3 (()) (1 () 3 () 5))

not desired

(1 3 () (1 3 5))

It would be very helpful to evaluate the tracks in the right direction.

+3
source share
1 answer

Just add more if,

(define (keep-if-all pred ls)
 (cond
  ((null? ls) '())
  ((pair? ls)
     (let ((x (keep-if-all pred (car ls))))
       (if (or (not (null? x))                ; if something left of (car ls)
               .... )                         ;     or if it was a pair,
        (cons x (keep-if-all pred (cdr ls)))  ;   then, include x in the output
        .... )))                              ;   else, don't include x in the output
  ((pred ls) ls)
  (else '())))

Now it works as expected:

(keep-if-all odd? (list 1 2 3 (cons 4 4) (list 1 2 3 4 5)))
;Value 15: (1 3 () (1 3 5))
+1
source

All Articles