Feeds:
Posts
Comments

Posts Tagged ‘lisp macros’

Lisp Macros and Types

(message ...) already accepts a format string, but if it didn’t it would be easy to add that functionality with a macro.

(defmacro message* (str &rest vars)
  `(message (format ,str ,@vars)))

But it only accepts a single format string. Perhaps I would like to concatenate a few strings or variables together. But then if I only pass a string in, I want that to work correctly too. Macros can generate different code if you pass in different types. (I fix the underlying format* so I can use it in message, error, etc.)

(defmacro format* (str &rest vars)
  (if (stringp str)
      `(format ,str ,@vars)
    `(format (concat ,@(mapcar #'identity str)) ,@vars)))

The result looks a little strange. When I see an unquoted list, the first element has to be the name of the function that is being called.

(defvar x "xxx")
(format* (x " " "%s") 1) ;; --> "xxx 1"

Read Full Post »

Follow

Get every new post delivered to your Inbox.