String range in Scala

In Ruby we can do this:

$ 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"]

In Scala if I try the same I get error:

$ 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)
                    ^

How do get a range of Strings in Scala ?


For this example you could do (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"

Edited as per comment, thanks (but getting a bit ugly!)


('a' to 'z').map("a" + _) :+ "ba" :+ "bb"

:)


A for comprehension would do nicely:

val abc = 'a' to 'z'
for (c1 <- abc; c2 <- abc) yield (s"$c1$c2")

This yields a Seq/Vector[String] with all the permutations you'd expect

链接地址: http://www.djcxy.com/p/19874.html

上一篇: 我怎样才能在Java中连接两个数组?

下一篇: Scala中的字符串范围