Page 1 of 1

Function (operator) as function parameter: how?

Posted: Wed Dec 26, 2012 5:59 am
by mugmug
Hello,

This newbie is stuck on a problem and hopes any one can give him a hint.
Having used Scheme somewhere in history, I am trying to use Lisp now.

I am stuck on how to do the following Scheme statement in Lisp:

( (lambda (FN) ( FN '( PB PC )))
(lambda (varx) (cons 'PA varx)))
The result is:
(pa pb pc)
the first function takes a function as parameter, which it invokes with a list as argument.

In Lisp I should, I think, quote the second function, like

( (lambda (FN) ( FN '( PB PC ))) '(lambda (varx) (cons 'PA varx)))

But this does not work. I have tried variations with funcall, function # etc, but nothing seems to help.

What is the way to do this in Common Lisp (emacs+cl or CMUcl)?

Greets
JW

Re: Function (operator) as function parameter: how?

Posted: Wed Dec 26, 2012 1:16 pm
by Goheeca
I suppose you mean Common Lisp by Lisp.
Because CL is Lisp-2, it evaluates the function position in other way than argument positions so you can't place lambda in a first position. CL has a function which takes a function and arguments and applies them on that: funcall
The code looks:

Code: Select all

(funcall (lambda (fn) (funcall fn '(pb pc))) (lambda (varx) (cons 'pa varx)))
Lisp-2 dialects has two namespaces for variables -- for values and for functions, therefore if you want to apply the + function you must use a special operator function:

Code: Select all

(funcall (function +) 10 10)
which can be abbreviated to:

Code: Select all

(funcall #'+ 10 10)
otherwise it'd look up in the value namespace ... where can be a function, too.
An example:

Code: Select all

(defun fn (a b) (+ a b))
(defvar fn (lambda (a b) (* a b)))
(funcall fn 2 3) ; result = 6
(funcall #'fn 2 3) ; result = 5

Re: Function (operator) as function parameter: how?

Posted: Thu Dec 27, 2012 2:54 pm
by mugmug
thank you !

I must have tried funcall at the wrong place.
There are Lisp-1 interpreters, I now know. I tried eulisp, but it did not even compile on my system.
Well, I ll be fine with the funcalls like in your example, for now.

cheers

Re: Function (operator) as function parameter: how?

Posted: Thu Dec 27, 2012 3:34 pm
by nuntius
If you want a lisp-1, try Racket (a descendent of, and some might say heir apparent to Scheme).

Re: Function (operator) as function parameter: how?

Posted: Sat Dec 29, 2012 8:46 am
by marcoxa
Please note that if you have a LAMBDA, you do not need FUNCALL

Code: Select all

((lambda (x) (+ x 42)) -42) ==> 0

Re: Function (operator) as function parameter: how?

Posted: Sat Dec 29, 2012 9:19 am
by Goheeca
Yeah, that's true, but it's important to understand in which namespace the lambda is and I wanted to avoid a confusion of OP.
In CL I even get used to approach to lambdas just like to any other functions so I originally wanted to write down something in this sense:

Code: Select all

(funcall #'(lambda (x) (1+ x)) 0)