SML NJ 的内部函数
我是 sml 的新手,并且在内部函数的语法方面遇到了麻烦。我需要做的是获取一个整数列表的列表,对每个列表求平均值,然后返回一个实数列表。这是我到目前为止的伪代码。
fun listAvg [] = 0
else (sum (x) div size (x))
fun sum[] = 0
| sum(head::rest)= head + sum rest;
fun size [] = 0
| size(head::rest) = 1 + size rest;
listAvg([[1,3,6,8,9], [4,2,6,5,1], [9,5,9,7], [5,4], [3,6,4,8]]);
任何建议将不胜感激。谢谢!
I am a complete newbie to sml and am having trouble with the syntax for inner functions. What I need to do is take a list of a list of ints, average each list, and return a list of reals. This is the psuedo-ish code I have so far.
fun listAvg [] = 0
else (sum (x) div size (x))
fun sum[] = 0
| sum(head::rest)= head + sum rest;
fun size [] = 0
| size(head::rest) = 1 + size rest;
listAvg([[1,3,6,8,9], [4,2,6,5,1], [9,5,9,7], [5,4], [3,6,4,8]]);
any advice would be greatly appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 let,如
您必须将
int list
传递给此函数,例如,除了重新排列顺序并放置关键字
let
之外,这不会对您的代码进行任何更改,中
和结束
。如果这不是家庭作业,我建议在List
结构中使用一些内置标准库函数,可以将此函数减少到两行,包括空列表上的模式匹配。编辑:
“对整数列表进行平均”有两种可能的含义。第一种方法是对每个列表求平均值,然后取平均值,第二种方法是将这些列表连接成一个长列表,然后对整个列表求平均值。当所有整数列表的长度相同时,这两种方法是等效的(舍入误差除外),但如您的示例所示,它们的长度不必相同。
由于这是作业,我不会直接给您答案,但请考虑以下内容,这可能会有所帮助:
Use a let, as in
You have to pass an
int list
to this function e.g.This is no change to your code, except to rearrange the order and putting the keywords
let
,in
, andend
. If this is not homework, I would recommend using a few built-in standard library functions in theList
structure that could reduce this function to two lines, including the pattern match on the empty list.EDIT:
There are two possible meanings to "average a list of a list of ints." The first is to average each list and then take the average of the averages, and the second is to join the lists together into one long list and take the average over the entire list. The two methods are equivalent (except for rounding errors) when all the lists of ints are of the same length, but as your example shows, they don't have to be the same length.
Since this is homework, I'm not going to give you the answer directly, but consider the following, which might be helpful: