title: How to takeWhile elements in a list wrapped in a monad
body: <p>Got a little puzzle I was wondering if you could help me clarify.</p>
  
  <p>Let's define a function that returns a list:</p>
  
  <pre><code>let f = replicate 3
  </code></pre>
  
  <p>What we want to do is map this function to an infinite list, concatenate the results, and then take only things that match a predicate.</p>
  
  <pre><code>takeWhile (&lt; 3) $ concatMap f [1..]
  </code></pre>
  
  <p>Great! That returns <code>[1,1,1,2,2,2]</code>, which is what I want.</p>
  
  <p>Now, I want to do something similar, but the function f now wraps its results in a Monad.  In my usecase, this is the IO monad, but this works for discussing my problem:</p>
  
  <pre><code>let f' x = Just $ replicate 3 x
  </code></pre>
  
  <p>To map and concat, I can use:</p>
  
  <pre><code>fmap concat $ mapM f' [1..5]
  </code></pre>
  
  <p>That returns: <code>Just [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5]</code></p>
  
  <p>If I want to use <code>takeWhile</code>, this still works:</p>
  
  <pre><code>fmap (takeWhile (&lt; 3) . concat) $ mapM f' [1..5]
  </code></pre>
  
  <p>Which returns: Just [1,1,1,2,2,2].  Great!</p>
  
  <p>But, if I make the list over which I map an infinite list this does not do what I expected:</p>
  
  <pre><code>fmap (takeWhile (&lt; 3) . concat) $ mapM f' [1..]
  </code></pre>
  
  <p>Seems like the <code>takeWhile</code> is never happening. Somehow, I'm not getting the lazy computation I was expecting. I’m a bit lost.</p>