title: Given these type declarations in OCaml for a stream type, how to I write a flatten function?
body: <pre><code>exception Empty_list
  
  type 'a stream = Stream of 'a * (unit -&gt; 'a stream) | Nil
  
  let shead s = match s with
    | Stream (a, _) -&gt; a
    | Nil -&gt; raise Empty_list
  
  let stail s = match s with
    | Stream (_, s) -&gt; s ()
    | Nil -&gt; raise Empty_list
  
  let stream_to_list s =
    let rec stream_to_list s accumulator = match s with
      | Nil -&gt; accumulator
      | Stream (_, _) -&gt; stream_to_list (stail s) (shead s :: accumulator)
    in List.rev (stream_to_list s [])
  </code></pre>
  <p>The flatten function would take an arbitrarily nested set of streams and produce a completely flattened version that's a result of an inorder traversal of the nesting structure and contains only the leaves. This would mean that the result of <code>shead</code> on each member of this new thing would return something that was not a stream.</p>
  <p>The idea is that <code>stream_to_list (flatten s)</code> would give back a list in which no element was a stream.</p>