【问题标题】:Scala: removing a list element by valueScala:按值删除列表元素
【发布时间】:2020-09-27 11:49:00
【问题描述】:

我最近开始在 SCALA 上学习函数式编程。我正在寻求有关创建函数的帮助,该函数以 0 作为参数的列表(在以下情况下为 lst)并返回不带 0 的新列表(newlst)。目前我创建了类似下面的 Demo 但由于不匹配异常而无法编译,有什么想法可以修复它吗?谢谢!

object Demo{
  def main(args: Array[String]) {
    val lst = List(0, 1, 2, 0, 3);
    def deletingZeros(list: List[Int]): List[Int] = {
      val newlst = list.filter(_ > 0)
    }
  }
}

【问题讨论】:

  • 编译错误到底说了什么?你需要从deletingZeros返回一个List[Int],你可能想返回newlst
  • 您刚刚忘记在deletingZeros 中返回值,现在它返回Unit,但根据您的签名,它应该返回List[Int],尝试删除val newlst = 它应该会有所帮助。

标签: list scala functional-programming


【解决方案1】:

简单错误,您没有从函数返回值。这样做之一:

def deletingZeros(list: List[Int]): List[Int] = {
  val newlst = list.filter(_ > 0)

  newlst
}

或者只是

def deletingZeros(list: List[Int]): List[Int] = {
  list.filter(_ > 0)
}

甚至只是

def deletingZeros(list: List[Int]): List[Int] =
  list.filter(_ > 0)

【讨论】:

    【解决方案2】:

    欢迎来到 Scala :)

    TL/DR

    这可能就是你要找的东西:

    object Demo{
      def main(args: Array[String]) {
        val lst = List(0, 1, 2, 0, 3);
        def deletingZeros(list: List[Int]): List[Int] =
          list.filter(_ > 0)
        val newlst = deletingZeros( lst )
        }
      }
    }
    

    故障

    函数的返回类型必须与其最后一条语句的类型相匹配。内部函数deletingZeros 应返回IntList,但赋值表达式val newlst = ... 的类型为Unit。那不匹配。有两种方法可以解决这个问题。我们可以返回分配的变量,如下所示:

       def deletingZeros(list: List[Int]): List[Int] = {
          val newlst = list.filter(_ > 0)
          newlst
        }
    

    因为变量的类型就是它的值的类型。或者,由于我们不使用变量 newlst,我们可以删除它,产生:

        def deletingZeros(list: List[Int]): List[Int] = {
          list.filter(_ > 0)
        }
    

    我们可以反过来简化为

      def deletingZeros(list: List[Int]): List[Int] = list.filter(_ > 0)
    

    然后我们可以使用lst 作为参数调用这个函数,并将这个调用的结果分配给newlst,从而得到上面的完整示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-13
      • 2020-03-14
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多