title: Implement the flatMap function
body: <p>Disclaimer: this is a part of a homework assignment. 
  I want to implement the flatMap for the custom List object. I have successfully implemented map, but I have problem with flatMap. I do not know how to flatten the List of Lists that I get from map. I do not know if I really should use map at all.</p>
  
  <pre><code>trait List[+A] {
    /** The first element */
    def head: A
    /** The rest of the elements */
    def tail: List[A]
    def flatMap[B](f: A =&gt; List[B]): List[B]
    def map[B](f: A =&gt; B): List[B]
  
    // Concatenate two lists
    def concat[B &gt;: A](that: List[B]): List[B] = this match {
      case Empty =&gt; that
      case NonEmpty(head, tail) =&gt; 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 =&gt; List[B]): List[B] = Empty
    def map[B](f: Nothing =&gt; 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 =&gt; B): List[B] = {
  
      NonEmpty(f(head), tail.map(f))
  
    }
  def flatMap[B](f: A =&gt; List[B]): List[B] = {
      val a = this.map(f)
      for (x &lt;- a; y &lt;- x) yield y
    }
  }
  </code></pre>