尝试创建一个打印数组最高元素的递归函数.
它说,它需要;之前else maxi=xs.head和}之后max(xs.tail)
我不认为scala使用半冒号,你何时应该使用它们以及其他一些基本的句法规则.
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)
}
Run Code Online (Sandbox Code Playgroud)
这看起来像是家庭作业,我的基础是这是Odersky在线Coursera课程中第一个家庭作业的一部分.
如果不是,请告诉我,但我会假设它是,所以我只是给出一个提示..看看你的if/else分支是如何组织的.
课程中的第一周视频涵盖了Scala的分号推断.
一些正确的格式将显示问题:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
分号在Scala代码中是有效的,但它们不需要它们在Java中.换句话说,您可以编写不需要它们的代码,或者如果您愿意,可以将它们用于某些事情.