Continued Walkthrough Style in General Lisp?

In an attempt to find a simple CPS example that does not give me a headache, I came across this scheme code (manual printing), so parens may not match):

(define fact-cps
    (lambda(n k)
        (cond
            ((zero? n) (k 1))
            (else
                (fact-cps (- n 1)
                          (lambda(v)
                             (k (* v n))))))))
(define fact
    (lambda(n)
        (fact-cps n (lambda(v)v))))  ;; (for giggles try (lambda(v)(* v 2)))

(fact 5) => 120

Great, but Scheme is not Common Lisp, so I took a snapshot:

(defun not-factorial-cps(n k v)
    (declare (notinline not-factorial-cps)) ;; needed in clisp to show the trace
    (cond
        ((zerop n) (k v))
        ((not-factorial-cps (1- n) ((lambda()(setq v (k (* v n))))) v))))
       ;; so not that simple...
(defun factorial(n)
    (not-factorial-cps n (lambda(v)v) 1))

(setf (symbol-function 'k) (lambda(v)v))

(factorial 5) => 120

, , , , . , , , - . , , : v? -? , , ? / Common Lisp ? .

+4
1

, , , . Common Lisp:

(defun fact-cps (n &optional (k #'values))
  (if (zerop n) 
      (funcall k 1)
      (fact-cps (- n 1)
                (lambda (v)
                  (funcall k (* v n))))))

(fact-cps 10) ; ==> 3628800

, if, , . funcall - LISP -2 Common Lisp Scheme.

-, CPS:

(defun fmapcar (fun lst &optional (k #'values))
  (if (not lst)
      (funcall k lst)
      (let ((r (funcall fun (car lst))))
        (fmapcar fun
                 (cdr lst)
                 (lambda (x)
                   (funcall k (cons r x)))))))

(fmapcar #'fact-cps '(0 1 2 3 4 5)) ; ==>  (1 1 2 6 24 120)

v ?

, , v. fmapcar, (fmapcar #'list '(1 2 3)),

;; base case calls the stacked lambdas with NIL as argument
((lambda (x) ; third iteration
   ((lambda (x) ; second iteration 
      ((lambda (x) ; first iteration
         (values (cons (list 1) x)))
       (cons (list 2) x)))
    (cons (list 3) x))
   NIL)

, - , , , . , , , . , , .

-? , , ?

(), , -cps n k, . , , flet labels , -. , .

/ Lisp ?

, . funcall, apply. .

+7

Source: https://habr.com/ru/post/1535193/


All Articles