本文介绍了Lisp 中的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 lisp 中创建子列表时遇到问题.我的任务是编写一个函数,该函数接受一个列表和两个索引 from 和 to,并返回sublist".其元素是 from 和 to 索引中的元素.我只被允许使用功能 cdr、car、cons、list 和 append.下面是代码输出的示例.

Im having trouble creating a sublist in lisp. My task is to write a function that takes a list and two indexes from and to, and returns "sublist" whose elements are the elements within from and to indexes. I am only allowed to use the functions cdr, car, cons, list and append. Here is an example of how the output of the code should look like.

子列表 '(1 6 12) 2 3)输出:(6 12)

sublist '(1 6 12) 2 3)output: (6 12)

推荐答案

提示:

(sublist '(1 6 12 15) 2 3)

结果与

(sublist '(6 12 15) 1 2)

当开始索引达到1时,可以在consing元素的同时检查end的值;也要小心空列表.前面的表达式可以改写:

When you reach 1 for start index, you can check the value of end while consing elements; be careful with empty lists too. The previous expression can be rewritten:

(cons 6 (sublist '(12 15) 1 1))

(cons 6 (cons 12 (sublist '(15) 1 0)))

终于

(cons 6 (cons 12 nil))

更准确地说,这是执行的痕迹:

More precisely, here is a trace of execution:

USER> (sub '(1 2 3 4 5) 2 4)
  0: (SUB (1 2 3 4 5) 2 4)
    1: (SUB (2 3 4 5) 1 3)
      2: (SUB (3 4 5) 1 2)
        3: (SUB (4 5) 1 1)
          4: (SUB (5) 1 0)
          4: SUB returned NIL
        3: SUB returned (4)
      2: SUB returned (3 4)
    1: SUB returned (2 3 4)
  0: SUB returned (2 3 4)
(2 3 4)

这篇关于Lisp 中的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:48