2016-03-28 82 views
-2

我知道如何获得第一n元素的列表,获取在DrRacket列表中最后n个元素,而无需列表裁判

(define (countup n ls) 
    (cond 
    [(zero? n) '()] 
    [else (cons (first ls) (countup (sub1 n) (rest ls)))])) 

,但我怎么能为最后做这样的事情n列表中的元素(不使用list-ref)

如果我打电话(countup 3 '(a b c d e)),我得到(list a b c)。我需要能够输入(counter 3 '(a b c d e))并获得(list c d e)

如果数字n大于列表长度,我需要错误消息。

回答

2

只需使用内置take-right程序,它正是你需要:

(take-right '(a b c d e) 3) 
=> '(c d e) 

或者你可以从头开始使用原始程序实现它,:

(define (counter n lst) 
    (define (move n lst) 
    (if (zero? n) 
     lst 
     (move (sub1 n) (rest lst)))) 
    (define (trim-left lst rst) 
    (if (empty? rst) 
     lst 
     (trim-left (rest lst) (rest rst)))) 
    (trim-left lst (move n lst))) 

它也可以作为预计:

(counter 3 '(a b c d e)) 
=> '(c d e) 
+0

我需要能够做到这一点而不使用take-right – KrissyMichaelsson

+0

altho I谢谢你的帮助,我不能使用trim,take,move或list-ref。 – KrissyMichaelsson

+0

我不使用任何这些,我只是定义了两个名为'move'和'trim-left'的帮助程序。无需使用额外的助手即可,无法轻松解决此问题。 –