LINUX.ORG.RU

История изменений

Исправление saufesma, (текущая версия) :

Тут такое дело, мне с Lispworks support обзор наших с тобой кодов пришел, не лестный

I think the style used in your sum-list and labels-sum-list examples is not good because it mixes side-effects (i.e. setq) with recursion for no good reason. The cleaner, standard way to do this is to add on return from the recursive step:

(defun sum-list-1 (lst)
  (if (eq (car lst) nil)
      0
    (+ (car lst) (sum-list-1 (cdr lst)))))

or pass the sum as an extra argument:

(defun sum-list-2 (lst &optional (n 0))
  (if (eq (car lst) nil)
      n
    (sum-list-2 (cdr lst) (+ (car lst) n))))

а это наша версия

(defvar *result*)
 (setq *result* 0)
 (defun sum-list (lst)
   (if (eq (car lst) nil)
       *result*
     (progn
       (setq *result* (+ *result* (car lst)))
       (sum-list (cdr lst)))))
 
 (sum-list '(1 2 3 4 5)) => 15

 ;; I rewrite the above code using labels.
 
 (defun labels-sum-list (lst &optional (n 0))
   (labels ((temp (lst)
              (if (null (car lst))
                  n
                  (progn
                    (setq n (+ n (car lst)))
                    (temp (cdr lst))))))
     (temp lst)))

Вот видишь век живи век учись, я вот так переписал

(defun labels-sum-list (lst &optional (n 0))
   (labels ((temp (lst n)
              (if (null (car lst))
                  n
                  (progn
                    (temp (cdr lst) (+ n (car lst)))))))
     (temp lst n)))

(labels-sum-list '(1 2 3 4 5) 0)

Исходная версия saufesma, :

Тут такое дело, мне с Lispworks support обзор наших с тобой кодов пришел, не лестный

I think the style used in your sum-list and labels-sum-list examples is not good because it mixes side-effects (i.e. setq) with recursion for no good reason. The cleaner, standard way to do this is to add on return from the recursive step:

(defun sum-list-1 (lst)
  (if (eq (car lst) nil)
      0
    (+ (car lst) (sum-list-1 (cdr lst)))))

or pass the sum as an extra argument:

(defun sum-list-2 (lst &optional (n 0))
  (if (eq (car lst) nil)
      n
    (sum-list-2 (cdr lst) (+ (car lst) n))))

а это наша версия

(defvar *result*)
 (setq *result* 0)
 (defun sum-list (lst)
   (if (eq (car lst) nil)
       *result*
     (progn
       (setq *result* (+ *result* (car lst)))
       (sum-list (cdr lst)))))
 
 (sum-list '(1 2 3 4 5)) => 15

 ;; I rewrite the above code using labels.
 
 (defun labels-sum-list (lst &optional (n 0))
   (labels ((temp (lst)
              (if (null (car lst))
                  n
                  (progn
                    (setq n (+ n (car lst)))
                    (temp (cdr lst))))))
     (temp lst)))