在 SML 中使用foldr 连接字符串

发布于 2024-09-27 00:17:31 字数 249 浏览 2 评论 0原文

我正在尝试声明一个函数,字符串列表 ->字符串,例如输入 ["Chicago","city","USA"] 应返回“美国芝加哥市”。到目前为止我所做的是:

fun gather ts = foldr op ^ "" ts;

这似乎有点符合实际,但问题是,我想在单词之间包含空格,因为此函数将返回 "ChigagocityUSA"

I'm trying to declare a function, string list -> string, that with the input for instance
["Chicago","city","USA"] should return "Chicago city USA". What I did so far was this:

fun gather ts = foldr op ^ "" ts;

This seems to be somewhat along the lines, however the problem is, I would like to include the spaces between the words, as this function would return "ChigagocityUSA".

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

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

发布评论

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

评论(2

蓝咒 2024-10-04 00:17:31

是的,问题是 ^ 是一个函数,对于两个字符串“foo”和“bar”返回“foobar”,尽管您想要“foo bar”。

因此,您需要做的是定义一个函数,该函数接受两个字符串参数(作为元组)并返回两个字符串,它们之间有一个空格(因此 string1 ^ " " ^ string2)。

然后,您可以将该函数作为 foldr 的参数提供,并获得您想要的结果。

Yes, the problem is that ^ is a function that for two strings "foo" and "bar" returns "foobar", although you want "foo bar".

So what you need to do is to define a function that takes two string arguments (as a tuple) and returns the two strings with a space in between them (so string1 ^ " " ^ string2).

You can then give that function as an argument to foldr and get the result you want.

假情假意假温柔 2024-10-04 00:17:31

使用 hdtl 获取 fold 的初始值。这可以避免结果中出现前导或尾随空白字符。如果您想从左到右思考,foldl 很有用。

定义:

fun gather xs = 
      foldl (fn (x,acc) =>
                acc  ^ " " ^ x) (hd xs) (tl xs)

用法:

- gather ["what", "is", "this", "gather"];
val it = "what is this gather" : string
- 

Use hd and tl to get inital values for fold. This avoids having a leading or trailing blank character in the result. foldl is useful if you want to think left-to-right.

Definition:

fun gather xs = 
      foldl (fn (x,acc) =>
                acc  ^ " " ^ x) (hd xs) (tl xs)

Usage:

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