简体   繁体   English

Scala中的空列表头

[英]Head of empty list in Scala

I've made this recursive metod in Scala that returns a list made of all distinct elements of another list. 我在Scala中创建了此递归方法,该方法返回由另一个列表的所有不同元素组成的列表。

object es20 extends App{

    def filledList:List[Int]=List()

    @scala.annotation.tailrec
    def distinct(l:List[Int]):List[Int] ={
        if (l.isEmpty) filledList
        if (filledList.forall(_!=l.head)) l.head::filledList

    distinct(l.tail)
    }
println(distinct(List(1,1,5,6,6,3,8,3))) //Should print List(1,5,6,3,8)
}

However, when I compile the code and then I run it, there's this exception: 但是,当我编译代码然后运行它时,会出现以下异常:

java.util.NoSuchElementException: head of empty list java.util.NoSuchElementException:空列表的头部

I thought that this exception was handle by the condition if (l.isEmpty ). 我认为此异常由条件if(l.isEmpty )处理。

How can I fix the code? 如何修复代码?

In Scala method returns last expression of the block. 在Scala方法中,返回该块的最后一个表达式。 In your case you have three expressions: two if-expressions which result in unit and call to distinct, so checks will be executed every time you call distinct, no matter if the list is empty or not. 在您的情况下,您具有三个表达式:两个if表达式会导致对unit和call的调用,因此无论列表是否为空,每次您调用distance都会执行检查。

To fix it you can use if / else construct, or pattern match on input list, or make operation on headOption. 要解决它,您可以在输入列表中使用if / else构造或模式匹配,或在headOption上进行操作。

Anyway I doubt if this code correct: you trying to check something on 'filledList' which is always empty 无论如何,我怀疑这段代码是否正确:您试图检查“ filledList”上始终为空的内容

You can fix this particular error by inserting else before the second if . 您可以通过在第二个if之前插入else来解决此特定错误。 However, as mentioned in the other answer, your code isn't correct, and won't work anyway, you need to rewrite it. 但是,如另一个答案中所述,您的代码不正确,无论如何都无法正常工作,您需要重写它。

Also, I understand, that you are just trying to write this function as an exercise (if not, just do list.distinct ), but I submit, that implementing quadratic solutions to trivially linear problems is never a good exercise to begin with. 另外,据我了解,您只是想将此功能编写为练习(如果不是,请执行list.distinct ),但是我认为,对平凡线性问题实施二次求解从来都不是一个好的练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM