Scala 从列表中删除元素
Scala drop elements from a list
给定以下列表:
sealed abstract class IntList
case class Empty() extends IntList
case class Element(n: Int, tail: IntList) extends IntList
- 定义函数drop(n, xs)。
- 它应该 return 列表 xs,没有前 n 个元素。
这是我试过的:
def drop(n: Int, xs: IntList): IntList = xs match {
case _ if n == 0 => xs
case xs : Empty => Empty()
case xs : Element => Element(xs.tail.n, drop(n-1, xs.tail))
}
但是
error: value n is not a member of Solution.IntList
case xs : Element => Element(xs.tail.n, drop(n-1, xs.tail))
我猜这是因为 xs.tail 不再保证是 Element
我应该怎么做?谢谢
差不多了,但是不需要在 Element()
中包装递归调用
def drop(n: Int, xs: IntList): IntList = xs match {
case _ if n == 0 => xs
case xs : Empty => xs
case xs : Element => drop(n-1, xs.tail)
}
这避免了调用 xs.tail.n
的需要,您已经将其确定为问题所在!
对于 Empty 情况,您也可以只 return xs
,以避免创建新实例。通常人们会使用 case object
来表示这样的空壳。
给定以下列表:
sealed abstract class IntList
case class Empty() extends IntList
case class Element(n: Int, tail: IntList) extends IntList
- 定义函数drop(n, xs)。
- 它应该 return 列表 xs,没有前 n 个元素。
这是我试过的:
def drop(n: Int, xs: IntList): IntList = xs match {
case _ if n == 0 => xs
case xs : Empty => Empty()
case xs : Element => Element(xs.tail.n, drop(n-1, xs.tail))
}
但是
error: value n is not a member of Solution.IntList
case xs : Element => Element(xs.tail.n, drop(n-1, xs.tail))
我猜这是因为 xs.tail 不再保证是 Element
我应该怎么做?谢谢
差不多了,但是不需要在 Element()
def drop(n: Int, xs: IntList): IntList = xs match {
case _ if n == 0 => xs
case xs : Empty => xs
case xs : Element => drop(n-1, xs.tail)
}
这避免了调用 xs.tail.n
的需要,您已经将其确定为问题所在!
对于 Empty 情况,您也可以只 return xs
,以避免创建新实例。通常人们会使用 case object
来表示这样的空壳。