【问题标题】:Is there a better or functional way to compare 2 values in a map in Scala?有没有更好或更实用的方法来比较 Scala 地图中的 2 个值?
【发布时间】:2017-05-20 10:40:21
【问题描述】:

我有允许用户比较地图中包含的两个团队的功能。地图中包含的数据是从一个文本文件中读取的,该文本文件包含有关足球队及其过去 5 个赛季的积分记录的信息。数据存储为 Map[String, List[Int]]:

Manchester United, 72, 86, 83, 90, 94
Manchester City, 80, 84, 91, 77, 88
Chelsea, 76, 85, 92, 87, 84
Arsenal, 70, 79, 81, 76, 83
Liverpool, 69, 77, 80, 73, 79

以下功能允许用户输入两支球队的名称,并比较两支球队最近(最后)得分之间的差异。

 val teamdata = readTextFile("teams.txt")

 //User presses 2 on keyboard, this invokes menuCompareTeams which invokes compareTeams
 def menuOptionTwo(): Boolean = {
   //2 - compare 2 teams selected by the user
   menuCompareTeams(compareTeams)
   true
 }

 //Function which displays the results of compareTeams
 def menuCompareTeams(f: (String, String) => ((String, Int), (String, Int), String)) = {
        val input = f(readLine("Enter first team to compare>"),
                      readLine("Enter second team to compare>"))
        println(s"""|Team 1: ${input._1._1} - Points: ${input._1._2}
                    |Team 2: ${input._2._1} - Points: ${input._2._2}
                    |${input._3}""".stripMargin)           
 }
   
 ///Function which compares the 2 teams - invoked by menuCompareTeams
 def compareTeams(team1: String, team2: String): ((String, Int), (String, Int), String) = {
   def lastPoints(list: List[Int]): Int = list match {
     case Nil => throw new Exception("Empty list")
     case h :: Nil => h
     case _ :: tail => lastPoints(tail)
   }

   val team1Points = teamdata.get(team1) match{
     case Some(p) => lastPoints(p)
     case None => 0
   }

   val team2Points = teamdata.get(team2) match{
     case Some(p) => lastPoints(p)
     case None => 0
   }

   val pointsComparison = if(team1Points > team2Points){
     "The team who finished higher is: " + team1 + ", their total points tally for last season was: " + team1Points + ". There was a difference of " + (team1Points-team2Points) + " points between the two teams."
   }
   else if(team1Points == team2Points){
     "The teams had equal points last season: " + (team1Points|team2Points)
   }
   else{
     "The team who finished higher is: " + team2 + ", their total points tally for last season was: " + team2Points + ". There was a difference of " + (team2Points-team1Points) + " points between the two teams."
   }

   ((team1, team1Points), (team2, team2Points), pointsComparison)
  
 }

例如用户输入“Manchester United”和“Manchester City”时的正确输出如下所示:

第 1 队:曼联 - 积分:94

第 2 队:曼城 - 积分:88

排名靠前的球队是:曼联,他们上赛季的总积分是:94,两队相差6分。

有没有更好或更实用的方法来做我目前正在做的比较 2 个团队的事情?

编辑:我已根据 Alex 的建议编辑了问题。

【问题讨论】:

  • 带有多个问题的超长文本。我想建议你把它分成多个问题。从基础开始:如何更好地根据赛季成绩比较两支球队。
  • @AlexFruzenshtein 感谢您的反馈,我已根据您的建议编辑了问题。

标签: scala functional-programming maps comparison


【解决方案1】:

“更多功能”

您确实拥有的一个“副作用”是为空列表引发异常。如果这确实是一个例外情况,那么lastPoints 应该返回一个Try[Int]。除此之外,您保持引用透明性,使用模式匹配并使用递归函数,因此您无法获得“更多功能”。

“更好”

您可以在lastPoints 中使用List#lastOption(假设您不抛出异常)而不是自己编写:

val lastPoints = (_ : List[Int]).lastOption

然后可以按如下方式使用:

val getPoints = 
  (team : String) => teamdata.get(team)
                             .flatMap(lastPoints)
                             .getOrElse(0)

val team1Points = getPoints(team1)
val team2Points = getPoints(team2)

一般来说,在尝试“自己动手”之前,我总是先寻找解决我问题的收集方法。通过依赖 lastOption、flatMap 和 getOrElse,可以减少 bug 潜伏的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    相关资源
    最近更新 更多