How to defun a function within a defun?

0 votes
asked Sep 22, 2010 by frost

For example, I pass the function name to another function

(personal-function 'func-name '(attr1 attr2 ...))

and what I want to do is

(defun personal-function (func-name)
     (defun func-name '(attr1 attr2 ...) (dosomething)))

However, it said I can't defun with a symbol... What should I do?

5 Answers

0 votes
answered Sep 22, 2010 by san-jacinto

You could use a lambda

If you're trying to make a new globally-accessible function inside a function, I don't think the language's grammar allows for that. If you create a lambda, you can initialize a variable to this lambda value and pass the variable around to your functions. In Common LISP, you can call (functionp x) to determine if a variable is a function before you try to call it.

0 votes
answered Sep 22, 2010 by zhongxia-zhou

Solve it as follows:


(defun create-function(a1)
  (defun plus-function(x) (+ x a1)))

(create-function 2) -> PLUS-FUNCTION
(plus-function 3) ->5


(setf (symbol-function 'printx) #'(lambda (x) (print x)))

(printx '(1 2 3)) -> (1 2 3)

Previously I also had the same problem when I defined the function.


(defun test-function(fn)
            (defun fn ((lambda() (print "aaa")))))

After I run

(test-function 'aaafunction)

The evaluation result is


It does not return a function named "aaafunction"...

To the person who downvote my answer: We are newbies of Lisp, but we are working hard to learn knowledge, and you are not so respectful.

0 votes
answered Sep 22, 2010 by alex

I use defmacros for metaprogramming, for example, this emacs lisp example.

0 votes
answered Sep 22, 2010 by rainer-joswig


(setf (symbol-function my-symbol) some-function)

create a new function with

(compile nil (list 'lambda args body))

where args and body have meaningful values.

0 votes
answered Sep 19, 2013 by harvis-wang

Using a macro will be a good choice. such as (defmacro personal-function (func-name) `(defun ,func-name '(attr1 attr2 ...) (dosomething))) please have a try, hope that helps you.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter