![](/img/trans.png)
[英]Spark java.lang.UnsupportedOperationException: empty collection
[英]How to resolve java.lang.UnsupportedOperationException: tail of empty list error
當 list1 和 list 2 都為空時,我收到此錯誤消息。
def append(list1: List[Int], list2: List[Int]): List[Int] = {
if list1.isEmpty && list2.isEmpty then
0
if list1.nonEmpty && list2.isEmpty then
list1
else if list1.isEmpty && list2.nonEmpty then
list2
else if list1.tail.isEmpty && list2.nonEmpty then
list1.head::list2
else
val x = append(list1.tail, list2)
list1.head::x
}
test("append", append, "list1", "list2")
具體問題是缺少else
,但是如果您使用match
,這會更干凈:
def append(list1: List[Int], list2: List[Int]): List[Int] =
(list1, list2) match {
case (Nil, Nil) =>
Nil
case (a, Nil) =>
x
case (Nil, x) =>
x
case (a::Nil, b) =>
a +: b
case (a::tail, b) =>
a +: append(tail, b)
}
要不就
def append(list1: List[Int], list2: List[Int]): List[Int] =
list1 match {
case Nil =>
list2
case a :: tail =>
a +: append(tail, list2)
}
但是這些都不是尾遞歸的,因此對於非常大的列表會有性能和 memory 問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.