Page 1 of 1

Destructive functions?

Posted: Mon Apr 14, 2008 9:08 pm
by hsmyers
What is the pattern for writing functions that change their parameters in the calling scope? For instance this clearly doesn't work:

Code: Select all

(define (strip move)
  (replace "[+#]" move "" 0))
So what would?

--hsm

Posted: Mon Apr 14, 2008 10:01 pm
by cormullion
In that example, move is local to the function, and won't survive the function.

Obviously, this is one way:

Code: Select all

(set 'm (strip m))
cos you're usually working with the values of evaluated functions. But how about this:

Code: Select all

(define (strip move) 
  (replace "[+#]" move "" 0))

(set 'm "+blah")

(strip m)
;-> "blah"

m
;-> "+blah"

(define-macro (strip move) 
  (replace "[+#]" (eval move) "" 0)) 

(set 'm "+blah")

(strip m)
;-> "blah"

m
;-> "blah"
Looks like we can pass the symbol itself...

Posted: Mon Apr 14, 2008 11:46 pm
by Jeff
You don't need a macro for that; just pass a quoted symbol.

Posted: Tue Apr 15, 2008 12:33 am
by hsmyers
Thanks all. The use of eval means that I can use it either way, as a value for set or setq and as a direct change--- cool!

--hsm