[plt-scheme] mreverse!
hello,
(require scheme/mpair)
(define lst (mlist 1 2 3 4)
(mreverse! lst)
> {4 3 2 1}
lst
> {1}
Unless I'm misunderstanding the point of mreverse!, that
seems like the wrong answer. Shouldn't lst evaluate to
{4 3 2 1}?
Here's the code for the function:
(define (mreverse! l)
(let loop ([l l][prev null])
(cond
[(null? l) prev]
[else (let ([next (mcdr l)])
(set-mcdr! l prev)
(loop next l))])))
The original list stops mutating after the first iteration
of the loop, i.e., after (set-mcdr! l null), which explains
the above result.
I tried fiddling with this (I assume the solution is very
simple) without success. I did write a rube goldberg-like
destructive reverse, but I'm eager to see what an elegant
solution looks like.
regards,
praimon