方案中的不正确列表与正确列表 [英] Improper vs. proper list in Scheme

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

问题描述

我尝试实现的原始代码..输出应该是我代码的(1.4)(2.5)..我想你们都知道我想做什么....这也是尾递归练习

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)))
  ))

你们中的一些人给我关于缺点对的好建议.现在它的中间是虚线符号.然后问题是列表不正确,最后是空列表. 当2个输入列表是这样的时候.....'(1 2 3 4)'(4 5 6)) 我的输出是这样的; ((1.4)((2.5)((3.6)()))))() 输出末尾的空列表不应该存在...所以我不了解不正确的列表,正确的列表....?有没有文件,我可以看看吗?

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?

推荐答案

考虑conslist之间的区别:

也就是说,(cons a b)创建一个单元格,该单元格的cara并且cdrb.
(list a b)创建一个单元格,该单元格的cara,但是cdr是一个列表,而car那个列表是b ,而其cdrnil.

That is, (cons a b) creates a cell whose car is a and cdr is b.
(list a b) creates a cell whose car is a, but the cdr is a list, and the car of that list is b, while its cdr is nil.

如果b是一个列表,则左边的列表将是一个以b为尾并且在b的前面添加a的列表. 右边的一个也将是一个列表,但其中一个将b作为其第二个 而不是其尾巴.

If b is a list, the one on the left will be a list which has b as its tail, and with a added at the front of b.
The one on the right will also be a list, but one which has b as its second element, not as its tail like you want.

要修复程序,只需要将list替换为cons.

To fix your program, you only need to replace your list with a cons.

但是您的函数不是尾部递归的,因为它通过递归调用的结果来完成工作.

But your function is not tail-recursive, because it does things with the result of the recursive call.

要使其成为尾递归,一种好方法通常是制作一个具有累加器参数的辅助函数.

To make it tail-recursive, a good way is usually to make a helper function which has an accumulator parameter.

我可能会这样写:

(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 '()))

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆