title: Generate sequence using previous values
body: <p>I'm learning functional programming with F#, and I want to write a function that will generate a sequence for me. </p>
  
  <p>There is a some predetermined function for transforming a value, and in the function I need to write there should be two inputs - the starting value and the length of the sequence. Sequence starts with the initial value, and each following item is a result of applying the transforming function to the previous value in the sequence.</p>
  
  <p>In C# I would normally write something like that:</p>
  
  <pre><code>public static IEnumerable&lt;double&gt; GenerateSequence(double startingValue, int n)
  {
      double TransformValue(double x) =&gt; x * 0.9 + 2;
  
      yield return startingValue;
  
      var returnValue = startingValue;
      for (var i = 1; i &lt; n; i++)
      {
          returnValue = TransformValue(returnValue);
          yield return returnValue;
      }
  }
  </code></pre>
  
  <p>As I tried to translate this function to F#, I made this:</p>
  
  <pre><code>let GenerateSequence startingValue n =
      let transformValue x =
          x * 0.9 + 2.0
  
      seq {
          let rec repeatableFunction value n = 
              if n = 1 then
                  transformValue value
              else 
                  repeatableFunction (transformValue value) (n-1)
  
          yield startingValue
          for i in [1..n-1] do
              yield repeatableFunction startingValue i
      }
  </code></pre>
  
  <p>There are two obvious problems with this implementation.</p>
  
  <p><strong>First</strong> is that because I tried to avoid making a mutable value (analogy of <code>returnValue</code> variable in C# implementation), I didn't reuse values of former computations while generating sequence. This means that for the 100th element of the sequence I have to make additional 99 calls of the <code>transformValue</code> function instead of just one (as I did in C# implementation). This reeks with extremely bad performance.</p>
  
  <p><strong>Second</strong> is that the whole function does not seem to be written in accordance with Functional Programming. I am pretty sure that there are more elegant and compact implementation. I suspect that <code>Seq.fold</code> or <code>List.fold</code> or something like that should have been used here, but I'm still not able to grasp how to effectively use them.</p>
  
  <hr>
  
  <p><strong>So the question is</strong>: how to re-write the <code>GenerateSequence</code> function in F# so it would be in Functional Programming style and have a better performance?</p>
  
  <p>Any other advice would also be welcomed.</p>