Page 1 of 1

Returning by reference

Posted: Sat Dec 26, 2009 12:36 am
by kks
Hi,

How to "return by reference" from a user-defined function/macro?

Code: Select all

(let (l '(a b c)) (pop l) l)   # => (b c)
(let (l '(a b c)) (pop (or l)) l)   # => (b c)
(let (l '(a b c)) (pop (println l)) l)   # => (a b c); is this a bug?
(let (l '(a b c)) (pop (begin (println l) l)) l)   # => (b c)
(let (l '(a b c)) (pop (let () l)) l)   # => (a b c); is this a bug?
(let (l '(a b c)) (pop ((fn () l))) l)   # => (a b c); how to make it return (b c)?
My intention is to write a debugging macro:

Code: Select all

(define-macro (%p) (println "% " (args 0) " = " (eval (args 0))))

(let (l '(a b c)) (pop (%p l)) l)   # => (a b c); how to make it return (b c)?
Thanks,
KS

Re: Returning by reference

Posted: Sat Dec 26, 2009 12:49 pm
by kks
By the way, in the following code:

Code: Select all

(setq x ((fn () '(a b c))))   # => (a b c)
does it perform ONE (either when returning or binding) or TWO (both) copy operations?

Is it possible to make all sequences return "by reference"? I think this still conforms to ORO (One Reference Only) memory management, as it is "binding" (set, let, parameter binding), not "returning", that causes "referencing"!

Re: Returning by reference

Posted: Sat Dec 26, 2009 4:20 pm
by cormullion
kks wrote: (let (l '(a b c)) (pop (println l)) l) # => (a b c); is this a bug?
Hi! I would guess not a bug:

Code: Select all

> (set 'l '(a b c))
(a b c)
> (println l)
(a b c)
(a b c)
> (pop (println l))
(a b c)
a
> l
(a b c)
since pop operated on the result returned by println rather than on l. That's only my guess, though...

Re: Returning by reference

Posted: Sat Dec 26, 2009 4:42 pm
by itistoday
User defined functions always pass things around by value, but there are ways of getting around this by passing "containers" by value (i.e. symbols or contexts).

You may want to look at the thread on the gen-wrapper function.