[英]sum of a list in scheme
I'm beginner in functional programming and scheme language. 我是函数式编程和方案语言的初学者。
I found a way to build the sum of a list: 我找到了一种建立列表总和的方法:
(define (sum lst)
(if (empty? lst)
0
(+ (car lst) (sum (cdr lst)))))
(sum (list 1 2 3))
My question is: is there a way to build the sum of a list without a extra function like sum, just using the "+" function like this: 我的问题是:有没有办法建立一个列表的总和没有像sum这样的额外函数,只需使用“+”函数,如下所示:
(+ 1 2 3)
You can apply
list of arguments to a function. 您可以
apply
参数列表apply
函数。 So in this case you can: 所以在这种情况下你可以:
> (apply + (list 1 2 3))
6
The reference for MIT/Gnu-Scheme says, that +
takes ANY number of arguments. MIT / Gnu-Scheme的参考文献说,
+
需要任意数量的参数。 I am sure, that this standard. 我相信,这个标准。
In general: 一般来说:
(define (foo . args) ....)
is used like (foo)
or (foo x)
or (foo xy)
, (foo xyz)
, .... . 使用像
(foo)
或(foo x)
或(foo xy)
, (foo xyz)
,.... Inside foo
the args will be '()
, (x)
, (xy)
or (xyz)
. 在
foo
里面,args将是'()
, (x)
, (xy)
或(xyz)
。
See exercise 2.20 in SICP or MIT/Scheme Reference 9.2 chap 2.1 参见SICP中的练习2.20或MIT / Scheme Reference 9.2 chap 2.1
This means: 这意味着:
For the arithmetic procedures +
, *
, -
and /
your procedure is not necessary, because they are defined for any number of arguments, including zero and one. 对于算术过程
+
, *
, -
和/
您的过程不是必需的,因为它们是为任意数量的参数定义的,包括零和一。 This is also true for some other built-in procedures. 对于其他一些内置程序也是如此。 For your own procedures you can use the dotted-tail notation.
对于您自己的程序,您可以使用点尾符号。
You can download the MIT/Scheme Reference from the GNU-Pages. 您可以从GNU-Pages下载MIT / Scheme Reference。 I think it helps for all implementation of Scheme, because extension of the standard are described.
我认为它有助于Scheme的所有实现,因为描述了标准的扩展。 Most parts are easy to read.
大多数部件都易于阅读。
Common Lisp programmers should look to [ http://www.gigamonkeys.com/book/functions.html] . Common Lisp程序员应该查看[ http://www.gigamonkeys.com/book/functions.html] 。
Here you must use &rest instead of >.< (defun + (&rest numbers) ...) 在这里你必须使用&rest而不是>。<(defun +(&rest numbers)...)
Both lisp-dialects know default, optional and rest parameters. 两种lisp方言都知道默认,可选和休息参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.