我需要在 Scala 中实现我自己的 List 类。我已经实现:
trait List[+A] {
/** The first element */
def head: A
/** The rest of the elements */
def tail: List[A]
def map[B](f: A => B): List[B]
def flatMap[B](f: A => List[B]): List[B]
def filter(f: A => Boolean): List[A]
// Concatenate two lists
def concat[B >: A](that: List[B]): List[B] = this match {
case Empty => that
case NonEmpty(head, tail) => NonEmpty(head, tail concat that)
}
}
/** The empty list, also known as Nil */
case object Empty extends List[Nothing] {
def head = throw new UnsupportedOperationException("Empty.head")
def tail = throw new UnsupportedOperationException("Empty.tail")
def map[B](f: Nothing => B): List[B] = Empty
def flatMap[B](f: Nothing => List[B]): List[B] = Empty
def filter(f: Nothing => Boolean): List[Nothing] = Empty
override def toString = "Empty"
}
现在我需要实现 filter、flatMap 和 Map 方法:
case class NonEmpty[A](head: A, tail: List[A]) extends List[A] {
//def map[B](f: A => B): List[B] = ???
//def flatMap[B](f: A => List[B]): List[B] = ???
def filter(predicate: A => Boolean): List[A] = {
}
例如方法filter(predicate: A => Boolean): List[A]
我如何遍历这个列表中的每个元素?如何检查给定谓词是真还是假?(试过if(predicate(head))
- 由于某种原因不起作用。)谢谢你的帮助。