简体   繁体   English

添加列表列表

[英]adding lists of lists

I am new to SML and am working on some list arithmitic. 我是SML的新手,正在从事一些列表算术研究。 I am trying to add a list of lists together using the fold function, without any iteration. 我正在尝试使用fold函数将列表列表一起添加,而没有任何迭代。 The idea is 这个想法是

[[1,2,3],[4],[1]] = 11

This is the fold function I am using 这是我正在使用的折叠功能

fun fold f base [] = base
| fold f base (x::xs) = f x (fold f base xs);

Because I am using fold, I am not sure if there is a way to use the fold function to make the list of lists one single list, and then it is pretty easy to add them together, or if I am just missing the ball completely. 因为我使用的是fold,所以我不确定是否可以使用fold函数将列表的列表制作为一个列表,然后将它们加在一起非常容易,或者我是否完全错过了球。

Here are the added functions, they add up the contents of a single list. 这是添加的功能,它们将单个列表的内容相加。

fun add x y = x+y;
fun sumList L = fold add 0 L;

I suggest that you first try to write a function that adds all numbers in a list of intergers and adds this number to a start value (hint: this can be done using fold as well). 我建议您首先尝试编写一个函数,该函数将整数列表中的所有数字相加并将该数字添加到起始值(提示:这也可以使用fold来完成)。

You can then use this function as a function argument to fold to achieve your goal. 然后,您可以将此函数用作函数参数来折叠以实现目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM