【发布时间】:2017-09-23 18:49:20
【问题描述】:
我希望我的函数对给定列表中的每个数字求平方,如果 lst 中的元素是一个列表,该函数递归地应用于它并对该列表的元素进行操作。
这是我的代码:
(define (sqr-up-rec-tail lst)
(define (helper lst newlist)
(if (null? lst) newlist
(if (list? (car lst))
(helper (cdr lst) (cons (sqr-up-rec-tail (car lst)) newlist))
(helper (cdr lst) (cons (* (car lst) (car lst)) newlist)))))
(helper lst ()))
我的函数有效,但是,我得到了一个反向平方列表。 例如,当我运行时:
(sqr-up-rec-tail '(2 4 6 (10 20)))
我得到的输出是:
((400 100) 36 16 4)
我想不使用使用外部反向功能获得正确的输出。我的猜测是我应该使用 append 而不是 cons,虽然我没有让它工作。
谢谢。
【问题讨论】:
-
只需将
...if (null? lst) newlist...更改为...if (null? lst) (reverse newlist)...。 -
@Renzo "我想在不使用外部反向函数的情况下得到正确的输出。"
标签: list recursion scheme racket tail-recursion