Creating functions with reference returns

For the Compleat Fan
Locked
Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Creating functions with reference returns

Post by Jeff »

Is there a way to return a reference that could be used in setf? For example:

Code: Select all

(define-macro (foo) (first (args 0)))
(setf bar '(1 2 3))
(setf (foo bar) 3)
; bar now is '(3 2 3)
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

no, only into the function the reference to the entire object:

Code: Select all

(set 'Mydb:Mydb (sequence 1 100))

(define (change-db obj idx value)
    (setf (obj idx) value))

(change-db Mydb 50 "abcdefg")

(Mydb 50) => "abcdefg"

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

Post by Jeff »

Not tellin' you how to do your job or anything, but it *sure* would be nice to be able to do reference returns in our functions. Boy oh boy would it :)
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

You can't have both, the style of fast resource saving, synchronous memory management newLISP has and the type of reference returns you are describing.

But you can adjust your programming style to it and will never miss it ;-)

Kazimir Majorinc
Posts: 388
Joined: Thu May 08, 2008 1:24 am
Location: Croatia
Contact:

Post by Kazimir Majorinc »

The question is - what is reference? Newlisp has no real references, at least not the part exposed to users. Lutz sometimes used that term to explain behaviour of the expressions like (setf (first L) 3) to those familiar with, say, C++ - but it was informal. However, we can define references, as, for example

(1) symbols to object, for example L
(2) expressions of the form (L 0) (L 1) ... (L 0 3 5) ...

Once we defined references, we can write our own functions that return references.

Code: Select all

(set 'random-reference 
     (lambda-macro(list-name)
        (list list-name (rand (length (eval list-name))))))

; (random-reference L) => (L 3), (L 7), (L 2), ...
        
(set 'setg (lambda(x y)
               (letex ((x x))
                    (setf x y))))

(setg 'L '(1 2 3 4 5))

(for (j 100 110)
  (setg (random-reference L) j)
  (println "L=" L))
(exit)
  
L=(100 2 3 4 5)
L=(100 2 101 4 5)
L=(102 2 101 4 5)
L=(102 2 101 4 103)
L=(102 2 104 4 103)
L=(102 2 105 4 103)
L=(102 106 105 4 103)
L=(102 106 105 4 107)
L=(102 106 105 4 108)
L=(102 106 105 109 108)
L=(110 106 105 109 108)
More expressive - and complicated - approach would be to abandon all anonymous values, and to insist that all values are assigned to some symbol. Instead of L=>(1 2 3) always using L=>(L1 L2 L3) where L1=>1, L2=>2, L3=>3. Such L1, L2, L3 can be used as references.

Locked