Wednesday, 7 February 2007

orf (a Common Lisp version of ||=)

I've recently been programming in ruby and one of the handy operators I've
been using has been ||= .

If you haven't seen it before think of it in terms of += .
So x ||= 3 is equivalent to x = x || 3.

I've found this pretty useful in a couple of cases and decided to write a
CL implementation of it. I give you ORF.


(defmacro orf (place value &environment env)
(multiple-value-bind (vars vals store-vars writer reader)
(get-setf-expansion place env)
`(let* (,@(mapcar 'list vars vals)
(,@store-vars (or ,reader ,value)))
,writer)))

So now (orf x 3) === (setf x (or x 3))

with the minor caveat that x will only being evaluated once.

Truly, Lisp is the Borg of programming languages.

No comments: