Note that there are some explanatory texts on larger screens.

plurals
  1. POimplementing a per-digit counter using the list monad
    text
    copied!<p>So, I was looking at the question <a href="https://stackoverflow.com/questions/1855561/implementing-a-factorisation-method-in-haskell">here</a>, and built a rather ugly solution for the problem. While trying to clean it up, I started investigating list comprehensions and the list monad. What I decided to do was to implement a per-digit counter using the list monad. Given an input sequence of digits, <code>[1, 2]</code>, I wanted to generate an output sequence that looked something like:</p> <pre><code>[ [ 0, 0], [ 0, 1 ], [ 0, 2 ], [ 1, 0 ], [ 1, 1 ], [ 1, 2 ] ] </code></pre> <p>That is, I'd iterate over all possible values of all elements in the list in that range.</p> <p>The haskell.org <a href="http://www.haskell.org/all_about_monads/html/listmonad.html" rel="nofollow noreferrer">list monad documentation</a> says:</p> <blockquote> <p>The bound function is applied to all possible values in the input list and the resulting lists are concatenated to produce a list of all possible results.</p> </blockquote> <p>Great! Looks perfect... Here's the code I wrote to produce the solution:</p> <pre><code>count :: [Integer] -&gt; [[Integer]] count [] = [] count (x:xs) = -- get all possible sequences for the remaining digits let remDigits :: [[Integer]] remDigits = count xs in -- pull out a possible sequence for the remaining digits do nextDigits &lt;- remDigits -- pull out all possible values for the current digit y &lt;- [0..x] -- record that "current digit" : "remaining digits" is -- a valid output. return (y:nextDigits) </code></pre> <p>But calling <code>count</code> with anything produces the empty list, and I don't know why. What am I missing?</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