Hi fellow OCaml’ers! Long time reader, first time poster.
I’m making a rookie mistake with polymorphic variants, but I can’t quite understand why. I figure others might stumble into this, so here goes…
First, what works: I’m adopting ('a, [> common_errors ]) result
return values for error management. It allows error variants to aggregate as we go back towards the top level, without having to maintain a program-wide regular variant. (I’m not interested in exceptions for my ultimate use case.) The [> … ]
bit in my function signatures is accepted. (The same in type signatures however, is a no-go and I need i.e. 'a
instead. “Weird,” I thought.)
What doesn’t work: I’m creating an in-memory cache for information that is expensive to create or fetch. In order to add some maintenance code and layer this ahead of other storage mechanisms later, I thought of a process-wide cache which could accept anything. A polymorphic hash table achieves this in utop
:
open Base
let store = Hashtbl.Poly.create ()
let () = Hashtbl.set store ~key:(`Foo 42) ~data:"asdf"
Compilation fails however:
Error: The type of this expression, (_[> `Foo of int ], string) Hashtbl.t,
contains type variables that cannot be generalized
…that pesky underscore. What’s more, this simpler experiment does compile:
let f (i : [> ]) = match i with _ -> 1
let _ = f `Roger
(* f has type ([> ] as 'a) -> int *) *)
I’m pretty sure I’ll need to go a completely different route (one cache per key/value type closer to modules making use of it) but before I abandon this idea, I’d love to understand what I’m missing here, which seems fundamental to manipulating polymorphic variants.
Any brave soul willing to help a confused rookie?