0

作业问题:

(diginlist '(4 5 3 2 8))应该返回(4(5(3)2)8)

(define(removelast L)
  (if(null?(cdr L)) '()
     (cons(car L) removelast(cdr L))))

(define(last L) (if(null?(cdr L)) (car L) (last(cdr L))))

(define(diginlist L)
  (cond((null? L) '())
       ((list?(car L)) ((diginlist(car L))
                           (list(diginlist(cdr L)))))
       (else(append(list(diginlist(cdr L)))))))

(diginlist '(4 5 3 2 8))

返回:

(list (list (list (list (list '())))))

我知道我应该合并 removelast 和 last,但我在这样做时遇到了麻烦。

4

1 回答 1

0

你必须学会​​递归思考。给定问题 P 的一个实例,目标是构建一个较小的问题 R 实例,以便可以轻松地“扩充” R 的解决方案以构建 P 的解决方案。

一旦以这种方式分解问题,您就可以通过递归调用解决 P 的相同过程来解决 R。

在这种情况下, P 是要“列出” (4 5 3 2 8)。那么什么是R?好吧,如果我们可以列出(5 3 2)来获取(5 (3) 2),那么我们的状态就会很好。我们只需要通过使其成为 3 元素列表中的第二个元素来扩充此解决方案,其中第一个元素是 4,最后一个元素是 8。

基本情况是输入为空或只有一个元素。在这些情况下,我们希望返回输入。

把它放在一起作为伪代码:

 function listify (lst)
   if lst has 0 or 1 elements, return lst
   otherwise
     split lst into 3 parts:
       F = first element of lst
       M = a copy of lst except with first and last elements omitted
       L = last element of lst
     return a list of 3 elements: (F (listify M) L)

现在在 Scheme 中表达这一点。你已经完成了一些。

于 2018-04-09T01:05:28.303 回答