我知道整个代码是返回列表的最后第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 ))))
有一个小错误,当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
几次,并且在一个聪明的算法中将是不必要)