在 SML 中使用foldr 连接字符串
我正在尝试声明一个函数,字符串列表 ->字符串,例如输入 ["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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,问题是
^
是一个函数,对于两个字符串“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.使用
hd
和tl
获取fold
的初始值。这可以避免结果中出现前导或尾随空白字符。如果您想从左到右思考,foldl
很有用。定义:
用法:
Use
hd
andtl
to get inital values forfold
. This avoids having a leading or trailing blank character in the result.foldl
is useful if you want to think left-to-right.Definition:
Usage: