Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To understand the result, you need to understand the <code>Comonad[NonEmptyList]</code> instance. <code>Comonad[W]</code> essentially provides three functions (the actual interface in Scalaz is a little different, but this helps with explanation):</p> <pre><code>map: (A =&gt; B) =&gt; W[A] =&gt; W[B] copure: W[A] =&gt; A cojoin: W[A] =&gt; W[W[A]] </code></pre> <p>So, <code>Comonad</code> provides an interface for some container <code>W</code> that has a distinguished "head" element (<code>copure</code>) and a way of exposing the inner structure of the container so that we get one container per element (<code>cojoin</code>), each with a given element at the head.</p> <p>The way that this is implemented for <code>NonEmptyList</code> is that <code>copure</code> returns the head of the list, and <code>cojoin</code> returns a list of lists, with this list at the head and all tails of this list at the tail.</p> <p>Example (I'm shortening <code>NonEmptyList</code> to <code>Nel</code>):</p> <pre><code>Nel(1,2,3).copure = 1 Nel(1,2,3).cojoin = Nel(Nel(1,2,3),Nel(2,3),Nel(3)) </code></pre> <p>The <code>=&gt;=</code> function is coKleisli composition. How would you compose two functions <code>f: W[A] =&gt; B</code> and <code>g: W[B] =&gt; C</code>, knowing nothing about them other than that <code>W</code> is a <code>Comonad</code>? The input type of <code>f</code> and the output type of <code>g</code> aren't compatible. However, you can <code>map(f)</code> to get <code>W[W[A]] =&gt; W[B]</code> and then compose that with <code>g</code>. Now, given a <code>W[A]</code>, you can <code>cojoin</code> it to get the <code>W[W[A]]</code> to feed into that function. So, the only reasonable composition is a function <code>k</code> that does the following:</p> <pre><code>k(x) = g(x.cojoin.map(f)) </code></pre> <p>So for your nonempty list:</p> <pre><code>g(Nel(1,2,3).cojoin.map(f)) = g(Nel(Nel(1,2,3),Nel(2,3),Nel(3)).map(f)) = g(Nel("Nel(1,2,3)X","Nel(2,3)X","Nel(3)X")) = BigInt(Nel("Nel(1,2,3)X","Nel(2,3)X","Nel(3)X").map(_.length).sum) = BigInt(Nel(11,9,7).sum) = 27 </code></pre>
 

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