Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Problem with iteration

19 views
Skip to first unread message

WJ

unread,
May 2, 2012, 5:09:25 AM5/2/12
to
Erik Naggum wrote:

> * Raffael Cavallaro
> | (defun my-reverse (a-list)
> | (do ((n (- 1) (incf n)) (result '() (cons (nth n a-list) result)))
> | ((= n (- (length a-list) 1)) result )))
>
> yikes.
>
> (defun my-reverse (list)
> (do ((reversed (list (pop list))
> (cons (pop list) reversed)))
> ((endp list) reversed)))

Buggy:

* (my-reverse '())

(NIL)


And POP won't work on immutable lists.

Let's do it the right way using Racket:

(define (my-reverse alist)
(do ((accum '() (cons (car alist) accum))
(alist alist (cdr alist)))
((null? alist) accum)))

Tim Bradshaw

unread,
May 2, 2012, 6:29:37 AM5/2/12
to
On 2012-05-02 09:09:25 +0000, WJ said:

> And POP won't work on immutable lists.

Uh, what? There are no cases where this is not fine:

(defun ok (l)
(assert (consp l) (l) "~A is not a cons" l)
(pop l))

WJ

unread,
May 2, 2012, 6:39:15 AM5/2/12
to
Of course, using do isn't the best way.

(foldl cons '() '(a b c))
=> '(c b a)

Pascal J. Bourguignon

unread,
May 2, 2012, 7:42:20 AM5/2/12
to
"WJ" <w_a_...@yahoo.com> writes:

> Erik Naggum wrote:
>
>> * Raffael Cavallaro
>> | (defun my-reverse (a-list)
>> | (do ((n (- 1) (incf n)) (result '() (cons (nth n a-list) result)))
>> | ((= n (- (length a-list) 1)) result )))
>>
>> yikes.
>>
>> (defun my-reverse (list)
>> (do ((reversed (list (pop list))
>> (cons (pop list) reversed)))
>> ((endp list) reversed)))
>
> Buggy:
>
> * (my-reverse '())
>
> (NIL)
>
>
> And POP won't work on immutable lists.

POP doesn't work on lists, immutable or not. POP works on places.

list is a VARIABLE: it is mutable! Duh!

--
__Pascal Bourguignon__ http://www.informatimago.com/
A bad day in () is better than a good day in {}.
0 new messages