title: Return index of an asked-for value of a list using fold in OCaml
body: <p>I wrote a recursive version of index as follows</p>
  
  <pre><code>let index list value =
    let rec counter num = function
      | [] -&gt; -1
      | h::t -&gt; 
          if h == value 
            then num 
          else (counter (num + 1)) t
    in counter 0 list;;
  </code></pre>
  
  <p>It works, but then our professor said we should use a tail recursive version in order to not timeout on the server, so I wrote a new index function using fold, but I can't seem to figure out why if it doesn't find the element, it returns a number greater than the length of the list, even though I want it to return -1.</p>
  
  <pre><code>let index2 list value = fold (fun i v -&gt; 
    if i &gt; (length list) then -1
    else if v == value then i                          
    else i+1) 0 list;;
  </code></pre>
  
  <p>Here's my fold version as well:</p>
  
  <pre><code>let rec fold f a l = match l with
      [] -&gt; a
    | (h::t) -&gt; fold f (f a h) t;;
  </code></pre>