Can lisp functions return links or get arguments by reference?

I want to know how this works:

(setf (car x) 42)

Does (car x) return an assignable link to setf? Or is it just magic? How does setf or car work?

I know that following a link would be a terrible sin in functional programming, but I want to know how to do it.

+4
source share
2 answers

This is macro magic. Form (setf value) is nothing more than a specialized macro extension. For example, (setf (car x) 42) would translate something like this: (rplaca x 42).

You can see how your Lisp implementation extends the SETF form with MACROEXPAND, for example (my example uses SBCL, other implementations can have completely different extensions):

CL-USER> (macroexpand '(setf (aref foo 10) 1234)) (SB-KERNEL:%ASET FOO 10 1234) T 

You can also define your own extensions:

 CL-USER> (defvar *value* 0) *VALUE* CL-USER> (defun get-value () *value*) GET-VALUE CL-USER> (defun (setf get-value) (x) (setq *value* x)) (SETF GET-VALUE) CL-USER> (setf (get-value) 42) 42 CL-USER> (get-value) 42 CL-USER> (macroexpand '(setf (get-value) 23)) (LET* () (MULTIPLE-VALUE-BIND (#:NEW1058) 23 (FUNCALL #'(SETF GET-VALUE) #:NEW1058))) T 
+9
source

In Common Lisp, this is the place. Place is the form for which the setf expander is defined. This is something like a generic link.

For advanced treatment, see Hyperspec .

+6
source

Source: https://habr.com/ru/post/1347813/


All Articles