title: Collection extension method which preserved both element type A and representation type Repr
body: <p>As a follow up to my <a href="https://stackoverflow.com/questions/20426411/creating-extension-methods-for-seqlike/20427464">previous question</a>, can I devise <em>one</em> implicit class that handles two types of <code>SeqLike</code> extensions:</p>
  
  <pre><code>import collection.SeqLike
  import collection.generic.CanBuildFrom
  
  implicit class Test[A, Repr](val sq: SeqLike[A, Repr]) extends AnyVal {
    // no constraints on Repr
    def foo[B](f: A =&gt; B)(implicit ord: Ordering[B]): Repr = sq.sortBy(f)
  
    // constraint that actually sq is Repr
    def bar[B, To](fun: (A, A) =&gt; B)(implicit cbf: CanBuildFrom[Repr, B, To]): To = {
      val b = cbf(sq)  // NO!
      // ...
      b.result
    }
  }
  </code></pre>
  
  <p>The <code>bar</code> method doesn't compile because we are missing the constraint that <code>typeOf(sq) == Repr</code>. As others have pointed out, if I change the constructor to <code>sq: Repr</code>, we lose the connection to type <code>A</code>.</p>
  
  <p>Right now, <code>Repr</code> is disconnected. For example:</p>
  
  <pre><code>// in Test:
  def isSortedBy[B](fun: A =&gt; B)(implicit ord: Ordering[B]): Boolean =
    sq.sliding(2, 1).forall {
      case a +: b +: _  =&gt; ord.lteq(fun(a), fun(b))
      case _            =&gt; true  // happens when it size == 1
    }
  
  [error] Test.scala: inferred type arguments [T,Equals] do not conform to method 
                      unapply's type parameter bounds 
                      [T,Coll &lt;: scala.collection.SeqLike[T,Coll]]
  [error]         case a +: b +: _  =&gt; ord.lteq(fun(a), fun(b))
  [error]                ^
  </code></pre>