Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String range in Scala

Tags:

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 ?

like image 977
tuxdna Avatar asked Apr 02 '14 12:04

tuxdna


People also ask

How do you find the length of a string in Scala?

Get length of the string So, a length() method is the accessor method in Scala, which is used to find the length of the given string. Or in other words, length() method returns the number of characters that are present in the string object. Syntax: var len1 = str1.

What is string * in Scala?

In scala, string is a combination of characters or we can say it is a sequence of characters. It is index based data structure and use linear approach to store data into memory. String is immutable in scala like java.

What does :+ mean in Scala?

On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.


3 Answers

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!)

like image 147
Gavin Avatar answered Sep 28 '22 16:09

Gavin


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

:)

like image 41
ZhekaKozlov Avatar answered Sep 28 '22 17:09

ZhekaKozlov


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

like image 32
klogd Avatar answered Sep 28 '22 17:09

klogd