Scala中的字符串范围
在Ruby中,我们可以这样做:
$ irb
>> ("aa".."bb").map { |x| x }
=> ["aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj", "ak", "al", "am", "an", "ao", "ap", "aq", "ar", "as", "at", "au", "av", "aw", "ax", "ay", "az", "ba", "bb"]
在斯卡拉,如果我尝试相同的我会得到错误:
$ scala
Welcome to Scala version 2.9.1 (OpenJDK 64-Bit Server VM, Java 1.7.0_51).
scala> ("aa" to "bb").map(x => x)
<console>:8: error: value to is not a member of java.lang.String
("aa" to "bb").map(x => x)
^
如何在Scala中获得一系列字符串?
对于这个例子你可以做(斯卡拉2.10)
val atoz = 'a' to 'z'
for {c1 <- atoz if c1 <= 'b'; c2 <- atoz if (c1 == 'a' || (c1 == 'b' && c2 < 'c'))} yield s"$c1$c2"
按照评论编辑,谢谢(但有点难看!)
('a' to 'z').map("a" + _) :+ "ba" :+ "bb"
:)
一个理解会很好地做到:
val abc = 'a' to 'z'
for (c1 <- abc; c2 <- abc) yield (s"$c1$c2")
这会产生一个Seq / Vector [String],其中包含您所期望的所有排列
链接地址: http://www.djcxy.com/p/19873.html