-1

试图创建一个递归函数来打印数组的最高元素。

它是说它需要一个;之前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)
}
4

6 回答 6

9

这看起来像家庭作业,我只是基于这是 Odersky 在线 Coursera 课程中第一个家庭作业的一部分。

如果不是,请告诉我,但我会假设它是,所以我只是给出一个提示.. 看看你的 if/else 分支是如何组织的。

课程的第一周视频涵盖了 Scala 的分号推断。

于 2012-09-20T03:03:55.717 回答
6

一些正确的格式会告诉你问题:

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 中不需要它们。换句话说,您可以编写不需要它们的代码,或者您可以根据需要将它们用于某些事情。

于 2012-09-20T03:04:28.647 回答
4

Scala 使用分号,但它们在行尾是可选的。也就是说,如果分号在行尾是合法的(即该行不在表达式的中间结束(如a +)),则会自动插入分号。

也就是说,尽管出现错误消息,但您的问题实际上与分号无关。您的问题是,如果您想在 if 或 else 块中包含多个表达式,则需要大括号。

PS:请注意,使用可变的非局部变量来跟踪您的状态在设计上是一个坏主意,并且如果您多次调用您的方法(不重置其间的变量)会给您带来麻烦。

PPS:你应该仔细看看你在xs.tail空的时候做什么。你确定逻辑正确吗?

于 2012-09-20T03:07:01.417 回答
2

这是 Coursera“使用 Scala 进行函数式编程”的示例作业。您有此类问题的课程论坛。

您应该更深入地研究递归并在没有任何额外 var 的情况下解决此任务。Lists 源中有关于辅助函数的提示。用它。

于 2012-09-20T11:29:21.023 回答
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)  
  }
于 2016-08-18T08:36:07.243 回答
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)        
}
于 2016-10-28T10:33:12.663 回答