Please forgive the "newbie" nature of my question. I'm familiar with the
lambda calculus as used in formal semantics, and I've just downloaded gcl and
started to poke around.
I'd like to see how Lisp would implement the "swap" operator, which accepts a
function and returns the same function with the first two argument positions
reversed. Ideally, I would have:
>((swap -) 5 3)-2
Generally, I want ((swap f) a b) to equal (f b a). So far, the best I've done
is as follows:
>(defun swap (f) `(lambda (arg0 &rest l) (apply ,f (car l) arg0 (cdr l))))SWAP
>(swap '#'-) (LAMBDA (ARG0 &REST L) (APPLY #'- (CAR L) ARG0 (CDR L)))
>(eval (list (swap '#'-) 100 10))-90
How can I elegantly avoid eval and list?
Thanks.
-John
--
==================================================================
John E. Tobey - "Happily hacking CGI since 1996"
······@user1.channel1.com
Daytime: ······@rmv.state.ma.us
http://www.channel1.com/users/jtobey/index.html
In article <·············@user1.channel1.com>, John Tobey
<······@user1.channel1.com> wrote:
How can I elegantly avoid eval and list?
You may have some objection to the semantics, but I would dispense with a
level of parens:
(defun swap (f x y) (funcall f y x))
You would call
(swap #'- 100 10)
--
cordially,
timothy larkin
····@cornell.edu
"The mind is not a vessel to be filled, but a
fire to be lighted."
Plutarch
John Tobey <······@user1.channel1.com> writes:
>I'd like to see how Lisp would implement the "swap" operator, which accepts a
>function and returns the same function with the first two argument positions
>reversed. Ideally, I would have:
>>((swap -) 5 3)-2
>Generally, I want ((swap f) a b) to equal (f b a). So far, the best I've done
>is as follows:
Here it is in Scheme:
(define swap
(lambda (f)
(lambda (x y)
(f y x))))
It works exactly the way you want. The difference between Lisp and Scheme
here is that Scheme uses a single name space for functions and variables,
which Lisp has separate name spaces. In Lisp, you'd need
(defun swap (f)
#'(lambda (x y) (funcall f y x)))
and you would have to call it as
(funcall (swap #'-) 5 3)
That's the only real difference.
--
Fifty years of programming language research, and we end up with C++ ???
Richard A. O'Keefe; http://www.cs.rmit.edu.au/~ok; RMIT Comp.Sci.