Reputation: 95
I'm new to Scala, and trying to understand how to work on lists of tuples, so I've created a fictive list of people:
val fichier = List(("Emma Jacobs","21"), ("Mabelle Bradley","53"), ("Mable Burton","47"))
I would like to catch the components of each element (tuple) and use them for other purposes, so I wrote this:
def classeur(personne: List[(String, String)]) : String =
personne match {
case Nil => "Empty file"
case h :: t => {
h._1 + "is " + h._2 + "years old"
classeur(t)
}
}
Result: Empty file.
What am I misunderstanding, as my fichier
is not empty? Why does it consider fichier
to be Nil
?
Upvotes: 1
Views: 236
Reputation: 16935
Because you're not updating your list, you're just creating a string (while doing nothing with it) and then recursing on the tail. You do this until you reach an empty list.
The others have told you how to fix your code as-is: just by concatenating the recursive call to your string.
I would consider, however, using map
, which is much more functional and less prone to mistakes like this:
def classeur(personne: List[(String, String)]) : String =
personne.map { case (name, age) => s"$name is $age years old" }.mkString("\n")
This will create a list of String
from your list of tuple, then join them with the argument to mkString
, which is a newline in this case.
Upvotes: 2
Reputation: 7928
Your code is almost right. The only issue is that you forgot to concatenate the String to the result of the recursive call:
def classeur(personne: List[(String, String)]) : String =
personne match {
case Nil => "Empty file"
case h::t => h._1 + "is " + h._2 + "years old " + classeur(t)
}
Here is another option by extracting the values of the tuple in the case statement, which I think may be clearer:
def classeur(personne: List[(String, String)]) : String =
personne match {
case Nil => "Empty file"
case (name, age)::t => name + "is " + age + "years old " + classeur(t)
}
EDIT:
Here is an option with map as suggested in comments:
personne.map{case (name, age) => s"$name is $age years old"}.mkString(",")
Output:
Emma Jacobs is 21 years old,Mabelle Bradley is 53 years old,Mable Burton is 47 years old
Upvotes: 5