这段代码的每一行都发生了什么?

What is happening in each line of this code?

我知道整个代码是 return 列表的最后 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 大于列表的长度时,您应该 return 整个列表(或发出错误信号),我修复了它。这是代码的分解:

(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几次,并且在一个不必要的聪明算法中)