title: Accepting only one variant of sum type as OCaml function parameter
body: <p>I have a large sum type originating in existing code. Let's say it looks like this:</p>
  
  <pre><code>type some_type =
    | Variant1 of int
    | Variant2 of int * string
  </code></pre>
  
  <p>Although both <code>Variant1</code> and <code>Variant2</code> are used elsewhere, I have a specific function that only operates on <code>Variant2</code>:</p>
  
  <pre><code>let print_the_string x =
    match x with
    | Variant2(a,s) -&gt; print_string s; ()
    | _ -&gt; raise (Failure "this will never happen"); ()
  </code></pre>
  
  <p>Since this helper function is only called from one other place, it is easy to show that it will always be called with an input of <code>Variant2</code>, never with an input of <code>Variant1</code>.</p>
  
  <p>Let's say the call looks like this:</p>
  
  <pre><code>let () =
    print_the_string (Variant2(1, "hello\n"))
  </code></pre>
  
  <p>If <code>Variant1</code> and <code>Variant2</code> were separate types, I would expect OCaml to infer the type <code>Variant2 -&gt; ()</code> for <code>print_the_string</code>, however, since they are both variants of the same sum type, OCaml infers the signature <code>some_type -&gt; ()</code>.</p>
  
  <p>When I encounter a program that throws an exception with a message like "this will never happen," I usually assume the original programmer did something wrong.</p>
  
  <p>The current solution works, but it means that a mistake in the program would be caught at runtime, not as a compiler error as would be preferable.</p>
  
  <p>Ideally, I'd like to be able to annotate the function like this:</p>
  
  <pre><code>let print_the_string (x : some_type.Variant2) =
  </code></pre>
  
  <p>But, of course, that's not allowed.</p>
  
  <p><strong>Question:</strong> Is there a way to cause a compiler error in any case where <code>Variant1</code> was passed to <code>print_the_string</code>?</p>
  
  <p>A related question was asked <a href="https://stackoverflow.com/questions/10337965/how-applying-a-function-to-a-variant">here</a>, but nlucarioni and Thomas's answers simply address cleaner ways to handle incorrect calls. My goal is to have the program fail more obviously, not less.</p>
  
  <hr>
  
  <p>Update: I'm accepting gallais's solution as, after playing with it, it seems like the cleanest way to implement something like this. Unfortunately, without a very messy wrapper, I don't believe any of the solutions work in the case where I cannot modify the original definition of <code>some_type</code>.</p>