For Programmers: Free Programming Magazines  


Home > Archive > Scheme > December 2005 > how to write a function like (set! x y) ?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author how to write a function like (set! x y) ?
abraham

2005-12-12, 7:17 pm

Hi!
I'm sorry if this has been asked before, but I'm new to scheme, and a
search on google didn't yield any results, nor in this newsgroup
(although I'm not too good at searching newsgroups) ...

I want to program a function (test x y) that acts like (set! x), so that
if I enter
(test a 7)
It sets a to the value of 7.
At first I tried to write the following:
(define (test x y)
(set! x y))
which obviously did not work, because it sets _x_ to y and not the
symbol-name contained in x...

Then I had the idea that I could write a function (return a) that
returns the value of x, in this case a symbol, and subsitute x in the
function with (return x):

(define (test x y)
(define (return a) a)
(set! (return x) y))

This didn't work either, it says:
"set!: not an identifier in: (return x)"

Does anyone have any suggestions on how I can write the function?
Thanks for any help.
/Abraha
Eric Hanchrow

2005-12-12, 7:17 pm

>>>>> "abraham" == abraham <abraham.w@home.se> writes:

abraham> I want to program a function (test x y) that acts like
abraham> (set! x)

abraham> Does anyone have any suggestions on how I can write the
abraham> function? Thanks for any help.

You want a macro. Read about macros.

--
None of the ... actors do anything we couldn't do if we looked
like them.
-- Roger Ebert, reviewing "The Chronicles Of Riddick"
drcode@gmail.com

2005-12-12, 7:17 pm

You cannot write a function that can do this- Whenever you call the
function it will always send the VALUE of x, not its name. You would
need to write a macro, or use eval (highly discouraged)

try:

(define (test x y)
(eval `(set! ,x ,y)))
[color=darkred]

(defmacro (test x y)
`(set! ,x ,y))
[color=darkred]

or use hygenic macros (SYNTAX-CASE)

-Conrad Barski

Anton van Straaten

2005-12-12, 7:17 pm

drcode@gmail.com wrote:
> or use hygenic macros (SYNTAX-CASE)


To do it in standard (R5RS) Scheme, you would need to use a syntax-rules
macro:

(define-syntax test
(syntax-rules ()
((test x y)
(set! x y))))

(define a #f)
(test a 7)
(display a) ;=> 7
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com