newLISP Fan Club

Forum => newLISP in the real world => Topic started by: incogn1to on April 30, 2011, 05:40:01 PM

Title: destructive functions & trees
Post by: incogn1to on April 30, 2011, 05:40:01 PM
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?
Title: Re: destructive functions
Post by: Kazimir Majorinc on April 30, 2011, 05:48:01 PM
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?
Title: Re: destructive functions
Post by: incogn1to on April 30, 2011, 08:58:56 PM
It doesn't work with passed values.
(set 'x '(0 1 2 '(3 4)))
(define (destruct lst) (setf (lst 3 0) 1))
(destruct x)
-> 1


This won't change the variable.
Title: Re: destructive functions & trees
Post by: johu on April 30, 2011, 10:51:12 PM
According to the manual,

//http://www.newlisp.org/downloads/newlisp_manual.html#pass_big


QuotenewLISP 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/newlisp_manual.html#pass_big


QuoteStrings and lists, which are packed in a namespace using default functors, are passed automatically by reference:


For example:

> (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).
Title: Re: destructive functions & trees
Post by: Kazimir Majorinc on May 01, 2011, 03:40:12 AM
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
(define (destruct lst)
           (letex((lst lst))
              (setf (lst 3 0 0) 1)
              (setf (lst 3 0 1) 2)))
           
Title: Re: destructive functions & trees
Post by: incogn1to on May 01, 2011, 05:25:50 AM
Thank you fro the answers, that solved the problem.