defparameter vs defun for passing functions around
Asked Answered
D

1

6

So I can do this:

(defparameter *some-function* ... ; returns lambda later

or this:

(defun some-function ...

With either, I can use funcall:

(funcall 'some-function ... or (funcall *some-function* ...

With the defun version I can also do this:

(some-function ...

I cannot do that with the defparameter function.

defparameter provides easier technique for re-assigning some-function to a different function (or anything else, including non-function data) later.

But other than these two points, what are other considerations of using one over another?

Degrading answered 31/10, 2013 at 14:29 Comment(1)
Depending on what exactly you're trying to do, fundamentally, you may also want to consider flet and/or labels, which I find a nice description of here.Sovereignty
H
9

This is an odd one to answer as we are somewhat comparing apples with oranges.

For those new to lisp who are looking at this, defparameter is for defining a dynamic variable whereas defun is for defining a function.

If you are worried about being able to programmatically reassign a function without using defun check out the following:

CL-USER> (defun jam () (print 'some-jam))
JAM

CL-USER> (jam)
SOME-JAM 

CL-USER> (setf (symbol-function 'jam) (lambda () (print 'some-ham)))
#<FUNCTION (LAMBDA ()) {1004C033DB}>

CL-USER> (jam)
SOME-HAM 

So defparameter doesn’t have an advantage when it comes to reassigning a function. Also if you want to redefine the function you could look into the compile command.

Herl answered 31/10, 2013 at 14:51 Comment(7)
You can also use (setf (fdefinition 'jam) ...) here, and fdefinition will work on all function names (including (setf ...) functions, not just symbols.Contemporaneous
@JoshuaTaylor: Brilliant, I didn’t know about that. Cheers (also good point about let)Herl
There's still an advantage with defparameter that let will bind a new value and restore the old value automatically for you, without you having to store it explicitly. E.g., compare the two snippets in this paste.Contemporaneous
For those looking at that paste, consider using unwind-protect to restore the fdefinition.Fining
Note that "A call within a file to a named function that is defined in the same file refers to that function, unless that function has been declared notinline. The consequences are unspecified if functions are redefined individually at run time or multiply defined in the same file." clhs.lisp.se/Body/03_bbc.htmFining
Or just use defun again: (defun jam () (print 'some-ham)). ;-) defun is not like defvar in not updating.Damle
This question shows another important distinction between defparameter and defun: stackoverflow.com/questions/19919918Degrading

© 2022 - 2024 — McMap. All rights reserved.