【问题标题】:How to write recursive function and print it in Lisp如何编写递归函数并在 Lisp 中打印
【发布时间】:2023-03-28 18:32:01
【问题描述】:

我有一个函数应该接受任何列表,然后像这样打印它(例如):

输入列表:(A B C)

输出:(A B C) (A) (B) (C)

那是原始列表后面跟着每个元素在它自己的列表中。函数应该写成递归函数。

我有以下伪代码,我无法正确处理,无法转换为递归:

Assuming input (A B C)

Function input (list)

  Cons newlist '(list) //newlist = (A B C)

  newlist append (car list) //car returns A

  pop list//remove firstElement

  newlist append (car list)//car returns B

  Pop list

  newlist append (car list)//car returns C

  pop list

  Print newlist.

这里的问题是,使用 Append,我会得到 (A B C A B C)。有没有其他方法可以将它分成各自的括号并递归?

【问题讨论】:

  • @kuroineko 这还有帮助吗?
  • 你想要的输出是什么? (A B C (A) (B) (C))((A B C) (A) (B) (C))?
  • @LePetitPrince 第二个
  • 请记住在以后的问题中添加common-lisp 标签。

标签: lisp common-lisp


【解决方案1】:

你可以这样做:

(defun f (lst)
  (labels 
      ((g (lst)
         (when lst
           (cons (list (car lst)) (g (cdr lst))))))
    (cons lst (g lst))))

其中外部函数 f 使用内部递归函数 g 并预先添加初始列表。

? (f '(A B C))
((A B C) (A) (B) (C))

基本上gmapcar 相同,因此,如果您不必递归执行,则可以改为:

(defun f (lst)
  (cons lst (mapcar #'list lst)))

【讨论】:

    【解决方案2】:

    这是你的逃生穿梭机,西格妮 :)

    (使用老式 GNU 通用 LISP windows 构建进行测试 - 我不得不手动重新键入会话,因为在编译这个东西时,复制粘贴仍然是一个科幻概念)

    >>(defun explode_list (input)
       (if (null input)
        nil                            ; list termination
        (cons 
          (list (first input))         ; create singleton list with first element 
          (explode_list (rest input))  ; concatenate with the rest of the list
      )))
    
    EXPLODE_LIST
    
    >> (explode_list '(a b c))
    
    ((A)(B)(C))
    
    >>(defun do_weird_thing_with_a_list (l) (cons l (explode_list l)))
    
    DO_WEIRD_THING_WITH_A_LIST
    
    >> (do_weird_thing_with_a_list '(a b c))
    
    ((A B C) (A) (B) (C))
    

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多