title: Building the built-in procedure "build-list" in Racket
body: <p>I am trying to build the built-in procedure <a href="http://docs.racket-lang.org/reference/pairs.html?q=build-list#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._build-list%29%29" rel="nofollow noreferrer"><em>build-list</em></a> in Racket.</p>
  
  <p>The built-in function works like this:</p>
  
  <pre><code>(build-list 10 (lambda (x) (* x x)))
  
  &gt;&gt; '(0 1 4 9 16 25 36 49 64 81)
  </code></pre>
  
  <p>My implementation is a recursive definition for a recursive procedure:</p>
  
  <pre><code>(define (my-build-list-recur list-len proc)
    (if (= list-len 0)
        '()
        (cons  (proc (sub1 list-len)) (my-build-list-recur (sub1 list-len) proc))))
  </code></pre>
  
  <p>When I call my implementation, I have:</p>
  
  <pre><code>(my-build-list-recur 10 (lambda (x) (* x x)))
  &gt;&gt; '(81 64 49 36 25 16 9 4 1 0)
  </code></pre>
  
  <p>As you might have seen, I get the same result, but in a reverse order.</p>
  
  <p>What can I do to have the result in the same order as the native function?</p>
  
  <p>P.S.: I have done an implementation using a recursive definition for an iterative procedure which works perfectly. I am struggling now to generate the same result with the totally recursive procedure. I <strong>already</strong> know how to solve this doubt with long tail recursion.</p>
  
  <p>This is my implementation with long tail recursion:</p>
  
  <pre><code>(define (my-build-list list-len proc)
    (define (iter list-len accu n)
      (if (= (length accu) list-len)
          (reverse accu)
          (iter list-len (cons (proc n) accu) (add1 n))))
    ;(trace iter)
    (iter list-len '() 0))
  </code></pre>