2016-02-11 41 views
-3

我正在寫一個函數,用於根據數據確定出生在birthYear中的具有指定gender(「M」或「F」)的人是否有生命文件(csvData),看起來像這樣:使用scala的工具編寫更好的代碼

( 「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

請問你能分享一下你的csvData obj ect看起來像? – rancidfishbreath

+0

這是一個列表,就像一個頂部 –

+0

對不起,你要求的對象。這是一個變量:val csvData = fromFile(「file-name.csv」)。它直接從文件讀取並將其放入列表中。 –

回答

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類,我們可以把它打掃乾淨了一點:

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

(通過測試過)

+0

你如何能夠比較字符串和整數?是通過將年齡與新創建的列表進行比較(例如,案例Some(List(_,maleLifeSpan ...))? –

+0

第一個版本具有顯式的'maleLifeSpan.toInt'來執行轉換,第二個轉換'String'當從'data'列表創建'expectancies'列表時,它將'Ints'與'Int'相比較,所以它始終將'Ints'與'Int'(或'String's與' ) –