总和SML中的两个列表
SML中有两个列表,我想在另一个列表中添加一个列表,
val one = [1.1,2.2,3.3] : real list;
val two = [4.4,5.5,6.6] : real list;
结果应该是[5.5,7.7,9.9]。
我不确定我正在做正确的事情,但基本上我正在尝试将这两个列表传递给一个乐趣,然后做一个[0] +两个[0]之类的事情,
还有更好的方法吗?谢谢〜
There are two list in sml and I want to add one to another
val one = [1.1,2.2,3.3] : real list;
val two = [4.4,5.5,6.6] : real list;
The result should be [5.5, 7.7, 9.9].
I not sure I'm doing this right but basically I'm trying to pass this two list to a fun then do things like one[0] + two[0]
Is there any better way to do it? thanks~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简洁的解决方案是使用
listPair.map
函数:如果一个列表比另一个列表更长,则此解决方案会丢弃多余的元素。
The most concise solution is to use the
ListPair.map
function:This solution discards the excess elements if one list is longer than the other.
SML列表通常不会通过索引访问。列表是 empty 或一个值和列表。使用此递归定义,我们可以有任何长度的列表。这也意味着我们只需要在两种情况下操作以迭代列表:空列表或带有元素和另一个列表的列表。
考虑
MAP
函数,该功能将函数f
映射到列表,然后返回另一个列表。我们可以在
int list
中的每个元素中添加1个,其中类似于以下内容,它将产生
[3,4,5]
。映射在两个列表上非常简单。
尽管这不能容纳不同长度的列表或如何处理它们。
如果您能弄清楚这一点,那么完成分配的任务是
map2
的非常简单的应用。SML lists are not typically accessed by index. A list is either empty or a value and a list. With this recursive definition we can have a list of any length. It also means we only need to operate on two cases to iterate over a list: the empty list, or a list with an element and another list.
Consider a
map
function that maps a functionf
to a list and returns another list.We could add 1 to every element in an
int list
with something like:Which would yield
[3, 4, 5]
.It's pretty straightforward to map over two lists.
Though this does not accommodate lists of differing lengths or how to handle them.
If you can figure this out, accomplishing your assigned task is a very straightforward application of
map2
.如何遵循...
测试
插图
How about following...
Test
Illustration