Problem with lambda

Discussion of Common Lisp
Post Reply
wilku
Posts: 2
Joined: Mon May 24, 2010 2:30 pm

Problem with lambda

Post by wilku » Mon May 24, 2010 2:52 pm

Hi

I'm trying to learn common lisp "by example" out of some course based on scheme. Here's my adaptation of the classic Newton algorithm to find square roots:

Code: Select all

(defun fixed-point (f start)
  (defvar tolerance 0.00001)
  (labels ((close-enough? (u v)
             (< (abs (- u v)) tolerance))
            (iter (old new)
              (if (close-enough? old new)
                new
                (iter new (funcall f new)))))
  (iter start (funcall f start))))
  
(defvar dx 0.00001)
(defun deriv (f)
               #'(lambda (x) (/ (- (funcall f (+ x dx)) 
                                  (funcall f x)) 
                               dx)))

(defun newton (f guess)
  (labels ((df () (deriv f)))
    (fixed-point 
      #'(lambda (x) (- x (/ (funcall f x) ((df) x)))) 
      guess)))

(defun mysqrt-newton (x)
  (labels ((square (x) (* x x)))
    (newton #'(lambda (y) (- x (square y))) 1))) 

(mysqrt-newton 2)
The problem is with expression ((df) x) - it is supposed to return the value of a derivative of f in x. (df) should return a function being derivative of f. Apparently it doesn't because I get an error: SYSTEM::EPAND-FORM (DF) should be a lambda expression. But it is, isn't it?

Please help.

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Problem with lambda

Post by gugamilare » Mon May 24, 2010 5:41 pm

wilku wrote:The problem is with expression ((df) x) - it is supposed to return the value of a derivative of f in x. (df) should return a function being derivative of f. Apparently it doesn't because I get an error: SYSTEM::EPAND-FORM (DF) should be a lambda expression. But it is, isn't it?
No, it isn't a lambda expression, but it evaluates to a lambda expression. You have to use funcall: (funcall (df) x).

In CL, the first element in a form must be either a symbol (naming a function or a macro) or an explicit lambda expression, like:

Code: Select all

cl-user> ((lambda (x) (+ x 1)) 2)
3
This you don't need anyway, you already have let.

Unlike Scheme, Common Lisp separates variable and function namespaces. In this case, I would say it loses to Scheme.

wilku
Posts: 2
Joined: Mon May 24, 2010 2:30 pm

Re: Problem with lambda

Post by wilku » Tue May 25, 2010 12:38 pm

It took me 15 more minutes to understand this even though you explained it very clearly.
This says something about the level of abstraction of higher functions :) (or my intelectual abilities :P )
Thank you for the answer.

Post Reply