This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Problem with lambda

3 posts · 830 views

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:
(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.

Re: Problem with lambda

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:
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.

Re: Problem with lambda

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.