title: Mapping which holds and passes previous result
body: <p>When solving system of linear equations by <a href="http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm" rel="nofollow">Tridiagonal matrix algorithm</a> in Haskell I met following problem.</p>
  
  <p>We have three vectors: <code>a</code>, <code>b</code> and <code>c</code>, and we want to make a third vector <code>c'</code> which is a combination of them:</p>
  
  <pre>
  c'[i] = c[i] / b[i], i = 0
  c'[i] = c[i] / (b[i] - a[i] * c'[i-1]), 0 &lt; i &lt; n - 1
  c'[i] = undefined, i = n - 1
  </pre>
  
  <p>Naive implementation of the formula above in Haskell is as follows:</p>
  
  <pre>
  calcC' a b c = Data.Vector.generate n f
    where
      n = Data.Vector.length a
      f i = 
        | i == 0 = c!0 / b!0 
        | i == n - 1 = 0
        | otherwise = c!i / (b!i - a!i * f (i - 1))
  </pre>
  
  <p>It looks like this function <code>calcC'</code> has complexity <i>O</i>(<i>n</i><sup>2</sup>) due to recurrence. But all we actualy need is to pass to inner function <code>f</code> one more parameter with previously generated value.</p>
  
  <p>I wrote my own version of <code>generate</code> with complexity <i>O</i>(<i>n</i>) and helper function <code>mapP</code>:</p>
  
  <pre>
  mapP f xs = mapP' xs Nothing
    where
      mapP' [] _ = []
      mapP' (x:xs) xp = xn : mapP' xs (Just xn)
        where
          xn = f x xp
  
  generateP n f = Data.Vector.fromList $ mapP f [0 .. n-1]
  </pre>
  
  <p>As one can see, <code>mapP</code> acts like a standard <code>map</code>, but also passes to mapping function previously generated value or <code>Nothing</code> for first call.</p>
  
  <p>My question: is there any pretty <b>standard</b> ways to do this in Haskell? Don't I reinvent the weel?</p>
  
  <p>Thanks.</p>