help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: defining a setter function with gv.el


From: Stefan Monnier
Subject: Re: defining a setter function with gv.el
Date: Mon, 27 Aug 2012 08:54:42 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.2.50 (gnu/linux)

> I am very new to setf. I would like to write a function that provides a
> place for setf to work on an alist. It would be wonderful if the
> function also worked as a getter.

The idea of setf is that you can define a getter (foo ARGS) which return
the data you want and then you can explain to setf how (setf (foo ARGS) VAL)
should work such that after that (foo ARGS) returns VAL.

> (defun my-function (&optional value)
>   (if value
>       (?)
>     (cdr (assoc 'oak tree))))
> (my-function) => tree
> (my-function 'shrub)
> foo => '((oak . shrub))

So I think what you mean is that you want

  (my-function) => tree
  (setf (my-function) 'shrub)
  (my-function) => shrub

So the "setf expander" for `my-function' will tell `setf' what
(setf (my-function) 'shrub) should macro-expand to.
  
> gv.el seems to have what I need to implement the setf portion.
> It doesn't provide example and I couldn't find doc in the elisp info.

gv.el itself has plenty of examples, I think.  As for Elisp doc, they
indeed haven't been updated for it yet, but you might like to look at
the CL documentation and then read the beginning of gv.el to understand
how they 2 differ.

As for you specific question, I suspect that it is answered in the last
few lines of gv.el:

   ;;; Vaguely related definitions that should be moved elsewhere.
   
   ;; (defun alist-get (key alist)
   ;;   "Get the value associated to KEY in ALIST."
   ;;   (declare
   ;;    (gv-expander
   ;;     (lambda (do)
   ;;       (macroexp-let2 macroexp-copyable-p k key
   ;;         (gv-letplace (getter setter) alist
   ;;           (macroexp-let2 nil p `(assoc ,k ,getter)
   ;;             (funcall do `(cdr ,p)
   ;;                      (lambda (v)
   ;;                        `(if ,p (setcdr ,p ,v)
   ;;                           ,(funcall setter
   ;;                                     `(cons (cons ,k ,v) ,getter)))))))))))
   ;;   (cdr (assoc key alist)))
   
If you uncomment the above, then (alist-get KEY ALIST) will do the
obvious lookup and (setf (alist-get KEY ALIST) VAL) will do the expected
in-place modification of ALIST so that (alist-get KEY ALIST) then
returns VAL.


        Stefan



reply via email to

[Prev in Thread] Current Thread [Next in Thread]