Reputation: 417
I am working on the examples of 99 scala problems.The question p11 i.e Modified run-length encoding. On the second line, it imports the object from p10 code "import P10.encode". My question here is when it gets into the below line of code
encode(ls) map { t => if (t._1 == 1) t._2 else t }
I am aware that it maps P10 encode definition but how does it know from where it should get the t value? Does it work on the output such as if the output of p10 is List((1,1), (2,4), (1,3)) for the input encode(List(1,4,4,3)) or something else? Please enlighten me
Upvotes: 0
Views: 58
Reputation: 1016
so the t
is just an identifier for an anonymous function parameter.
I am assuming that encode(ls)
returns List[(Int, Int)]
so that means that map
has the following signature map[B](f : ((Int, Int)) => B)
this means it requires a function from Int
(which is what's in the list) to some other type.
t => if (t._1 == 1) t._2 else t
is a literal for a function that takes one parameter called t
(the compiler can infere that it has to be an (Int, Int)
due to the literal being in the parameter position of map
on a List[(Int, Int)]
) and and returns a single Int
yielding a List[Int]
after the map
really it could also have been x => if (x._1 == 1) x._2 else x
it's just a local name
EDIT: Added parens for the int tuple in map as per comment. woops
Upvotes: 2