Destructive functions?

For the Compleat Fan
Locked
hsmyers
Posts: 104
Joined: Wed Feb 20, 2008 4:06 pm
Location: Boise, ID, USA
Contact:

Destructive functions?

Post 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
"Censeo Toto nos in Kansa esse decisse."—D. Gale "ℑ♥λ"—Toto

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post 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...

Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Post by Jeff »

You don't need a macro for that; just pass a quoted symbol.
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

hsmyers
Posts: 104
Joined: Wed Feb 20, 2008 4:06 pm
Location: Boise, ID, USA
Contact:

Post 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
"Censeo Toto nos in Kansa esse decisse."—D. Gale "ℑ♥λ"—Toto

Locked