用自然语言(Scala)枚举列表的最佳方法是什么?
List
对象具有 mkString
方法,可以将其转换为带有分隔符的字符串。然而,大多数人类语言在枚举列表时对最后一个元素的处理方式有所不同。例如 A、B、C 和 D。就
代码大小和合理效率而言,完成此任务的最佳方案是什么?准确地说,我正在寻找一个满足以下条件的函数:
assertEquals("",foo(List()))
assertEquals("A",foo(List("A")))
assertEquals("A and B",foo("List("A","B")))
assertEquals("A, B and C", foo(List("A","B","C")))
assertEquals("A, B, C and D", foo(List("A","B","C","D")))
The List
object has the mkString
method that will can convert to a string with a seperator. However most human languages treats the last element different when enumerating a list. For example A, B, C and D.
What is the best in terms of code size and reasonable efficiency to accomplish this? To be precise, I am searching for a function that satisfies:
assertEquals("",foo(List()))
assertEquals("A",foo(List("A")))
assertEquals("A and B",foo("List("A","B")))
assertEquals("A, B and C", foo(List("A","B","C")))
assertEquals("A, B, C and D", foo(List("A","B","C","D")))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:这可能更清楚一点:
@axaluss 速度取决于列表长度。由于平均列表长度超过 4 个元素,第二个版本比 Tomasz 的版本更快。否则,速度会稍微慢一些。
edit: This might be a bit clearer:
@axaluss The speed depends on the list length. With an average list length above about 4 elements, this second version is faster than Tomasz's. Otherwise, it's slightly slower.
我的看法:
还要利用尾递归:
My take:
Also to utilize tail recursion: