title: Implementing a direct-threaded interpreter in a functional language like OCaml
body: <p>In C/C++ you can implement a direct threaded interpreter with an array of function pointers.  The array represents your program - an array of operations.  Each of the operation functions must end in a call to the next function in the array, something like:</p>
  
  <pre><code>void op_plus(size_t pc, uint8_t* data) {
    *data += 1;
    BytecodeArray[pc+1](pc+1, data); //call the next operation in the array
  }
  </code></pre>
  
  <p>The <em>BytecodeArray</em> is an array of function pointers.  If we had an array of these  op_plus operations then length of the array would determine how ofter we'd be incrementing the contents of data. (of course, you'd need to add some sort of terminating operation as the last operation in the array).</p>
  
  <p>How would one go about implementing something like this in OCaml?  I may be trying to translate this code too literally: I was using an OCaml Array of functions as in the C++.  The problem with that is that I keep ending up with something like:</p>
  
  <pre><code>let op_plus pc data = Printf.printf "pc: %d, data_i: %d \n" pc data;
                          let f = (op_array.(pc+1)) in         
                          f (pc+1) (data+1) ;;
  </code></pre>
  
  <p>Where op_array is an Array defined in the scope above and then redefine it later to be filled with a bunch of op_plus functions... however, the op_plus function uses the previous definition of op_array.  It's a chicken&amp;egg problem.</p>