In Haskell, a Proxy is a type witness value that makes it easy to pass some types around
data Proxy a = Proxy
An example use is here in json-schema:
class JSONSchema a where
schema :: Proxy a -> Schema
so you could do schema (Proxy :: Proxy (Int,Char))
to obtain what the JSON representation for an Int-Char-Tuple would be (probably an array).
Why do people use proxies? It seems to me that the same could be accomplished by
class JSONSchema a where
schema :: Schema a
similar to how the Bounded
typeclass works.
I first thought it might be easier to get the schema of some given value when using proxies, but that doesn't seem to be true:
{-# LANGUAGE ScopedTypeVariables #-}
schemaOf :: JSONSchema a => a -> Schema a
schemaOf (v :: x) = schema (Proxy :: Proxy x) -- With proxy
schemaOf (v :: x) = schema :: Schema x -- With `:: a`
schemaOf _ = schema -- Even simpler with `:: a`
Also, one might worry about whether the Proxy
values are actually eradicated at runtime, which is an optimisation problem that doesn't exists when using the :: a
approach.
If the :: a
approach as taken by Bounded
achieves the same result with shorter code and less worries about optimisation, why do people use proxies? What are the benefits of proxies?
EDIT: Some answers and commenters rightfully pointed out that the :: a
approach taints the data Schema = ...
type with a "useless" type parameter - at least from the perspective of the plain data structure itself, which doesn't ever use the a
(see here).
The suggestion is to use the phantom type Tagged s b
instead, which allows to separate the two concerns (Tagged a Schema
combines the non-parametric schema type with a type variable a
), which is strictly better than the :: a
approach.
So my the question should better be What are the benefits of proxies vs. the tagged approach?
typeRep :: Proxy a -> TypeRep
. The alternative would be to use the old way of doing it,typfeOf :: a -> Typeable
. But that latter is unpleasant because you often have to use it withtypeOf (undefined :: T)
, and IMHO it's better to usetypeRep (Proxy :: Proxy T)
.Bounded
. Using a type-tag as provided for example by hackage.haskell.org/package/tagged-0.7.3/docs/Data-Tagged.html is a valid alternative to using Proxies. It somewhat depends on whether you want the extra type argument on the result type or not.Tagged
would be the cleaner way to not pollute mySchema
with a uselessa
(since forSchema
thea
would actually never be used on the left hand side of the data declaration). I will add a bit to the end of the question to say that a better question would be about the difference betweenProxy
andTagged
.typeRep
you need the proxy. Could you elaborate a bit?typeRep
: ParameterizingTypeRep
by the type represented would destroy its usefulness. Without a proxy, the type oftypeRep
would beTypeable a => TypeRep
.