首页 > 解决方案 > 方案难以理解我的函数“连接列表”输出的输出

问题描述

我编写了一个名为“my-append”的函数,它接受两个列表 L1、L2 并将 L2 的每个元素附加到 L1 的末尾。(换句话说,它将 L1 与 L2 连接起来)

该功能似乎表现正确,但是我似乎得到了一个奇怪的输出。

(my-append '(a b '(1 2 3)) (list '(4 5 6) 7 8 9)) ==>

(list 'a 'b (list 'quote (list 1 2 3)) (list 4 5 6) 7 8 9)

我是新来的计划,不知道这是正确的还是现在。请注意,我在 dr Racket 中使用高级学生语言。这是该函数的代码。(它使用两个辅助函数)

;my-append
;takes two lists L1,L2 and returns concat of L2 to L1
;it first checks if either list is empty if so it returns the non empty one
;if both are empty returns empty
;if both are non empty determine which list has smaller length
;calls my-append-helper with first arg as smaller second larger
;append-element
;takes a list L and element x and adds x
; to the end of L
; I am super limited on which operations i can use
; so i must resort to this O(n) algorithm

;my-append-helper
;takes either two non empty lists L1 L2 then
;builds the concatenation of L1 L2
;by stripping of first element of L2
;and adding it to L1

(define (append-element L x)
  (cond ((equal? L '())    
         (list x) )          
        (else           
         (cons (first L)    
                (append-element (rest L) x)))))

(define my-append-helper
  (lambda (L1 L2)
    (cond ( (equal? '() L2)
            L1)
          (else (my-append-helper (append-element L1 (first L2)) (rest L2))))))

(define my-append
  (lambda (L1 L2)
    (cond ( (and (equal? L1 '()) (equal? L2 '()))
            '() )
          ( (equal? L1 '() )
            L2 )
          ( (equal? L2 '() )
            L1)
          ( else
            (my-append-helper L1 L2)))))

标签: schemeracketquote

解决方案


这算不算?

(define (myappend lst1 lst2)
  (cond
    ((null? lst2) lst1)
    (else (myappend (cons lst1 (cons (car lst2) '())) (cdr lst2)))))

这是一个迭代过程(而不是递归)。

请注意,如果

  1. 列表 2 为空,您可以简单地返回列表 1。
  2. 由于您的基本情况要求您返回 list1,因此只需使用基于不变量的证明,您将 list1 定义为不变量。

如果这不起作用,请告诉我,我会尝试帮助您调试代码。


推荐阅读