on function...

Discussion of Common Lisp
Post Reply
megera
Posts: 30
Joined: Wed Oct 10, 2012 1:34 pm

on function...

Post by megera » Sat Nov 10, 2012 10:44 am

HI
It seems that I still have some doubt on ‘function’ operator..
For example some code that I’m learning on the book (and also on the web)use it with lambda:

In compose definition:

Code: Select all

(defun compose (&rest fns)
      (destructuring-bind (fnl . rest) (reverse fns)
          #'(lambda (&rest args)
                 (reduce #'(lambda (v f) (funcall f v))
                    rest  :initial-value (apply fnl args)))))

but that code works also without function in front of lambda …of course CL interpreter to know that lambda is a function and not a variable…
it’s the same also for reduce, apply, setf,..ecc
Have I misunderstood something? (maybe yes.... :? )
Thanks in AV

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: on function...

Post by ramarren » Sat Nov 10, 2012 10:53 am

LAMBDA is a macro that expands into (FUNCTION (LAMBDA ...)), so in CL they are equivalent.

In some other contexts, like with many standard higher order functions, you can use both (FUNCTION function-name) (or #'function-name syntax) and (QUOTE function-name) (or 'function-name syntax), but they behave differently. The former retrieves the function at read time from lexical bindings function space, whereas the latter at runtime by name from dynamic bindings function space. It manifests when, for example, using lexical function bindings:

Code: Select all

CL-USER> (defun test () 'test)
TEST
CL-USER> (test)
TEST
CL-USER> (funcall #'test)
TEST
CL-USER> (funcall 'test)
TEST
CL-USER> (flet ((test () 'test2)) (funcall 'test))
TEST
CL-USER> (flet ((test () 'test2)) (funcall #'test))
TEST2

megera
Posts: 30
Joined: Wed Oct 10, 2012 1:34 pm

Re: on function...

Post by megera » Sat Nov 10, 2012 12:02 pm

Thank Ramarren for explanation !! ;)

Post Reply