fork download
  1. ; nth from the end
  2.  
  3. (define (nth-last n xs)
  4. (list-ref (reverse xs) (- n 1)))
  5.  
  6. (display (nth-last 3 '(1 2 3 4 5 6 7 8 9))) (newline)
  7.  
  8. (define (nth-last n xs)
  9. (list-ref xs (- (length xs) n)))
  10.  
  11. (display (nth-last 3 '(1 2 3 4 5 6 7 8 9))) (newline)
  12.  
  13. (define (nth-last n xs)
  14. (let loop ((n n) (rabbit xs) (greyhound xs))
  15. (if (positive? n) (loop (- n 1) (cdr rabbit) greyhound)
  16. (if (pair? rabbit) (loop n (cdr rabbit) (cdr greyhound))
  17. (car greyhound)))))
  18.  
  19. (display (nth-last 3 '(1 2 3 4 5 6 7 8 9))) (newline)
Success #stdin #stdout 0.02s 50288KB
stdin
Standard input is empty
stdout
7
7
7