方案阶乘(事实* l)问题
我是Scheme的新手,所以请原谅这个问题:我有一个计算数字列表的阶乘的函数,但它在结果中的最后一个数字之前给了我一个句点。我哪里错了?
代码:
#lang scheme
(define fact
(lambda (n)
(cond
((= n 0) 1)
((= n 1) 1)
(else (* n (fact (- n 1)))))))
(define fact*
(lambda (l)
(cond
((null? (cdr l)) (fact (car l)))
(else
(cons (fact (car l)) (fact* (cdr l)))))))
输出:
> (fact* '(3 6 7 2 4 5))
(6 720 5040 2 24 . 120)
I'm a newbie at Scheme, so forgive the question: I have a function that calculates the factorials of a list of numbers, but it gives me a period before the last number in the results. Where am I going wrong?
code:
#lang scheme
(define fact
(lambda (n)
(cond
((= n 0) 1)
((= n 1) 1)
(else (* n (fact (- n 1)))))))
(define fact*
(lambda (l)
(cond
((null? (cdr l)) (fact (car l)))
(else
(cons (fact (car l)) (fact* (cdr l)))))))
output:
> (fact* '(3 6 7 2 4 5))
(6 720 5040 2 24 . 120)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您所做的是创建一个 列表不正确。试试这个:
在第四行中添加
list
应该可以使此工作按您的预期进行。更好的可能是:这允许您的
fact*
函数在空列表上工作,并减少调用fact
的位置数量。What you have done is create an improper list. Try this:
The addition of the
list
in the fourth line should make this work as you expect. Better might be the following:This allows your
fact*
function to work on the empty list, as well as reducing the number of places where you make a call tofact
.其他 答案指出了您的
事实*
导致您得到不正确列表的原因功能。我只想指出,您可以使用 高阶函数map
:map
将一个函数和一个列表作为参数,并将该函数应用于列表中的每个元素,生成一个新列表。The other answers have pointed out the reason why you get an improper list as a result of your
fact*
function. I would only like to point out that you could use the higher-order functionmap
:map
takes a function and a list as arguments and applies the function to every element in the list, producing a new list.使用
append
而不是cons
。cons
用于构造对,这就是为什么你有“.”。用于分隔一对的元素。这是一个例子:Use
append
instead ofcons
.cons
is used to construct pairs, which is why you have the "." that is used to separate the elements of a pair. Here's an example: