开发者

How to define inner function in a function?

开发者 https://www.devze.com 2023-04-04 18:55 出处:网络
(defun div618 (p1 p2) \"golden split\" (let ((ratio \'(0. 0.191 0.236 0.382 0.5 0.618 0.809 1.)) (price (lambda (r) (if (<= p1 p2) (+ p1 (* (- p2 p1) r)) (- p1 (* (- p1 p2) r))))))
(defun div618 (p1 p2)
"golden split"
    (let ((ratio '(0. 0.191 0.236 0.382 0.5 0.618 0.809 1.))
          (price (lambda (r) (if (<= p1 p2) (+ p1 (* (- p2 p1) r)) (- p1 (* (- p1 p2) r))))))
         (if (<= p1 p2)
             (dolist (r (reverse ratio)) (format t "-------~d   ~d-------~%" r (price r)))
             (dolist (r ratio) (format t "-------~d  ~d-------~%" r (price r))))))

(div618 1600 6000)

 *** - EVAL: undefined function PRICE
 The following restarts are available:
 USE-VALUE      :R1      Input a value to be used instead of (FDEFINITION 'PRICE).
 RETRY          :R2      Retry
 STORE-VALUE    :R3      Input a new value for (FDEFINITION 'PRICE).
 ABORT          :R4      Abort main loop

Why cannot 开发者_StackOverflowthe inner function "price" be used ?

Sincerely!


Common Lisp has different namespaces for function and variable bindings; this page explains it in some detail: http://cl-cookbook.sourceforge.net/functions.html. I think what you want to try is something like:

(defun div618 (p1 p2)
"golden split"
    (let ((ratio '(0. 0.191 0.236 0.382 0.5 0.618 0.809 1.))
          (price (function (lambda (r) (if (<= p1 p2) (+ p1 (* (- p2 p1) r)) (- p1 (* (- p1 p2) r)))))))
         (if (<= p1 p2)
             (dolist (r (reverse ratio)) (format t "-------~d   ~d-------~%" r (funcall price r)))
             (dolist (r ratio) (format t "-------~d  ~d-------~%" r (funcall price r))))))

Untested!

0

精彩评论

暂无评论...
验证码 换一张
取 消