1

Let's suppose I have a string "foo" and want to create a function that would be an equivalent of (defun foo (...) ...).

Is there a nice way to do it?

I played with make-symbol and fset, but could not get a working snippet: I fail to produce a new cell to attach both a name and code to.

(Why am I doing this: to better understand how it works.)

3

Try this:

(let ((name "foo")) (fset (intern name) (lambda (x) (* 2 x))))
(foo 21) ; 42

Brief explanation: (intern name) creates a symbol with the given name and adds it to the list of accessible symbols (that is what interning means). But if the symbol with that name already exists, it does nothing; just returns the already existing symbol.

And (lambda …) creates a function with the given argument list and body.

Addendum: It may be more appropriate to use defalias than fset. See the manual for more on this:

The proper place to use defalias is where a specific function name is being defined—especially where that name appears explicitly in the source file being loaded. This is because defalias records which file defined the function, just like defun (see Unloading).

By contrast, in programs that manipulate function definitions for other purposes, it is better to use fset, which does not keep such records. See Function Cells.

  • 1
    To define you should use defalias. fset should only be used for low-level manipulation. – Stefan Apr 26 at 0:28
  • @Stefan I added a bit on that. (The manual seems a bit more nuanced on when to use defalias.) – Harald Hanche-Olsen Apr 26 at 9:28
  • Poking around, I discovered that defalias is a primitive (defined in C code), while defun is a macro which is basically just a wrapper around defalias. After all these years using emacs, I had no idea! – Harald Hanche-Olsen Apr 27 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.