Page 1 of 1
destructive functions & trees
Posted: Sun May 01, 2011 12:40 am
by incogn1to
I have a few questions about destructive functions. Can anybody explain why setf doesn't work with passed values ? It may return correct value, but it doesn't change the variable itself.
PS maybe it would be better if I describe full problem:
I need to edit branches or / and leafs inside a tree. I wanted to pas the branch as a parameter to my changing function, and process it with destructive pop and push functions, but it doesn't work. Is there a right way to do this?
Re: destructive functions
Posted: Sun May 01, 2011 12:48 am
by Kazimir Majorinc
It works for local variables
> (let((x 1))(setf x 7)(* 2 x))
14
> (local(x)(setf x 8)(+ x 1))
9
What exactly do you dislike?
Re: destructive functions
Posted: Sun May 01, 2011 3:58 am
by incogn1to
It doesn't work with passed values.
Code: Select all
(set 'x '(0 1 2 '(3 4)))
(define (destruct lst) (setf (lst 3 0) 1))
(destruct x)
-> 1
This won't change the variable.
Re: destructive functions & trees
Posted: Sun May 01, 2011 5:51 am
by johu
According to the manual,
http://www.newlisp.org/downloads/newlis ... l#pass_big
newLISP passes parameters by value copy.
Variable's
lst in function
destruct is not
x, but the copy of
x.
Then
x is not changed.
And according to the same chapter in manual.
http://www.newlisp.org/downloads/newlis ... l#pass_big
Strings and lists, which are packed in a namespace using default functors, are passed automatically by reference:
For example:
Code: Select all
> (set 'y:y '(0 1 2 (3 4)))
(0 1 2 (3 4))
> (define (destruct lst) (setf (lst 3 0) 1))
(lambda (lst) (setf (lst 3 0) 1))
> y:y
(0 1 2 (3 4))
> (destruct y)
1
> y:y
(0 1 2 (1 4))
>
Note that there is no quote before
(3 4).
Re: destructive functions & trees
Posted: Sun May 01, 2011 10:40 am
by Kazimir Majorinc
Without using contexts, demonstrated by johu, if you want
pass by reference, you should really
pass the reference of the structure (not the structure itself), and make your function dereference it:
(set 'x '(0 1 2 (3 4)))
(define (destruct lst) (setf ((eval lst) 3 0 0) 1)) ; eval is dereference
(println x) ; =>(0 1 2 (3 4))
(setf (x 3 0) 4)
(println x) ; =>(0 1 2 (4 4))
(destruct 'x) ; passes symbol x, which is reference of the list stored as value of x
(println x) ; =>(0 1 2 (1 4))
Another way for dereference (if you want to do it once in larger blocks) is
Code: Select all
(define (destruct lst)
(letex((lst lst))
(setf (lst 3 0 0) 1)
(setf (lst 3 0 1) 2)))
Re: destructive functions & trees
Posted: Sun May 01, 2011 12:25 pm
by incogn1to
Thank you fro the answers, that solved the problem.