问题描述
我只是在研究scheme/lisp,并在考虑如何修正自己对average
的定义.我不确定如何做一些我认为必需的事情.
I'm just playing around with scheme/lisp and was thinking about how I would right my own definition of average
. I'm not sure how to do some things that I think are required though.
- 定义一个接受任意数量参数的过程
- 计算这些参数
- 将参数列表传递给(+)以将它们加在一起
有人提供定义average
的示例吗?我对LISP的了解似乎不足,无法形成Web搜索来获取我想要的结果.
Does someone have an example of defining average
? I don't seem to know enough about LISP to form a web search that gets back the results I'm looking for.
推荐答案
该定义将是一个非常简单的单行代码,但是在不破坏它的情况下,您应该研究一下:
The definition would be a very simple one-liner, but without spoiling it, you should look into:
-
一个"rest"参数-该
(define (foo . xs) ...xs...)
将foo
定义为一个接受任意数量参数的函数,它们可作为列表使用,该列表将是xs
的值.
a "rest" argument -- this
(define (foo . xs) ...xs...)
definesfoo
as a function that takes any number of arguments and they're available as a list which will be the value ofxs
.
length
返回列表的长度.
apply
接受一个函数和一个值列表,并将该函数应用于这些值.
apply
takes a function and a list of values and applies the function to these values.
当您了解到这一点时,可以去做更多:
When you get that, you can go for more:
-
参见
foldl
函数,以避免将列表应用于可能非常大的列表(在某些实现中,参数列表的长度受到限制,这可能很重要,但是在Racket中不会有太大的区别).
see the
foldl
function to avoid applying a list on a potentially very big list (this can matter in some implementations where the length of the argument list is limited, but it wouldn't make much difference in Racket).
请注意,Racket具有确切的原理,您可以使用exact->inexact
制作更有效的浮点版本.
note that Racket has exact rationals, and you can use exact->inexact
to make a more efficient floating-point version.
破坏者是:
-
(define (average . ns) (/ (apply + ns) (length ns)))
使其需要一个参数:(define (average n . ns) (/ (apply + n ns) (add1 (length ns))))
使用foldl
:(define (average n . ns) (/ (foldl + 0 (cons n ns)) (add1 (length ns))))
使其使用浮点:(define (average n . ns) (/ (foldl + 0.0 (cons n ns)) (add1 (length ns))))
这篇关于(在Lisp中定义(平均....))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!