I'm working through the "Learning Scala" book and have gotten to this exercise in chapter 4:
Write a function that takes a 3-sized tuple and returns a 6-sized tuple, with each original parameter followed by its String representation. For example, invoking the function with (true, 22.25, "yes") should return (true, "true", 22.5, "22.5", "yes", "yes").
The most promising of my attempts to specify the type signature is this:
def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
produces these errors:
Exercises.scala:99: error: not found: type A
def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
^
Exercises.scala:99: error: not found: type B
def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
^
Exercises.scala:99: error: not found: type C
def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
^
The intent is to allow any type, so I though I could indicate those with the A
, B
, or C
?
If I take away the type specification and just use Tuple3
, then it complains that I should have type params:
Exercises.scala:99: error: type Tuple3 takes type parameters
def t3ToT6[Tuple3[A, B, C]](t: Tuple3) = {
I suspect I'm close, and this is some sort of syntax issue, but have not yet found any examples of specifying Tuples in type signatures of functions.
What is the correct type signature for this problem description?
Are there examples you know of that I've not yet found which would help me understand this?
Identify 3 type parameters like so: [A,B,C]
With this you can ...
def t3ToT6[A,B,C](t: Tuple3[A,B,C]):Tuple6[A,String,B,String,C,String] =
Tuple6(t._1, t._1.toString
,t._2, t._2.toString
,t._3, t._3.toString)
It can also be done with a quick pattern match.
def t3ToT6[A,B,C](t:(A,B,C)):(A,String,B,String,C,String) = t match {
case (a,b,c) => (a, a.toString, b, b.toString, c, c.toString)
}