Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I apply the enrich-my-library pattern to Scala collections?
    primarykey
    data
    text
    <p>One of the most powerful patterns available in Scala is the enrich-my-library* pattern, which uses implicit conversions to <em>appear</em> to add methods to existing classes without requiring dynamic method resolution. For example, if we wished that all strings had the method <code>spaces</code> that counted how many whitespace characters they had, we could:</p> <pre><code>class SpaceCounter(s: String) { def spaces = s.count(_.isWhitespace) } implicit def string_counts_spaces(s: String) = new SpaceCounter(s) scala&gt; "How many spaces do I have?".spaces res1: Int = 5 </code></pre> <p>Unfortunately, this pattern runs into trouble when dealing with generic collections. For example, a number of questions have been asked about <a href="https://stackoverflow.com/questions/4761386/scala-list-function-for-grouping-consecutive-identical-elements">grouping items sequentially with collections</a>. There is nothing built in that works in one shot, so this seems an ideal candidate for the enrich-my-library pattern using a generic collection <code>C</code> and a generic element type <code>A</code>:</p> <pre><code>class SequentiallyGroupingCollection[A, C[A] &lt;: Seq[A]](ca: C[A]) { def groupIdentical: C[C[A]] = { if (ca.isEmpty) C.empty[C[A]] else { val first = ca.head val (same,rest) = ca.span(_ == first) same +: (new SequentiallyGroupingCollection(rest)).groupIdentical } } } </code></pre> <p>except, of course, it <em>doesn't work</em>. The REPL tells us:</p> <pre><code>&lt;console&gt;:12: error: not found: value C if (ca.isEmpty) C.empty[C[A]] ^ &lt;console&gt;:16: error: type mismatch; found : Seq[Seq[A]] required: C[C[A]] same +: (new SequentiallyGroupingCollection(rest)).groupIdentical ^ </code></pre> <p>There are two problems: how do we get a <code>C[C[A]]</code> from an empty <code>C[A]</code> list (or from thin air)? And how do we get a <code>C[C[A]]</code> back from the <code>same +:</code> line instead of a <code>Seq[Seq[A]]</code>?</p> <p>*<sup> Formerly known as pimp-my-library.</sup></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload