help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Functions returning functions in Emacs Lisp


From: Barry Margolin
Subject: Re: Functions returning functions in Emacs Lisp
Date: Wed, 16 Apr 2008 00:33:49 -0400
User-agent: MT-NewsWatcher/3.5.3b2 (Intel Mac OS X)

In article 
<c98a949b-5ada-490a-805f-298e84783e01@l28g2000prd.googlegroups.com>,
 srinik001@hotmail.com wrote:

> Hi,
> 
> I am trying to learn Emacs Lisp. I know a bit of (Common) Lisp and was
> trying the following on Emacs. This is to define a function called
> derivative, which returns as its result a function which is the
> derivative of the argument function fn, when the numerical calculation
> is done over delta. So I did the following.
> 
> (defun derivative (fn delta)
>   #'(lambda(x) (/ (- (funcall fn (+ x delta)) (funcall fn x)) delta)))
> 
> --> this seemed to work (i.e. no error on C-x C-e)
> 
> (setq c (derivative #'sin 0.001))
> 
> --> this seemed to work (again, no error on evaluation)
> 
> (funcall c (/ 3.1415 2))
> 
> --> this threw up an error. The error is the following:
> 
> Debugger entered--Lisp error: (void-variable fn)
>   (funcall fn (+ x delta))
>   (- (funcall fn (+ x delta)) (funcall fn x))
>   (/ (- (funcall fn ...) (funcall fn x)) delta)
>   (lambda (x) (/ (- ... ...) delta))(1.57075)
>   funcall((lambda (x) (/ (- ... ...) delta)) 1.57075)
>   eval((funcall c (/ 3.1415 2)))
>   eval-last-sexp-1(nil)
>   eval-last-sexp(nil)
>   call-interactively(eval-last-sexp)
> 
> I tried lambda expressions on mapcar, and it seemed to work on Emacs
> the way it does in Common Lisp. Could someone please tell me if I am
> doing something wrong vis-a-vis Emacs, or if Emacs does not support
> this? Thanks.

Emacs Lisp uses dynamic scoping, not lexical scoping, so it doesn't 
create lexical closures.

You can get the effect using lexical-let:

(defun derivative (fn delta)
  (lexical-let ((fn fn) (delta delta))
     #'(lambda (x) (/ (- (funcall fn (+ x delta))
                         (funcall fn x))
                      delta))))

-- 
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***


reply via email to

[Prev in Thread] Current Thread [Next in Thread]