(define (slice a-list start end)
(define (slicify n)
(if (negative? n)
(+ (length a-list) n)
n))
(let* ((s (slicify start))
(e (slicify end))
(len (abs (- s e))))
(take (drop a-list (min s e)) len)))
More complicated than the other attempts, but
>(define l '(1 2 3 4 5 6 7 8 9 0))
l
>(slice l 3 6)
'(4 5 6)
>(slice l 2 -2)
'(3 4 5 6 7 8)
>(slice l -3 -8)
'(3 4 5 6 7)
I'm sure I missed edge cases and other interactions, but this is a bit closer to how python treats slicing. It is sort of surprising that you have to write this yourself instead of having it provided. That said, I've never really found myself slicing very much in Scheme. And when I do, it's typically easier/more semantically accurate to use take
, drop
and list-ref
than actual slicing.