Next: Types, Previous: Iteration, Up: Welcome to Lisp [Contents][Index]
In Lisp, functions are regular objects, like symbols or strings or lists. If
we give the name of a function to function
, it will return the associated
object. Like quote
, function
is a special operator, se we don’t have to
quote the argument:
> (function +) #<Compiled-Function + 17BA4E>
Until now we have only dealt with objects that look the same when Lisp displays them as when we typed them in. This convention does not apply to functions. Internally, a built-in function like ‘+’ is likely to be a segment of machine code. A Common Lisp implementation may choose whatever external representation it likes.
Just as we can use ‘’’ as an abbreviation for quote
, we can use ‘#’’ as an
abbreviation for function
:
> #’+ #<Compiled-Function + 17BA4E>
This abbreviation is known as shart-quote.
Like any other kind of object, we can pass functions as arguments. One
function that takes a function as an argument is apply
. It takes a function
and a list of arguments for it, and returns the result of applying the function
to the arguments:
> (apply #’+ ’(1 2 3)) 6 > (+ 1 2 3) 6
It can be given any number of arguments, so long as the last is a list:
> (apply #’+ 1 2 ’(3 4 5)) 15
The function funcall
does the same thing but does not need the arguments to
be packaged in a list:
> (funcall #’+ 1 2 3) 6
The defun
macro creates a function and gives it a name. But functions don’t
have to have names, and we don’t need defun
to define them. We can refer to
functions literally. To refer literally to a function, we use what’s called a
lambda expression. A lambda expression is a list containing the symbol
lambda
, followed by a list of parameters, followed by a body of zero or
more expressions.
Here is a lambda expression representing a function that takes two numbers and returns their sum:
(lambda (x y) (+ x y))
Like an ordinary function name, a lambda expression can be the first element of a function call,
> ((lambda (x) (+ x 100)) 1) 101
and by affixing a sharp-quote to a lambda expression, we get the corresponding function,
> (funcall #’(lambda (x) (+ x 100)) 1) 101
Next: Types, Previous: Iteration, Up: Welcome to Lisp [Contents][Index]