Avertissement: ceci fait partie d'un devoir. Je veux implémenter le flatMap pour l'objet List personnalisé. J'ai implémenté la carte avec succès, mais j'ai un problème avec flatmap. Je ne sais pas comment aplatir la liste des listes que je reçois de la carte. Je ne sais pas si je devrais vraiment utiliser la carte du tout.Implémentez la fonction 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
}
}
+1 pour avis de non-responsabilité. SO devrait avoir une étiquette pour cela, ou peut-être qu'ils le font. –
ils l'ont, mais il dit qu'il est obsolète – LearnToMath