使用mkString和foldRight合并一个字符串列表 [英] Merging a list of Strings using mkString vs foldRight

查看:101
本文介绍了使用mkString和foldRight合并一个字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试Scala中的一些东西,试图习惯函数式编程以及再次倾听一种新语言(这是上一次以来的一段时间)。



<现在给出一个字符串列表,如果我想将它们合并成一个长字符串(例如scala,is,fun=>scalaisfun )我想一个办法是做一个 foldRight ,并在各个元素上应用连接。无可否认,更简单的另一种方法是调用 mkString

我检查了github,但无法真正找到相应函数的源代码(任何帮助都将不胜感激),所以我不确定函数被执行。从我的头顶来看,我认为 mkString 更灵活,但感觉可能有 foldRight in在某处执行。它有什么道理吗?



否则,scaladocs会在 toString 上调用 mkString 为每个相应的元素。看到它们已经是字符串,在这种情况下,这可能是 mkString 的一个负面因素。对性能,简单/优雅等两种方法的优缺点有何评论?

解决方案

简单的回答:使用 mkString



someString.toString 返回同一个对象。



mkString 用单个 StringBuilder 实现,它只创建一个新字符串。使用 foldLeft ,您将创建 N-1 新字符串。



您可以在 foldLeft 中使用 StringBuilder ,它会像 mkString ,但 mkString 更短:

 字符串.foldLeft(new StringBuilder){(sb,s)=> sb append s} .toString 
strings.mkString //相同的结果,至少速度相同


I am currently trying out things in Scala, trying to get accustomed to functional programming as well as leaning a new language again (it's been a while since last time).

Now given a list of strings if I want to merge them into one long string (e.g. "scala", "is", "fun" => "scalaisfun") I figured one way to do it would be to do a foldRight and apply concatenation on the respective elements. Another way, admittedly much simpler, is to call mkString.

I checked on github but couldn't really find the source code for the respective functions (any help on that would be appreciated), so I am not sure how the functions are implemented. From the top of my head, I think the mkString is more flexible but it feels that there might be a foldRight in the implementation somewhere. Is there any truth to it?

Otherwise the scaladocs mention that mkString calls on toString for each respective element. Seeing that they are already strings to start with, that could be one negative point for mkStringin this particular case. Any comments on the pros and cons of both methods, with respect to performance, simplicity/elegance etc?

解决方案

Simple answer: use mkString.

someString.toString returns the same object.

mkString is implemented with a single StringBuilder and it creates only 1 new string. With foldLeft you'll create N-1 new strings.

You could use StringBuilder in foldLeft, it will be as fast as mkString, but mkString is shorter:

strings.foldLeft(new StringBuilder){ (sb, s) => sb append s }.toString
strings.mkString // same result, at least the same speed

这篇关于使用mkString和foldRight合并一个字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆