title: Why is this code not constant-space?
body: <p>I'm learning Haskell currently (being a programmer by trade, but this is my first attempt at a functional language).</p>
  
  <p>I want to write a function that scans a list and returns both the minimum and maximum element of that list. Sort of what the Prelude functions <code>minimum</code> and <code>maximum</code> do, but both at the same time. I've come up with the following code:</p>
  
  <pre><code>import Data.List
  
  -- Declaration of rand
  
  minMax :: [Int] -&gt; Maybe (Int, Int)
  minMax []   = Nothing
  minMax (x:xs) = Just (foldl' f (x, x) xs)
                  where
                    f (a, b) c = (if c &lt; a then c else a, if c &gt; b then c else b)
  </code></pre>
  
  <p><code>rand</code> is a function that generates an infinite list of numbers.
  The thing is that when I append the following <code>main</code> function:</p>
  
  <pre><code>main = print $ minMax $ take 1000000 $ rand 7666532
  </code></pre>
  
  <p>compile and run all this with profiling, it shows me it uses over 200 MB of memory, so it's definitely not a constant-space function (which I'd like it to be).</p>
  
  <p>The question is why and what should I change to fix it. As I understand <code>foldl'</code> folds the list from left (same way it's generated) and is not lazy, so I don't see why the memory usage is so high. I'm pretty sure it's the <code>minMax</code> function that is incorrect, as simply printing the said list, using</p>
  
  <pre><code>main = print $ take 1000000 $ rand 7666532
  </code></pre>
  
  <p>gives me 1MB usage, something that I understand and expect.</p>