【问题标题】:LISP - atom after every occurrence of search atomLISP - 每次出现搜索原子后的原子
【发布时间】:2018-01-07 04:59:10
【问题描述】:

我正在尝试在列表中的搜索原子之后添加一个新原子。

当我尝试递归调用函数 appendConst 时,我收到以下错误 -

[1]> (defun appendConst (OLD NEW L)
       (cond
         ((null L) ())
         ((EQ (car L) OLD) (appendConst (cons OLD (cons NEW (cdr L))))  )
         (T (cons (car L) (appendConst OLD NEW (cdr L))))
    ))
APPENDCONST
[2]> (appendConst 'a 'd '(a c d e a m k))

*** - EVAL/APPLY: Too few arguments (1 instead of at least 3) given to APPENDCONST
The following restarts are available:
ABORT          :R1      Abort main loop
Break 1 [3]> 

在这里,使用我的输入,在每次出现“a”之后,我想在给定的整个列表中添加一个“d”。

我是新手,如何在这里递归调用函数?

TIA。

【问题讨论】:

    标签: lisp elisp


    【解决方案1】:

    您的第一个递归调用(在其中添加NEW)实际上只有一个参数,即错误所说的。仅仅添加缺少的OLDNEW 是行不通的,因为递归调用会再次找到OLD。因此,只需像在其他情况下一样在通话之外进行consing:

    (cons OLD (cons NEW (appendConst OLD NEW (cdr L))))
    

    请注意,这两种情况都不是尾递归的:为避免堆栈使用与列表长度成正比,您必须就地修改列表或执行更复杂的操作,例如传递新列表的头部和尾部递归时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多