Getting every nth atom using scheme does not pick up the last atom

后端 未结 3 1446
野趣味
野趣味 2020-12-04 04:00

The program is suppose to pick out every third atom in a list. Notice that the last atom \'p\' should be picked up, but its not. Any suggestions as to why the last atom is n

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 04:29

    You're missing a couple of base cases:

    (define (every3rd lst)
      (cond ((or (null? lst) (null? (cdr lst))) lst)
            ((null? (cdr (cdr lst))) (list (car lst)))
            (else (cons (car lst)
                        (every3rd (cdr (cdr (cdr lst))))))))
    

    See how the following cases should be handled:

    (every3rd '())
    => '()
    
    (every3rd '(a))
    => '(a)
    
    (every3rd '(a b))
    => '(a)
    
    (every3rd '(a b c))
    => '(a)
    
    (every3rd '(a b c d))
    => '(a d)
    
    (every3rd '(a b c d e f g h i j k l m n o p))
    => '(a d g j m p)
    

提交回复
热议问题