Adam Hinz: The Blog
anything python can do, scheme can do better
On 2007-12-16 at 12/16/2007 10:07:00 PM...
Jens Lekman - A Man Walks Into a BarI started learning Python today just for the hell of it, and I found out you can access the last items in a list with a negative index. I thought, "shit, I bet Scheme can do that just fine," and here's my solution:
(define list-ref-a
(lambda (ols n)
(letrec ([list-ref-n-help
(lambda (ls count k)
(cond
[(and (null? ls) (> (- n) count))
(error 'list-ref "index ~s is out of range for list ~s"
n ols)]
[(null? ls) 0]
[else (let ([res
(add1
(list-ref-n-help (cdr ls) (add1 count) k))])
(cond
[(= n (- res)) (k (car ls))]
[else res]))]))])
(cond
[(>= n 0) (list-ref ols n)]
[else (call/cc (lambda (k) (list-ref-n-help ols 0 k)))]))))