我正在尝试创建一个函数,该函数接受 2 个数字,并将创建一个列表,使用第一个数字作为起始数字,第二个数字作为结束值,同时填充起始数字和结束数字之间的值。
例如:
用户传入 3 和 7:
输出应该是 (3 4 5 6)
我试图这样做并使用递归,但我很挣扎:
(define (createlist start end)
(if(= start end)
'())
(cons start '())
(createlist (+ 1 start) end))
最佳答案
在此类问题的解决方案中发现了一个重复模式,您必须在使用递归的过程中构建一个列表。让我来说明一般步骤,我会让你填空:
(define (createlist start end)
(if (= <???> <???>) ; the problem is solved when start and end are the same
'() ; lists end in null
(cons <???> ; if we are not done yet, we `cons` the current value of start
(createlist <???> end)))) ; with the result of calling the recursion
; notice that start is one step closer to the end, so we increment it
该算法的思想是在每一步我们添加当前的 start
使用 cons
构建的列表的值, 并递增 start
直到它到达 end
, 至此递归结束。
你应该看看 The Little Schemer或 How to Design Programs ,这两本书都会教你如何为这种列表递归问题构建解决方案。
更新:
现在您已经发布了到目前为止编写的代码,我可以告诉您正确答案。请非常小心括号 [ if
的右括号在 else
之后部分 ] 和空格 [ if(
与 if (
不同],它们在 Scheme 中很重要。正确缩进你的代码,它会帮助你找到很多错误:
(define (createlist start end)
(if (= start end)
'()
(cons start
(createlist (+ 1 start) end))))
现在你可以看到 <???>
正确填写。
关于lisp - 处理列表和附加值的开始方案 (LISP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719787/