title: Simple Generators
body: <p>This code comes from a paper called <a href="http://www.cs.indiana.edu/~sabry/papers/yield-pp.pdf" rel="nofollow">"Lazy v. Yield"</a>. Its about a way to decouple producers and consumer of streams of data. I understand the Haskell portion of the code but the O'Caml/F# eludes me. I don't understand this code for the following reasons:</p>
  
  <p>What kind of behavior can I expect from a function that takes as argument an exception and returns unit?</p>
  
  <p>How does the consumer project into a specific exception? (what does that mean?)</p>
  
  <p>What would be an example of a consumer?     </p>
  
  
  
  <pre class="lang-ml prettyprint-override"><code>module SimpleGenerators
  
  type 'a gen        = unit -&gt; 'a
  type producer      = unit gen
  type consumer      = exn -&gt; unit  (* consumer will project into specific exception *)
  type 'a transducer = 'a gen -&gt; 'a gen 
  
  let yield_handler : (exn -&gt; unit) ref = 
      ref (fun _ -&gt; failwith "yield handler is not set")
  
  let iterate (gen : producer) (consumer : consumer) : unit = 
      let oldh = !yield_handler in
      let rec newh x =
          try 
              yield_handler := oldh
              consumer x
              yield_handler := newh
          with e -&gt; yield_handler := newh; raise e
      in
      try
          yield_handler := newh
          let r = gen () in
          yield_handler := oldh
          r
      with e -&gt; yield_handler := oldh; raise e
  </code></pre>