Sometimes I come upon a need to return values of an existentially quantified type. This happens most often when I’m working with phantom types (for example representing the depth of a balanced tree). AFAIK GHC doesn’t have any kind of exists quantifier. It only allows existentially quantified data types (either directly or using GADTs).
To give an example, I’d like to have functions like this:
-- return something that can be shown
somethingPrintable :: Int -> (exists a . (Show a) => a)
-- return a type-safe vector of an unknown length
fromList :: [a] -> (exists n . Vec a n)
So far, I have 2 possible solutions that I’ll add as an answer, I’d be happy to know if anyone knows something better or different.
The standard solution is to create an existentially quantified data type. The result would be something like
Now, one can freely use
show (somethingPrintable 42).Exists1cannot benewtype, I suppose it’s because it’s necessary to pass around the particular implementation ofshowin a hidden context dictionary.For type-safe vectors, one could proceed the same way to create
fromList1implementation:This works well, but the main drawback I see is the additional constructor. Each call to
fromList1results in an application of the constructor, which is immediately deconstructed. As before,newtypeisn’t possible forExists1, but I guess without any type-class constraints the compiler could allow it.I created another solution based on rank-N continuations. It doesn’t need the additional constructor, but I’m not sure, if additional function application doesn’t add a similar overhead. In the first case, the solution would be:
now one would use
somethingPrintable 42 showto get the result.And, for the
Vecdata type:this can be made a bit more readable using a few helper functions:
The main disadvantages I see here are: