3 Dec 2009 ingvar   » (Master)

Neat(ish) hack...

Sometimes, I find myself writing anonymous functions, to fill out keyword arguments for functions or adapting the argument order. So, I thought, how hard would it be to write a macro to write the code for me? Turns out, not very complex, at all. The formatting is not QUITE what I started out with, as the Advogato edit box is a bit on the short end, but, hey...


(defmacro _ (form)
 (flet ((is-arg (sym)
	  (ignore-errors
	   (and (char= (char (symbol-name sym) 0) #\_)
		(cons
		 (parse-integer (symbol-name sym)
				:start 1)
		 sym)))))
   (let ((syms (loop for arg in form
		  for temp = (is-arg arg)
		  if temp collect temp)))
    `(lambda
	 ,(mapcar #'cdr (sort syms #'< :key #'car))
       ,form))))

With this in hand, you can, for example, easily make an adapter to parse C-style hex constants:


  (_ (parse-integer _1 :radix 16 :start 2))

Not that the lambda-wrapping of this would've been much more complex and I am not entirely sure this wins as far as readability is concerned, but that is as it may be. It's if nothing else a neat macro that would be more than a little tricky to pull off with a less capable macro facility.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!