【问题标题】:Work on list of tuples in Scala - part 1在 Scala 中处理元组列表 - 第 1 部分
【发布时间】:2018-07-24 22:04:06
【问题描述】:

我是 Scala 新手,想了解如何处理元组列表,所以我创建了一个虚构的人员列表:

val fichier = List(("Emma Jacobs","21"), ("Mabelle Bradley","53"), ("Mable Burton","47"))

我想捕获每个元素(元组)的组件并将它们用于其他目的,所以我写了这个:

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)
    }

  }

结果:空文件。

我误会了什么,因为我的fichier 不是空的?为什么它认为fichierNil

【问题讨论】:

  • 你应该考虑使用地图。
  • h._1 + "is " + h._2 + "years old" 行没有意义
  • @cchantep 为什么会这样?
  • 丢弃值

标签: scala list functional-programming pattern-matching tuples


【解决方案1】:

您的代码几乎是正确的。唯一的问题是您忘记将字符串连接到递归调用的结果:

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)
  }

这是另一种选择,通过提取case语句中的元组的值,我认为这可能更清楚:

def classeur(personne: List[(String, String)]) : String = 
  personne match {
    case Nil => "Empty file" 
    case (name, age)::t => name + "is " + age + "years old " + classeur(t)
  }

编辑

这是 cmets 中建议的带有地图的选项:

personne.map{case (name, age) => s"$name is $age years old"}.mkString(",")

输出:

Emma Jacobs is 21 years old,Mabelle Bradley is 53 years old,Mable Burton is 47 years old

【讨论】:

  • 同意,但我仍然认为需要解释为什么操作的代码不起作用
【解决方案2】:

因为你没有更新你的列表,你只是创建了一个字符串(同时什么都不做),然后在尾部递归。你这样做,直到你到达一个空列表。

其他人已经告诉您如何按原样修复您的代码:只需将递归调用连接到您的字符串。

不过,我会考虑使用map,它更实用,更不容易出错:

def classeur(personne: List[(String, String)]) : String = 
    personne.map { case (name, age) => s"$name is $age years old" }.mkString("\n")

这将从您的元组列表中创建一个String 列表,然后将它们与mkString 的参数连接起来,在这种情况下是一个换行符。

【讨论】:

猜你喜欢
  • 2018-07-29
  • 2018-07-25
  • 2018-07-26
  • 2015-07-06
  • 2014-01-23
  • 2020-04-05
  • 1970-01-01
  • 2014-12-30
  • 2014-08-03
相关资源
最近更新 更多