[plt-scheme] Re: Lexical Scoping, References and Side Effects
Does this do what you want?
-----
#lang scheme
(define-syntax (stack-push stx)
(syntax-case stx ()
((_ name item)
#`(set! name (cons item name)))))
(define stack-top
(lambda (s)
(car s)))
-----
Then in the interactions pane I can do:
> (define stack '())
> (stack-push stack 1)
> (stack-top stack)
1
Note that I do have to quote () in the first line, but I don't think
that that was the focus of your question.
Incidentally I've just been doing a lot of stack-based system
development in DrScheme -- I work on a kind of genetic programming
based on stack machines -- and I do a lot of destructive stack
modification. I use different ideas than I presented here, but it's a
messier context...
-Lee
On Sep 2, 2009, at 10:42 AM, tbourdon wrote:
> As I said, "For my second implementation I had the stack-push function
> just return the updated stack but as you can see this leads to
> successive set! calls" and that's the whole point. I don't want stack-
> push to return anything. I want it to change the state of the stack
> that's passed in so the caller can reference that stack's changed
> state later. In other words, is there a way for the following to work?
>
> (define stack ()) ; stack is defined as empty list.
> (stack-push stack 1) ; stack-push pushes 1 onto stack.
> (stack-top stack) => 1 ; stack-top returns 1.
>
> On Sep 2, 12:30 am, Matthias Felleisen <matth... at ccs.neu.edu> wrote:
>> On Aug 30, 2009, at 7:42 PM, tbourdon wrote:
>>
>>
>>
>>> Hello -
>>
>>> I'm currently teaching myself Scheme by working through "Teach
>>> Yourself Scheme in Fixnum Days" and "The Little Schemer". As I was
>>> working through the sources I decided to break off and implement
>>> some
>>> stack data structures. So far I've implemented the stack functions
>>> three different ways and I've noticed that I really can't (or
>>> haven't
>>> found a way) to create a reference to a stack and pass it around
>>> to be
>>> operated on.
>>
>>> For example; I can't come up with an implementation for a stack-push
>>> function where the following works:
>>
>>> (define stack ())
>>> (stack-push stack 1)
>>> (stack-top stack) => 1
>>
>> You omitted the most important part of your quasi-spec? What should
>> stack-push return?
>>
>> _________________________________________________
>> For list-related administrative tasks:
>> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> _________________________________________________
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
--
Lee Spector, Professor of Computer Science
School of Cognitive Science, Hampshire College
893 West Street, Amherst, MA 01002-3359
lspector at hampshire.edu, http://hampshire.edu/lspector/
Phone: 413-559-5352, Fax: 413-559-5438
Check out Genetic Programming and Evolvable Machines:
http://www.springer.com/10710 - http://gpemjournal.blogspot.com/