2012-09-20 55 views
-1

試圖創建一個遞歸函數來打印數組的最高元素。遞歸方法不起作用。需要; ?

它說,它需要else maxi=xs.head;}max(xs.tail)

我沒想到斯卡拉採用半冒號,什麼時候應該使用它們,什麼是其他一些基本的語法規則。

var maxi = 0 
def max(xs: List[Int]): Int = {if (xs.isEmpty) throw new java.util.NoSuchElementException() 
     else if (xs.tail.isEmpty) maxi 
     else if (xs.tail.head > xs.head) maxi = xs.tail.head 
     max(xs.tail) 
     else maxi=xs.head 
     max(xs.tail) 
} 

回答

4

Scala使用分號,但它們在行尾是可選的。也就是說,如果分號在行尾是合法的(即行不會在表達式的中間結束(例如a +)),則會自動插入一個分號。

也就是說,儘管出現錯誤消息,但您的問題實際上並沒有與分號有任何關係。你的問題是如果你想在if或else塊中有更多的表達式,你需要大括號。 PS:請注意,使用可變非局部變量來跟蹤你的狀態在設計方面是一個壞主意,如果你多次調用你的方法(不需要重新設置它們之間的變量),會給你帶來麻煩。

PPS:您應該仔細看看xs.tail爲空時的操作。你確定這個邏輯是正確的嗎?

7

這看起來像功課,我只是一個事實,即這是Odersky的在線Coursera課程第一家庭作業的一部分,這個基礎。

如果不是,請告訴我,但我會假設它是這樣的,所以我會給出一個提示..看看你的if/else分支是如何組織的。

該課程的第一週視頻涵蓋了Scala的分號推理。

5

一些適當的格式會顯示您的問題:

var maxi = 0 
def max(xs: List[Int]): Int = { 
    if (xs.isEmpty) 
    throw new java.util.NoSuchElementException() 
    else if(xs.tail.isEmpty) 
    maxi 
    else if(xs.tail.head > xs.head) { // <-- need this opening brace 
    maxi = xs.tail.head    // because there are two lines 
    max(xs.tail)     // in the body of the if-statement 
    }         // <-- and this closing brace 
    else { 
    maxi=xs.head 
    max(xs.tail) 
    } 
} 

分號是Scala代碼有效,但他們並不需要他們在Java的程度。換句話說,你可以編寫不需要它們的代碼,或者如果你願意,你可以使用它們做某些事情。

2

這是Coursera的Scala功能編程示例作業。你有這類問題的課程論壇。

您應該深入探討遞歸併解決此任務而無需任何附加的變量。列表中提供了有關幫助函數的提示。用它。

+1

我同意不使用的可變全局狀態('maxi'),當它在暗示說,作爲隱含在演習中指定「您可能需要定義一個輔助手段」。 –

1
def max(xs: List[Int]): Int = { 
    def loop(a: Int, b: List[Int]): Int = { 
    if (b.tail.isEmpty) 
     if (a >= b.head) a 
     else b.head 
    else 
     if (a >= b.head) loop(a, b.tail) 
     else loop(b.head, b.tail) 
    } 
    if (xs.isEmpty) throw new java.util.NoSuchElementException() 
    else loop(xs.head, xs.tail) 
    } 
0
def max(xs: List[Int]): Int = { 
    def maxNew(xs: List[Int], maxx: Int): Int ={ 
    if(xs.isEmpty) maxx else { 
    if (maxx<=xs.head) 
     maxNew(xs.tail, xs.head) 
    else 
     maxNew(xs.tail, maxx) 
    } 
} 

    if(xs.isEmpty) throw new java.util.NoSuchElementException() 
    else maxNew(xs,0)   
} 
+0

很容易,並使用遞歸。 –