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

Type mismatch when using map on a zipped list in Scala

Consider this code :

  /** Takes a list and turns it into an infinite looping stream. */
  def loop(l: List[Char]): LazyList[Char] = {
      l.to(LazyList)  #:::loop(l)
  }

  /** Encodes a sequence of characters with a looped key. */
  def codec(message: Seq[Char], key: Seq[Char], cipher: (Char, Char) => Char): Seq[Char] = {
    val loopedKey = loop(key.toList)
    val mergedMessage = message.toList zip loopedKey
    val xorResult = mergedMessage.map(cipher)
    xorResult.toSeq
  }

The loop function is correct, but the function named codec yield the following error when compiled :

[error]  type mismatch;
[error]  found   : (Char, Char) => Char
[error]  required: ((Char, Char)) => ?
[error]     val xorResult = mergedMessage.map(cipher)

I don’t understand why the required part says : ((Char, Char)) => ?.

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

>Solution :

(Char, Char) => Char is a function accepting 2 Chars and returning Char while zip will result in a collection of tuples (Char, Char). One option is to change cipher type to accept a tuple – ((Char, Char)) => Char:

def codec(message: Seq[Char], key: Seq[Char], cipher: ((Char, Char)) => Char): Seq[Char] = ...

Without changing the signature – access tuple elements directly:

val xorResult = mergedMessage.map(t => cipher(t._1, t._2))

Or just use tupled:

val xorResult = mergedMessage.map(cipher.tupled)
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