我正在编写一个函数,根据数据确定出生在gender
的具有指定birthYear
(“M”或“F”)的人是否还活着文件(csvData)看起来像这样:
(“1930,”67“,”76“)
(“1950,”65“,”77“)
(“1970,”64“,”76“)
其中:
第一个数字代表一年
第二个代表男性的预期寿命
第三个代表女性的预期寿命
示例:
“1930年出生的人的预期寿命为67岁。”
def expectedAlive(gender: String, birthYear: Int, currentYear: Int): Boolean = {
val age = currentYear-birthYear //gets the person's age
if(gender == "F")//checks for male of female in order to acces the right element
if(csvData.contains(birthYear.toString)//checks if year exists in the database
if(age < csvData.filter(x => x(2).toInt)) //attempts to compare the 3 element in list with age.
else...
else ...
else ...
这是我的问题:
我看过并询问过如何将字符串与int进行比较。虽然我理解为什么它会给我一个错误,但我不知道如何绕过它。 我认为这样做的方法是编写if / else语句。但是,据我所知,Scala具有强大的语法和功能。
有没有更好的方法来解决这个问题?
答案 0 :(得分:1)
像
这样的东西val data = List(List("1930", "67", "76"),
List("1950", "65", "77"),
List("1970", "64", "76"))
def expectedAlive(gender: String, birthYear: Int, currentYear: Int): Boolean = {
val birthString = birthYear.toString
val entry = data.find(_(0) == birthString)
val age = currentYear - birthYear
entry match {
case None => true //?? or throw an exception
case Some(List(_, maleLifespan, femaleLifespan)) => gender match {
case "M" => age <= maleLifespan.toInt
case "F" => age <= femaleLifespan.toInt
}
}
}
测试:
expectedAlive("M", 1930, 1996) //> res1: Boolean = true
expectedAlive("M", 1930, 2016) //> res2: Boolean = false
expectedAlive("F", 1950, 2015) //> res3: Boolean = true
expectedAlive("F", 1950, 2035) //> res4: Boolean = false
虽然有案例类,我们可以稍微整理一下:
case class Expectancy(year:Int, male:Int, female:Int)
val data = List(List("1930", "67", "76"),
List("1950", "65", "77"),
List("1970", "64", "76"))
val expectancies = data.map(e => Expectancy(e(0).toInt, e(1).toInt, e(2).toInt))
def expectedAlive(gender: String, birthYear: Int, currentYear: Int): Boolean = {
val age = currentYear - birthYear
val entry = expectancies.find(_.year == birthYear)
entry match {
case None => true //?? or throw an exception
case Some(e) => gender match {
case "M" => age <= e.male
case "F" => age <= e.female
}
}
}
(也通过测试)