From: Antony on
Hi

Many times I see in my code things like

(if (< (gethash x y) 10)
(incf (gethash x y) )

or things like
(if (= (aref a b) 10)
(setf (aref a b) 20)

(all stuff above is typed without any testing)

My question is how do people generally deal with this kind of repetition
(of places versus values of places)
I am guessing macros, but is there some other way or CL idiom for such
things.

-Antony
From: Raymond Wiker on
Antony <spam+lisp_dot_linux(a)gmail.com> writes:

> Hi
>
> Many times I see in my code things like
>
> (if (< (gethash x y) 10)
> (incf (gethash x y) )
>
> or things like
> (if (= (aref a b) 10)
> (setf (aref a b) 20)
>
> (all stuff above is typed without any testing)
>
> My question is how do people generally deal with this kind of
> repetition (of places versus values of places)
> I am guessing macros, but is there some other way or CL idiom for such
> things.

Check the Hyperspec for define-modify-macro.
From: Olof-Joachim Frahm on
Hello Antony,

Antony <spam+lisp_dot_linux(a)gmail.com> writes:

> My question is how do people generally deal with this kind of
> repetition (of places versus values of places) I am guessing macros,
> but is there some other way or CL idiom for such things.

Depends on what you like, imho symbol macros are clearer if you have
multiple places and have good names for them, otherwise using the reader
comes to mind. E.g.:

--8<---------------cut here---------------start------------->8---
(let ((hash (make-hash-table)) (x 42))
(setf (gethash x hash) 0)

(if (< (gethash x hash) 10)
(incf (gethash x hash)))

;; using the reader
(when (< #1=(gethash x hash) 10)
(incf #1#))

;; expanding PLACE to (GETHASH ...)
(symbol-macrolet ((place (gethash x hash)))
(when (< place 10)
(incf place)))

;; using an anaphoric variant from that package
(use-package :anaphora)
(slet (gethash x hash)
(when (< it 10)
(incf it)))

(gethash x hash))
--8<---------------cut here---------------end--------------->8---

Of course, if you have one pattern all over the place, just write
something ((local) function, macro) to reduce the clutter.

hth, Olof

--
The world is burning. Run.