免责声明:这是家庭作业的一部分。我想为自定义 List 对象实现 flatMap。我已经成功实现了地图,但是我对 flatMap 有问题。我不知道如何展平从地图中获得的列表列表。我不知道我是否真的应该使用地图。
trait List[+A] {
/** The first element */
def head: A
/** The rest of the elements */
def tail: List[A]
def flatMap[B](f: A => List[B]): List[B]
def map[B](f: A => B): List[B]
// 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)
}
}
case object Empty extends List[Nothing] {
def head = throw new UnsupportedOperationException("Empty.head")
def tail = throw new UnsupportedOperationException("Empty.tail")
def flatMap[B](f: Nothing => List[B]): List[B] = Empty
def map[B](f: Nothing => B): List[B] = Empty
override def toString = "Empty"
}
case class NonEmpty[A](head: A, tail: List[A]) extends List[A] {
def map[B](f: A => B): List[B] = {
NonEmpty(f(head), tail.map(f))
}
def flatMap[B](f: A => List[B]): List[B] = {
val a = this.map(f)
for (x <- a; y <- x) yield y
}
}