【问题标题】:In list, how can I make modifications to a list through a function which takes the list as a parameter?在列表中,如何通过将列表作为参数的函数对列表进行修改?
【发布时间】:2013-01-21 02:31:15
【问题描述】:

我正在用 Lisp 编写一个程序,将两个列表中的公共元素放入一个新列表中。这是我的代码。

(defun test (a b)
  (let ((alist nil) (blist nil))
    (progn
      (join a b alist blist)
      (print blist))))

(defun join (a b alist blist)
  (cond
   ((and (null a) (null b))
    (setf blist (cons alist blist)))
   ((equal (car a) (car b))
    (setf alist (cons (list (car a) (car b)) alist)))
   (t (join (cdr a) (cdr b) alist blist))))

但是函数的输出总是nil。然后我在网上查了一些东西,发现当我尝试使用setf时,它不再指向原始列表,而是指向一个新列表。那么如果我不能使用setf,我还能用什么来实现呢?

【问题讨论】:

  • 我不确定你的函数到底应该做什么。您是否希望您的结果包含两个输入列表中相同位置的元素,或者您是否想要某种交集?如果是后者,那么重复呢?
  • 我同意 daniel 的观点 - 这是一个令人困惑的功能。你能举一些函数调用和预期输出的例子吗?另外,如果函数将两个列表连接在一起,为什么它需要四个参数?
  • 你应该始终使用正确的缩进 Lisp 代码。

标签: list lisp common-lisp pass-by-value


【解决方案1】:

不要在 Lisp 中使用“输出”参数。更好地从函数返回结果。 此外,CL 中有一个函数“intersection”可以满足您的需求,因此请使用它,除非它是一个练习(然后您可以查看它的实现)。

【讨论】:

    【解决方案2】:
    (defun test (a b)
      (let ((alist nil) (blist nil))   ; two variables initialized to NIL
        (progn                         ; this PROGN is not needed
          (join a b alist blist)       ; you call a function, but ignore the
                                       ; return value? Why?
          (print blist))))             ; since blist was never modified, this
                                       ; can only be the initial value, NIL
    
    
    
    (defun join (a b alist blist)      ; four new local variables
      (cond
       ((and (null a) (null b))
        (setf blist (cons alist blist)))    ; why do you set the variable BLIST?
                                            ; you never use it later
    
       ((equal (car a) (car b))
        (setf alist (cons (list (car a) (car b)) alist)))
                                            ; why do you set the variable ALIST?
                                            ; you never use it later
    
       (t (join (cdr a) (cdr b) alist blist))))
                                            ; the only recursive call of JOIN
    

    您只能更改词法可访问的变量。

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 1970-01-01
      • 2016-06-09
      • 2020-07-14
      • 1970-01-01
      • 2018-08-29
      • 2021-11-03
      • 1970-01-01
      相关资源
      最近更新 更多