0
我有以下斯卡拉代码来回答问题4(在清单上实现dropWhile,它将从列表前缀中删除元素,只要它们与谓词匹配)第3章Functional Programming In Scala:将方法添加到列表并传递匿名参数
object Chapter3 {
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
def dropWhile[A](l: List[A], f: A => Boolean): List[A] =
l match {
case Nil => sys.error("cannot drop from empty list")
case Cons(h, t) if f(h) => dropWhile(t, f)
case _ => l
}
}
def main(args : Array[String]) {
def smallerThanThree(i: Int): Boolean = i < 3
println(List.dropWhile(List(1, 2, 3, 4, 5), smallerThanThree))
// How can I call this directly on the list with anonymous function like below?
println(List(1, 2, 3, 4, 5).dropWhile(i => i < 3))
// => Should return List(3, 4, 5) or Cons(3, Cons(4, Cons(5, Nil))).
}
}
我想要做的是两方面的:列表对象(List(1,2,3,4,5).dropWhile([f: A => Boolean])
)上
- 呼叫
dropWhile
而是采用List.dropWhile([List[A]], [f: A => Boolean])
- 传递,而不是限定的功能
smallerThanThree
并传递该匿名方法(i => i < 3
)。
现在,这给出了错误:
error: value dropWhile is not a member of Main.List[Int]
而匿名函数不也行。当我做
println(List.dropWhile(List(1, 2, 3, 4, 5), i => i < 3))
它给人的错误:
error: missing parameter type
谁能解释,如果以上两点可以完成,如果是这样,怎么样?
感谢您的帮助。要添加到你的答案,你实际上也可以对类似'i => i <3'的匿名函数进行类型干涉。如果签名(和实现)更改如下,则可以这样做:'def dropWhile [A](l:List [A])(f:A => Boolean):List [A]'。然后你可以改变trait中的方法:'def dropWhile(f:A => Boolean):List [A] = List.dropWhile(this)(f)'。您不必指定类型,可以使用'dropWhile'如下:'println(List(1,2,3,4,5).dropWhile(i => i <3))'。 –