Autogenerating functions in emacs-lisp

| categories: emacs-lisp, emacs | tags: | View Comments

I have a need to generate a lot of similar functions, and I do not want to cut and paste the code. I want to generate the functions with code. This seems to be what macros are for in emacs lisp.

As a prototype example, we will make functions that raise a number to a power. We want functions like power-3 and power-4 that raise numbers to the third and fourth powers. We will define functions like this for the numbers 0-9.

Here we define the macro. i do not want to get into the nitty gritty details of macro definitions here.

(defmacro make-power-n (n)
 `(defun ,(intern (format "power-%s" n)) (arg) (expt arg ,n)))

(make-power-n 4)

(power-4 4)
256

Now we use the macro and mapcar on it onto a list of numbers. We have to eval the macro in the mapcar lambda function.

(defmacro make-power-n (n)
 `(defun ,(intern (format "power-%s" n)) (arg) (expt arg ,n)))

(mapcar (lambda (x) (eval `(make-power-n ,x))) '(0 1 2 3 4 5 6 7 8 9))
 
;; example of a few functions
(list (power-0 3) (power-1 3) (power-2 3))
1 3 9

It works! We created 10 functions in a little bit of code.

Copyright (C) 2014 by John Kitchin. See the License for information about copying.

org-mode source

Org-mode version = 8.2.6

blog comments powered by Disqus