Recursion in scheme

2019-08-02 20:10发布

问题:

My goal is to find from this list

(A B C D E G)

a new list

(B D G)

But my code is not working.

(define  (fun lst)
    (cond
     ((null? lst) '())
      ((null? (cdr lst) '())
       (else  (cons ( cadr lst) ( fun lst))))

I'm getting (B C D E G). Where have I gone wrong?

回答1:

Your function isn't doing anything and you really haven't specified what you want to test. If you really only want to get B D G from that specific list then all you need to do is make those each tests, (equal? (car lst) 'B) and so on for each character.

If instead the function is suppose to just print every other character in a list then you need to construct a way to do that. For example your base case for recursion that you have now is correct, and empty list should return an empty list. Otherwise if it is not empty return the the cdr of the list and then work with that.

If you still can't figure out an answer just start writting it down on paper and see what different tests will do. You need to come up with a way to find every other character.