I'm using mapcar in Common Lisp, and I've seen examples that use #' and ' in front of the + but they both appear to do the same thing. Does it matter which is used?
CL-USER> (mapcar '+ '(1 2) '(2 3))
(3 5)
CL-USER> (mapcar #'+ '(1 2) '(2 3))
(3 5)
I'm using mapcar in Common Lisp, and I've seen examples that use #' and ' in front of the + but they both appear to do the same thing. Does it matter which is used?
CL-USER> (mapcar '+ '(1 2) '(2 3))
(3 5)
CL-USER> (mapcar #'+ '(1 2) '(2 3))
(3 5)
They are often interchangeable, but are not the same thing. mapcar
takes a function designator – a symbol designating a symbol-function
or a function designating itself – which will be coerced to a function object. #'foo
is a reader macro that expands to (function foo)
, which returns a function object by looking up the functional value of foo
in the lexical environment, i.e. the innermost flet
, labels
, or the global function definition. Thus, nothing needs to be done to coerce it. If you use a quoted symbol with mapcar
, however, it is coerced to a function using symbol-function
, which will not work with non-global function definitions, as there are no fboundp
symbols involved in this case. For example:
CL-USER> (flet ((frob (x) (1+ x)))
(mapcar #'frob '(1 2 3)))
(2 3 4)
CL-USER> (flet ((frob (x) (1+ x)))
(mapcar 'frob '(1 2 3)))
; Evaluation aborted on #<CCL::UNDEFINED-FUNCTION-CALL #x18AB7F1E>.
Also, when exactly the coercion happens, is implementation dependent, which has consequences for self or mutualy redefining code.
In general, using #'
seems to be widely preferred nowadays, probably because it is felt to be more consistent – using #'
everywhere you want to pass a function is a simple rule. I rarely see quoted symbols used with functions taking function designators in CL. In other dialects however, especially older or dynamically scoped ones like Emacs Lisp, passing quoted symbols to these functions is quite common.