title: SML with lazy list function
body: <p>I'm trying to make a function which can return the specific nth element of lazylist.</p>
  
  <p>Here is what I made:</p>
  
  <pre><code>datatype 'a lazyList = nullList
                   | cons of 'a * (unit -&gt; 'a lazyList)
  
  fun Nth(lazyListVal, n) = (* lazyList * int -&gt; 'a option *)
      let fun iterator (laztListVal, cur, target) =
          case lazyListVal of
               nullList =&gt; NONE
             | cons(value, tail) =&gt; if cur = target
                                    then SOME value
                                    else iterator (tail(), cur+1, target)
      in
          iterator(lazyListVal,1,n)
      end
  </code></pre>
  
  <p>I expected the result that as recusing proceeds, eventually the variable <strong><code>cur</code></strong> gets same as the variable <strong><code>target</code></strong>, and then the function iterator returns <strong><code>SOME value</code></strong> so it will return the final nth element.</p>
  
  <p>But when I compile it and run, it only returns the very first element however I test with the lazylist objects.</p>
  
  <p>Please figure what is the problem. I have no idea...</p>
  
  <p>cf) I made another function which is relevant to this problem, the function that transforms lazylist into SML original list containing the first N values. Codes above:</p>
  
  <pre><code>fun firstN (lazyListVal, n) = (* lazyList * int -&gt; 'a list *)
      let fun iterator (lazyListVal, cur, last) =
          case lazyListVal of
               nullList =&gt; []
             | cons(value, tail) =&gt; if cur = last
                                    then []
                                    else value::iterator(tail(),cur+1,last)
      in
          iterator(lazyListVal,0,n)
      end          
  </code></pre>
  
  <p>The strange thing is the function firstN is properly working.</p>