[plt-scheme] mreverse!

From: praimon (praimon at gmail.com)
Date: Sat Jan 24 15:57:56 EST 2009


(require scheme/mpair)

(define lst (mlist 1 2 3 4)
(mreverse! lst)
> {4 3 2 1}
> {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])
     [(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.


Posted on the users mailing list.