Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>First of all pls refactore my code Haskell-way. I already know one magic refactring:</p> <pre><code>Control.Monad.replicateM n [0,1] </code></pre> <p>but this solution is not good for studying purposes :)</p> </blockquote> <p>Actually, while I certainly wouldn't expect someone new to Haskell to come up with such a solution, I think that <em>understanding</em> this version would be <em>very</em> good for studying purposes.</p> <p>The regular <code>replicate</code> function is pretty simple: It creates a list of the same element repeated some number of times. This is also the first step of what <code>replicateM</code> does:</p> <pre><code>&gt; replicate 2 ["0", "1"] [["0", "1"], ["0", "1"]] </code></pre> <p>The second step of what <code>replicateM</code> does is "sequence" the list according to the <code>Monad</code> of the elements, turning something a list of monadic values <code>[m a]</code> into a monadic list of values <code>m [a]</code>. What this does is "combine" the structure of each monadic value in some sense, where the specific meaning of "combine" depends on the specific monad.</p> <p>As a <code>Monad</code>, lists represent something like <em>trying multiple possibilities</em>. So when we "sequence" the values, that means that at each step, every possibility is tried separately, and all possible results are collected.</p> <p>So, <code>["0", "1"]</code> is a monadic value representing trying two different possibilities. <code>[["0", "1"], ["0", "1"]]</code> is a list of that monadic value repeated twice. To sequence that list, we take each possibility from the first element of the list, use it as the head of the result list, then continue until reaching the end. Because each group of possibilities is the same, the final result is all the possible combinations of each possible item:</p> <pre><code>&gt; replicateM 2 ["0", "1"] [["0","0"],["0","1"],["1","0"],["1","1"]] </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