0

The original code I try to implement.. the output should be (1.4) (2.5) from my code.. I think you all know what I try to do....this is also tail recursion practice

my code
(define (myFunc lst1 lst2)
 (if (or (null? lst1) (null? lst2))       
    '()                                  
     (list (cons (car lst1) (car lst2))
        (myFunc (cdr lst1) (cdr lst2)))
  ))

after several of you gave me good advice about cons-pair.. so now it get's the dotted symbol in the middle.. then problem is that the improper list with empty list in the end.. when 2 input lists are like this ..... '(1 2 3 4) '(4 5 6)) my output is like this ; ((1 . 4) ((2 . 5) ((3 . 6) ()))) the empty list in the end of output shouldn't be there... so I couldn't understand about improper list , proper list....? is there are any document, I can look at?

4

2 回答 2

2

cons考虑和之间的区别list

缺点与列表

也就是说,(cons a b)创建一个其carisacdris的单元格b
(list a b)创建一个单元格,其caris a,但cdr是一个列表,并且该列表的 是car,而它是。bcdrnil

如果b是一个列表,那么左边的就是一个列表,b它的尾部是一个列表,并a在前面添加b
右边的也将是一个列表,但b它的第二个元素是它,而不是你想要的它的尾巴。

要修复您的程序,您只需将您的替换listcons.

但是您的函数不是尾递归的,因为它使用递归调用的结果来处理。

为了使其尾递归,一个好方法通常是创建一个具有累加器参数的辅助函数。

我可能会这样写:

(define (zip-cars l1 l2)
    (cons (car l1) (car l2)))

(define (zip-help l1 l2 result)
    (if (or (null? l1) (null? l2))
        result
        (zip-help (cdr l1) (cdr l2) (cons (zip-cars l1 l2) result))))

(define (zip l1 l2)
    (zip-help l1 l2 '()))
于 2014-05-13T09:52:17.187 回答
1

只需替换listcons. 然后您的代码将评估为 `(cons (cons (cons .... (cons ... '())) 并且您的列表将被正确终止。

(define (zip lst1 lst2)
  (if (or (null? lst1) (null? lst2))       
      '()                                  
      (cons (cons (car lst1) (car lst2))
            (zip (cdr lst1) (cdr lst2)))))

然后

(zip '(1 2 3 4) '(4 5 6))
=> '((1 . 4) (2 . 5) (3 . 6))

但是,这不是尾递归的,因为在从zipconsing 返回之后仍然必须完成。

编辑

尾递归版本的示例:

(define (zip lst1 lst2)
  (let loop ((lst1 lst1) (lst2 lst2) (res '()))
    (if (or (null? lst1) (null? lst2))       
        (reverse res)
        (loop (cdr lst1) 
              (cdr lst2) 
              (cons (cons (car lst1) (car lst2)) res)))))
于 2014-05-13T07:26:01.307 回答