title: F# generics: can I constrain a type to not be "unit"?
body: <p>I'm currently teaching myself F#, and have come across this need a few times so I thought it was time to get an answer.</p>
  
  <p>Essentially I would like a function to be generic and to work with every type <strong>except unit</strong>. In the most recent case I'm writing a function that will wrap any other function and cache its result in the given concurrent dictionary. My code so far is as follows: </p>
  
  <pre><code>type CacheStore = System.Collections.Concurrent.ConcurrentDictionary&lt;Guid * obj, DateTime * obj&gt;
  
  let (|ItemPresent|ItemExpired|ItemNotPresent|) ((cacheStore : CacheStore), cacheKey) =
      if cacheStore.ContainsKey cacheKey
      then
          let expiryTime, value = cacheStore.[cacheKey]
          if expiryTime &gt; DateTime.Now
          then ItemPresent value
          else ItemExpired (DateTime.Now - expiryTime)
      else ItemNotPresent
  
  let cache&lt;'a, 'b&gt; (cacheStore : CacheStore) (functionToCache : 'a -&gt; 'b) =
      let functionId = Guid.NewGuid()
  
      let updateCache (cacheStore : CacheStore) cacheKey newValue =
          printfn "Updating cache"
          cacheStore.[cacheKey] &lt;- ((DateTime.Now.AddSeconds 1.0), box newValue)
          newValue
  
      fun arg -&gt;
          let cacheKey = functionId, (box arg)
  
          match cacheStore, cacheKey with
          | ItemPresent value -&gt;
              printfn "Retrieving from cache"
              value :?&gt; 'b
          | ItemExpired ago -&gt;
              printfn "Item in cache but expired %A ago; running function" ago
              updateCache cacheStore cacheKey (functionToCache arg)
          | ItemNotPresent -&gt;
              printfn "Item not in cache; running function."
              updateCache cacheStore cacheKey (functionToCache arg)
  </code></pre>
  
  <p>Obviously, it makes no sense to cache a function that is void / returns unit, <s>and in fact this code will fail at runtime if someone tries to cache a 'a -> unit function.</s></p>
  
  <p>How do I make it fail at compiletime if someone calls this incorrectly? From what I've read I feel that I should be able to do this with an inline function and static type constraints but I don't know how to write that...</p>
  
  <p><strong>UPDATE</strong>
  I have since found that this particular version actually <em>does</em> work with unit functions - the cache wrapper essentially has no effect (it just adds runtime overhead), but the gist of the original question still stands: can I stop people calling this function with unit functions?</p>