局部变量使数据不被先前执行 [英] Local variable keeps data from previous execution

查看:99
本文介绍了局部变量使数据不被先前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,即使(我相信)我仅在每个函数中使用局部变量,但多次运行后的结果似乎仍将数据保留在变量中,最终会添加旧的&新结果。

 (defun funcC(target res)
(cond
((null res) (列出(列出目标1)))
((相等(汽车(汽车))目标)
(setf(cadr(汽车))(+(cadr(汽车))1)))
res)
(t(setf(cdr res)(funcC目标(cdr res)))res)
))
(defun funcB(l res)
(cond((null l)nil)
((atom l)(funcC l res))
((atom(car l))
(funcB(car l)res)
(funcB(cdr l)res))
((listp(car l))(funcB(car l)res))
(t(funcB(cdr l)res)))
res

(defun funcA(l)
(cdr(funcB l'((())))

结果:

 断裂27 [30]> ; lb 
(10 7 7 7 4 3 7 3 10 10)
突破27 [30] (funcA lb)
((10 3)(7 4)(4 1)(3 2));我希望该结果在下一次运行中重复,但是...
打破27 [30]> (funcA lb)
((10 6)(7 8)(4 2)(3 4))
打破27 [30] (funcA lb)
((10 9)(7 12)(4 3)(3 6));每次运行总计前一次运行的结果

环境:Ubuntu 11.10,GNU CLISP 2.49

解决方案

这是一个常见问题。在堆栈溢出上应该有这个问题的副本(很简单!)。



您的 funcA 包含文字数据。该数据每次都会传递到 funcB 并在那里进行修改。



您应该为该数据制作一个新副本。每次运行。使用 COPY-TREE



还请注意,根据Common Lisp标准,修改文字数据可能会带来不确定的后果。例如,假设有一个将所有文字数据放入只读数据存储段的编译器,或者想象一个在多个地方重用相似文字数据以节省空间的编译器。


ith the code below, even though (I believe) I'm only using local variables in each function, the result after running multiple times looks like data remain in variables and it ends up adding old & new result. What is wrong?

(defun funcC (target res)
  (cond
   ((null res) (list (list target 1)))
   ((equal (car (car res)) target)
    (setf (cadr (car res)) (+ (cadr (car res)) 1))
    res)
   (t (setf (cdr res) (funcC target (cdr res))) res)
  ))
(defun funcB (l res)
  (cond ((null l) nil)
    ((atom l) (funcC l res))
    ((atom (car l)) 
     (funcB (car l) res)
     (funcB (cdr l) res))
    ((listp (car l)) (funcB (car l) res))
    (t (funcB (cdr l) res)))
  res
)
(defun funcA (l)
  (cdr (funcB l '(())))
)

Result:

Break 27 [30]> lb
(10 7 7 7 4 3 7 3 10 10)
Break 27 [30]> (funcA lb)
((10 3) (7 4) (4 1) (3 2))   ; I want this result to repeat in the next run but...
Break 27 [30]> (funcA lb)
((10 6) (7 8) (4 2) (3 4))   
Break 27 [30]> (funcA lb)
((10 9) (7 12) (4 3) (3 6))  ; Each run adds up to results from previous run

Environment: Ubuntu 11.10, GNU CLISP 2.49

解决方案

That's a frequently asked question. There should be copies (sic!) of this question on stackoverflow.

Your funcA contains literal data. This data is passed every time to funcB and modified there.

You should make a fresh copy of that data for each run. Use COPY-TREE.

Note also that modifying literal data might have undefined consequences according to the Common Lisp standard. Imagine for example a compiler which puts all literal data in read-only data memory segments or imagine a compiler which reuses similar literal data in several places to save space.

这篇关于局部变量使数据不被先前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆