Home > Software engineering >  How to concatenate Char type elements in Scala
How to concatenate Char type elements in Scala

Time:05-28

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.

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.

CodePudding user response:

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)

CodePudding user response:

If you want a Seq[Char] like Luis Miguel commented in your question you should yield Seq(x, y, z)

If you want to concatenate the chars into a String you can use an interpolator:

s"$x$y$z"
  • Related