如何迭代列表?

发布于 2024-10-03 12:54:29 字数 345 浏览 3 评论 0原文

我正在尝试使用 SML 进行基本的列表操作。

我想提取列表中的每个元素并将字符串附加到该元素并将其添加回列表中。 示例:

List : [A,B,C,D]
String : A
Final List: [AA,AB,AC,AD]

如何在 SML 中迭代列表中的每个元素?我可以使用 ^ 附加字符串并使用 @ 连接列表,但如何从列表中提取每个元素?

我们还可以使用映射或数组之类的东西来存储这些列表值并将其传递给 SML 中的不同函数吗?

我只能找到一些关于地图的模糊信息,而没有关于我们如何使用它的明确信息。

I am trying to do basic list operations with SML.

I want to extract each element of the list and append string to that element and add it back to the list.
Example:

List : [A,B,C,D]
String : A
Final List: [AA,AB,AC,AD]

How can I iterate through each element in the list in SML? I can append strings using ^ and concatenate lists using @ but how do I extract each element from the list?

Also can we use something like map or arrays to store these list values and pass it to different functions in SML?

I could just find some vague information about map and no definite information as to how we can use it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸩远一方 2024-10-10 12:54:29

有两种简单的方法可以做到这一点:

- fun addstring (x::xs) a = (a^x) :: addstring xs a  
=   | addstring []      a = []  
=   ;  
val addstring = fn : string list -> string -> string list  
- addstring ["A", "B", "C", "D"] "A";  
val it = ["AA","AB","AC","AD"] : string list  

上面使用模式匹配来破坏列表,执行操作,然后再次构造列表,不断递归。

- fun addstring2 xs a = map (fn x => a^x) xs;  
val addstring2 = fn : string list -> string -> string list  

- addstring2 ["A", "B", "C", "D"] "A";  
val it = ["AA","AB","AC","AD"] : string list  

这个要简单一些(可能比 addstring 中的显式情况更难阅读。)但它显示了如何使用 map - 您指定一个将每个元素从源域映射到目标域的函数,给它源域中的元素列表,并返回目标域中的列表。

当然,这些都不会对列表进行就地更新,而是返回新列表。

two easy ways to do this:

- fun addstring (x::xs) a = (a^x) :: addstring xs a  
=   | addstring []      a = []  
=   ;  
val addstring = fn : string list -> string -> string list  
- addstring ["A", "B", "C", "D"] "A";  
val it = ["AA","AB","AC","AD"] : string list  

The above uses pattern matching to destruct the list, performs the operation, then constructs the list again, recursing as it goes.

- fun addstring2 xs a = map (fn x => a^x) xs;  
val addstring2 = fn : string list -> string -> string list  

- addstring2 ["A", "B", "C", "D"] "A";  
val it = ["AA","AB","AC","AD"] : string list  

This one is a fair bit simpler (if perhaps a tiny bit harder to read than the explicit cases in addstring.) but it shows how map is used - you specify a function that maps each element from the source to the target domain, give it a list of elements in the source domain, and it returns a list in the target domain.

of course, neither of these do in-place updating of the list, they return the new list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文