我知道整体代码将返回列表的最后n个元素,但是,我不了解该过程,就像每一行中正在发生的事情一样(以及为什么,如果可能的话)?
(define (last-n lst n)
(define (help-func lst drop)
(cond
((> drop 0)
(help-func (cdr lst ) (- drop 1)))
(else
(cdr lst ))))
(if (= (length lst ) n )
lst
(help-func lst (- (length lst ) 1 n ))))
答案 0 :(得分:3)
有一个小错误,当n
大于列表的长度时,您应该返回整个列表(或发出错误信号),我对此进行了修复。这是代码的细分:
(define (last-n lst n)
(define (help-func lst drop)
(cond
; iterate while there are elements to drop
((> drop 0)
; advance on the list, and we're one
; element closer to reach our target
(help-func (cdr lst) (- drop 1)))
(else
; else we reached the point we wanted, stop
(cdr lst))))
; if n is at least as big as the list
(if (>= n (length lst))
; return the whole list
lst
; else calculate how many elements
; we need to drop and start the loop
(help-func lst (- (length lst) 1 n))))
仅供参考,Racket已经具有此功能,只需使用take-right
内置过程,它甚至会更快,只需一次遍历列表(您将length
称为一对次数,并且采用了不需要的聪明算法)