Obtener resultado en List[(Char, Int)] en lugar de List[Product]

I'm trying out the following piece of code in Scala REPL,

val a = List(('a',4),('b',8))
val z = ('a',1)
a map (x => if (x._1 == z._1) (x._1, x._2 - z._2) else (z :: a))

Obtengo el siguiente resultado: List[Product] = List((a,3), List((a,1), (a,4), (b,8)))

Why am I getting output in List[Product] ?

What should I do to get the resultant type of the output be List[(Char, Int)] en lugar de List[Product]

preguntado el 05 de mayo de 13 a las 21:05

Isn't double-nested lists and List[(Char, Int)] at the same time oxymorons? -

Which result do you want to have in concrete, given your values? Note that the if-part and the else part don't match in the returned type. Either you return a new pair, or a List of pairs. -

1 Respuestas

You are applying a function to every element in the list "a"

In the first iteration you take (a,4) and in this case you are applying a function that substract 1 to the second element of the tuple.

El resultado es (a,3)

But in the second element you are using cons operator to "a" so the result of this operation is a new inmmutable list.

('a',1) :: List(('a',4),('b',8)) === List((a,1), (a,4), (b,8))

IMO what you want as result is:


Eso se puede lograr así:

a.map {
    case (z._1, x) => (z._1, x - z._2)
    case x => x

Respondido el 08 de Septiembre de 13 a las 11:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.