0

Possible Duplicate:
What does # mean in LISP

I am learning lisp, but one thing I do not understand is why it is necessary for #' to be used. If a function with a specific name exists, why would lisp think its a variable? Ex:

>(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
 (2 4 6 8 10)
Community
  • 1
  • 1
Andy
  • 10,553
  • 21
  • 75
  • 125

2 Answers2

4

Some lisps, like Common Lisp, require this. Others, like Scheme, do not.

You need to do this because the Lisp you're using has a separate namespace for functions versus "normal" variables. If you left out the #' then the symbol evenp would be interpreted as referring to the "normal" (non-function) namespace.

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • Thanks for the quick response. I did not know lisp separated it this way, at least in common lisp. Much appreciated. – Andy Mar 07 '12 at 04:03
3

The read syntax

#'X

means exactly the same thing as

(FUNCTION X)

(FUNCTION X) means, roughly, "resolve the symbol X in the namespace of functions". Without this, X is evaluated as a variable. Functions and variables are in separate namespaces in Common Lisp. This is a rule.

As to the question, why would Lisp think it is a variable? Let's put it another way: given that there are two namespaces, why can't Lisp just fall back automatically on one or the other if there is no ambiguity? The reason is that that would be a hack compared to just Lisp-1 or Lisp-2, worse than either of them. Lisp-1 and Lisp-2 are words used in the Lisp culture to refer to dialects that have one a single namespace for variables and those that have two.

If you want to know more about the pros and cons of doing it one way or another, it's all in this paper by Kent Pitman and Richard Gabriel: http://www.nhplace.com/kent/Papers/Technical-Issues.html [Technical Issues of Separation in Function Cells and Value Cell].

As an aside: you can use 'FUNC or (QUOTE FUNC) instead: (remove-if-not 'evenp ...). This is a very late binding mechanism that goes through the symbol, and will not work for lexical functions. It probably won't compile very efficiently. Calling through 'FUNC always has to do a lookup through the symbol, whereas #'FUNC (at least in some important situations) can be optimized.

Kaz
  • 55,781
  • 9
  • 100
  • 149
  • Thanks for the response. And the example is from the book I am using, so I wouldn't be using it in my code, but I appreciate the advice. – Andy Mar 07 '12 at 04:05