max() 应该为空列表返回什么? [英] What should max() return for empty lists?

查看:50
本文介绍了max() 应该为空列表返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

得到 java.util.NoSuchElementException: head of empty list 所以我试图检查它.但现在我得到 [info] - 最多几个数字 *** 失败 ***[信息] 0 不等于 7 (ListsSuite.scala:128)

def max(xs: List[Int]): Int = {if xs.isEmpty 0//我能做什么?否则 if (xs.head > max(xs.tail)) max(xs.tail)否则最大(xs.tail)}

  1. 测试用例失败,因为我的测试错误.
  2. 对于我的班级同学,Coursera 荣誉代码提醒:>

    • 我只会注册一个帐户.我对作业、测验的回答和考试将是我自己的工作(明确的作业除外允许合作).
    • 我不会为家庭作业、测验做解答或其他任何人都可以参加的考试.这包括两种解决方案由我写的,以及任何官方提供的解决方案课程工作人员.
    • 我不会从事任何其他活动不诚实地改善我的结果或不诚实地改善/伤害其他人的结果.

解决方案

在一般情况下,除了 None 之外,您不能返回任何内容,因为通常空序列没有有意义的默认最大值.然而,情况并非总是如此.例如,您可能想在人员列表中找到最高工资,在这种情况下,如果列表为空,则将其设为 0 是有意义的;但是,没有简单的方法可以通用地实现这种默认值逻辑(您必须使用类型类和包装值之类的东西);现在最好的办法是简单地使用 Option[Int]:

def max(xs: List[Int]): Option[Int] = xs match {情况为零 =>没有任何情况 x :: Nil =>一些(x)案例 x :: xs =>一些(x max max(xs))}

然后,您可以轻松地回退到调用站点的默认值:

val posOrNeg = List(-5, -2, 1, 4, 10)max(posOrNeg)//=>一些(10)val posOrNeg = List.empty[Int]max(posOrNeg)//=>没有任何val onlyPos = List(1, 2, 3)max(onlyPos).getOrElse(0)//=>3val onlyPos = List.empty[Int]max(onlyPos).getOrElse(0)//=>0

奖励:此外,您可以让 max 处理任何数值列表:

def max[T: Numeric](xs: List[T]): Option[T] = xs match {情况为零 =>没有任何情况 x :: Nil =>一些(x)案例 x :: xs =>一些(x max max(xs))}

或者实际上任何合适的由数值组成的数据结构,使用比List更通用的类型,但我会留给你.

但请记住:无论您选择哪种解决方案,都要尽量避免 try 和一般的异常——异常不符合惯用的函数式编程的精神(即使某些库函数由于各种原因偶尔会使用它们).

Got java.util.NoSuchElementException: head of empty list so I tried to check for that. But now I get [info] - max of a few numbers *** FAILED *** [info] 0 did not equal 7 (ListsSuite.scala:128)

def max(xs: List[Int]): Int = {
  if xs.isEmpty 0 // What can I do? 
  else if (xs.head > max(xs.tail)) max(xs.tail)
  else max(xs.tail)
}

edit:

  1. The test case failed because my test was wrong.
  2. For my classmates, a reminder of the Coursera honor code:

    • I will register for only one account. My answers to homework, quizzes and exams will be my own work (except for assignments that explicitly permit collaboration).
    • I will not make solutions to homework, quizzes or exams available to anyone else. This includes both solutions written by me, as well as any official solutions provided by the course staff.
    • I will not engage in any other activities that will dishonestly improve my results or dishonestly improve/hurt the results of others.

解决方案

In the general case, you can't return anything but None because an empty sequence in general has no meaningful default max value. That, however, is not necessarily the case all the time; for example you might want to find the maximum salary in a list of people, in which case it would make sense to say it's 0 if the list is empty; however, there is no trivial way to implement such default value logic generically (you'd have to use stuff like type classes and wrapped values); your best bet now is to simply use Option[Int]:

def max(xs: List[Int]): Option[Int] = xs match {
  case Nil => None
  case x :: Nil => Some(x)
  case x :: xs => Some(x max max(xs))
}

Then, you can easily fall back to a default value at the call site:

val posOrNeg = List(-5, -2, 1, 4, 10)
max(posOrNeg) // => Some(10)
val posOrNeg = List.empty[Int]
max(posOrNeg) // => None

val onlyPos = List(1, 2, 3)
max(onlyPos).getOrElse(0) // => 3
val onlyPos = List.empty[Int]
max(onlyPos).getOrElse(0) // => 0

Bonus: Also, you can make your max work on any list of numeric values:

def max[T: Numeric](xs: List[T]): Option[T] = xs match {
  case Nil => None
  case x :: Nil => Some(x)
  case x :: xs => Some(x max max(xs))
}

or in fact any suitable data structure made up of numeric values by using a type more general than List, but I'll leave that up to you.

But keep in mind: no matter which solution you opt for, always try to avoid try and exceptions in general — exceptions are not in the spirit of idiomatic functional programming (even though even some library functions use them occasionally for various reasons).

这篇关于max() 应该为空列表返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆