Search code examples
functioncommon-lispsymbolskeyworddispatch

Function or Macro to Apply Other Functions Determined by Keywords


I would like to be able to write a function like:

(dispatchme :foo)

which then executes:

(foo!)

in which the colon of the colon has been stripped off the keyword and (in this case) and exclamation point has been added to determine the final function name. foo! is defined separately and I want to avoid using some kind of dispatch table such as using cond or a hash-table - there could be a number of keyword/function pairs in principle.


Solution

  • If you assume that the conventions you imply are observed, you can simply do that, but you need to think about the package. I'll assume that you have that in a special variable, but maybe you want *package* (i. e. the current package at run time) or #.*package* (i. e. the current package at read time) there:

    (defun call-by-key (keyword)
      (funcall (intern (concatenate 'string (symbol-name keyword) "!")
                       *special-package*)))
    

    However, the only sensible use case I have seen for such things is when the required packages have not been created yet at the time when the function call is read, i. e. in a system definition (ASDF). So, the question for me would be: what are you trying to do?