Reputation: 21
I know the overall code is to return the last nth elements of the list, however, I don't understand the process, like in each line what is happening(and why, if possible)?
(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 ))))
Upvotes: 0
Views: 86
Reputation: 235984
There's a small bug, when n
is greater than the length of the list you should return the whole list (or signal an error), I fixed it. Here's a break-down of the code:
(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))))
FYI, Racket already has this functionality, just use the take-right
built-in procedure, it'll even be faster, requiring a single pass over the list (you're calling length
a couple of times, and in a clever algorithm that would be unnecessary)
Upvotes: 3