views:

51

answers:

2

I am trying to write a scheme function that takes a list of the form:

((#f ((1 1) (2 1)))
 (#f ((1 3) (5 1)))
 (#f ((1 4) (7 1)))
)

and removes all the #f to give a list like:

( ((1 1) (2 1))
  ((1 3) (5 1))
  ((1 4) (7 1))
)

I have tried the following code but cannot get it to work:

(define meth
  (lambda lst
    (if (equal? (cdr lst) '())
      (cdr (car lst))
      (cons (list-ref (car lst) 1) (meth (cdr lst))))))

Does anyone know how to do this? Thanks.

+1  A: 

You can just use map to apply the cdr function to each sublist in the list, like this: (map cdr lst). However this will give you

( (((1 1) (2 1)))
  (((1 3) (5 1)))
  (((1 4) (7 1)))
)

for your sample input, which is one level of nesting more than your sample output. So to get your sample output, use list-ref to get the second element of each sublist:

(define (meth lst) (map (lambda (x) (list-ref x 1)) lst))

Edit: As Eli Barzilay helpfully pointed out, there is the cadr function to get the second element of a list, so this can be shortened to:

(define (meth lst) (map cadr lst))
sepp2k
Note that `cadr` returns the second element. (Also, this is a fine answer -- but the "modification" in the question text is bogus.)
Eli Barzilay
+1  A: 

Here is a way to do it more closely to what you had:

(define meth
  (lambda (lst)
    (cond
      ((null? lst) '())
      ((cons (cadr (car lst)) (meth (cdr lst))))
      )
    )
  )


(define a '(
            (#f ((1 1) (2 1)))
            (#f ((1 3) (5 1)))
            (#f ((1 4) (7 1)))
            ))
mangoDrunk