Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to concatenate Char type elements in Scala

I want to compute all the combination of size 3 from the letters of the alphabet (stored in vocabulary as Seq[Char]) and output each combination as a Seq[Char], while storing it in a sequence.

Here is the definition of the alphabet :

 val alphabet:Seq[Char] = Seq('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')

I wrote this piece of code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def enumProduct3(vocabulary: Seq[Char]): Seq[Seq[Char]] = {
    // vocabulary = alphabet
    val keys:Seq[Seq[Char]] = (for {x<-vocabulary;y<-vocabulary;z<-vocabulary} yield(x + y + z).toSeq).toSeq
  }

I get a type mismatch error :

[error]  found   : Unit
[error]  required: Seq[Seq[Char]]

I searched the Scala API to concatenate Char type elements but didn’t find anything.

>Solution :

There are two problems in your enumProduct3 – yield should be Seq(x, y, z) and method should return value:

def enumProduct3(vocabulary: Seq[Char]): Seq[Seq[Char]] = {
  // vocabulary = alphabet
  val keys: Seq[Seq[Char]] = for {x <- vocabulary; y <- vocabulary; z <- vocabulary}
    yield Seq(x, y, z)
  keys
}

Or just:

def enumProduct3(vocabulary: Seq[Char]): Seq[Seq[Char]] = for {
  x <- vocabulary; y <- vocabulary; z <- vocabulary
} yield Seq(x, y, z)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading