开发者

Printing elements of a list with odd indices in Scheme

so theres this code called ret-odds

 ex: (define (ret-odds lst)
      (if (null? lst) null
         (if (null? (cdr lst)) null
          (cons (car lst) (ret-odds (cdr (cdr lst)))))))

i know the problem is with the last line in that it skips over the second element of the list and gives only the 3rd.....

ex: (ret-odds (list 'a 'g 'e )) the procedure instead skips over the g and e and gives me null s开发者_高级运维o i only end up with a so i was wondering how would i fix this?


Your code is always skipping the last element in the list:

  1. On the first invocation with (list 'a 'd 'e), lst is non-null and (cdr lst) is non-null, so it takes the car ('a) and does a recursive call with the cddr (which is (list 'e))
  2. On the second invocation with (list 'e), lst is non-null but (cdr lst) is null. So it returns null, skipping the 'e completely.

Something like this should work:

 ex: (define (ret-odds lst)
      (if (null? lst) null
         (cons (car lst)
          (if (null? (cdr lst)) null (ret-odds (cdr (cdr lst)))))))


Change null of your second if to lst.

(define (ret-odds lst)
  (cond ((null? lst) lst)
        ((null? (cdr lst)) lst)
        (else (cons (car lst) (ret-odds (cddr lst))))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜