How do I write Push and Pop in Scheme?

Posted by kunjaan on Stack Overflow See other posts from Stack Overflow or by kunjaan
Published on 2009-06-25T00:20:26Z Indexed on 2010/06/08 21:12 UTC
Read the original article Hit count: 205

Filed under:
|
|
|

Right now I have

(define (push x a-list)
  (set! a-list (cons a-list x)))

(define (pop a-list)
  (let ((result (first a-list)))
    (set! a-list  (rest a-list))
    result))

But I get this result:

Welcome to DrScheme, version 4.2 [3m].
Language: Module; memory limit: 256 megabytes.
> (define my-list (list 1 2 3))
> (push 4 my-list)
> my-list
(1 2 3)
> (pop my-list)
1
> my-list
(1 2 3)

What am I doing wrong? Is there a better way to write push so that the element is added at the end and pop so that the element gets deleted from the first?

© Stack Overflow or respective owner

Related posts about lisp

Related posts about Scheme