我试图实现一个Scheme过程,它接受一个嵌套的数字列表,该列表的格式可能不是很好,并且返回一个嵌套列表,该列表具有相同的内容和结构,但在显示时没有任何点。
示例:
scm> (reform '((1 . 2) 3))
((1 2) 3)
scm> (reform '(1 (2 3 . 4) . 3))
(1 (2 3 4) 3)
scm> (reform '(1 . ((2 3 . 4) . 3)))
(1 (2 3 4) 3)我目前的解决方案:
(define (reform s)
(cond
((null? s) nil)
((number? s) s)
((null? (cdr s)) (car s))
(else (list (reform (car s)) (reform (cdr s))))
)
)这个解决方案确实删除了所有的点,但它没有保持输入的形式。我如何重写我的实现,这样它就不会创建输入中不存在的额外列表?
发布于 2015-04-05 19:27:09
这通过了测试。
(define (reform xs)
(cond
[(null? xs) xs]
[(and (pair? xs) (pair? (cdr xs)))
(cons (reform (car xs)) (reform (cdr xs)))]
[(and (pair? xs) (null? (cdr xs)))
(list (reform (car xs)))]
[(pair? xs)
(cons (reform (car xs)) (list (reform (cdr xs))))]
[else xs]))
(reform '((1 . 2) 3))
(reform '(1 (2 3 . 4) . 3))
(reform '(1 . ((2 3 . 4) . 3)))发布于 2015-04-06 01:26:24
不知道为什么@soegaard有这么多测试--当明显的情况是先做例外时,列表是否是一对:
(define (dot->proper xs)
(cond ((null? xs) '())
((not (pair? xs)) (list xs))
((pair? (car xs)) (cons (dot->proper (car xs)) (dot->proper (cdr xs))))
(else (cons (car xs) (dot->proper (cdr xs))))))
(dot->proper '((1 . 2) 3)) ; ==> ((1 2) 3)
(dot->proper '(1 (2 3 . 4) . 3)) ; ==> (1 (2 3 4) 3)
(dot->proper '(1 . ((2 3 . 4) . 3))) ; ==> (1 (2 3 4) 3)https://stackoverflow.com/questions/29460947
复制相似问题