I need to implement my own List class in Scala. I’ve implemented:
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"
}
And now I need to implement filter, flatMap and Map methods:
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] = {
}
For instance method filter(predicate: A => Boolean): List[A] how can I iterate through every element in this list? How can I check if given predicate is true or false? (tried if(predicate(head)) – doesn’t work for some reason.)
Thank you for help.
You need to traverse the elements with
headandtail:This implementation can be defined in
List. The last thing you need for this is thereversemethod. You can implement it the same way asfilter– use an inner method to traverse all elements.Instead of
reverseyou can use a non-tail-recursive implementation, which must not reversed and can be implemented in the subclasses:The other methods can be defined in a similar way.