Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For lists (such as <code>tossDie</code>), the <code>do</code> notation acts like a list comprehension -- that is to say, as if each variable binding were a nested <code>foreach</code> loop.</p> <p>The do-block expression:</p> <pre><code>toss2Dice = do { n &lt;- tossDie; m &lt;- tossDie; return (n+m) } </code></pre> <p>does the same thing as this list comprehension:</p> <pre><code>toss2Dice = [ n+m | n &lt;- tossDie, m &lt;- tossDie ] </code></pre> <p>The result is comparable to the following imperative pseudocode:</p> <pre><code>toss2Dice = [] foreach n in tossDie: foreach m in tossDie: toss2Dice.push_back(n+m) </code></pre> <p>except that the Haskell examples generate their results lazily, on demand, instead of eagerly and all at once.</p> <hr> <p>If you look at the monad instance for lists, you can see how this works:</p> <pre><code>instance Monad [] where xs &gt;&gt;= f = concat (map f xs) return x = [x] </code></pre> <p>Starting at the beginning of the <code>do</code> block, each variable binding creates a loop over the remainder of the block:</p> <pre><code>do { n &lt;- tossDie; m &lt;- tossDie; return (n+m) } ===&gt; tossDie &gt;&gt;= \n -&gt; do { m &lt;- tossDie; return (n+m) } ===&gt; concat ( map (\n -&gt; do { m &lt;- tossDie; return (n+m) }) tossDie ) </code></pre> <p>Note that <code>map</code> function iterates over the items in the list <code>tossDie</code>, and the results are <code>concat</code>enated. The mapping function is the remainder of the <code>do</code> block, so the first binding effectively creates an outer loop around it.</p> <p>Additional bindings create successively nested loops; and finally, the <code>return</code> function creates a singleton list out of each computed value <code>(n+m)</code> so that the "bind" function <code>&gt;&gt;=</code> (which expects lists) can concatenate them properly.</p>
 

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