PS equivalent to REPL's :type command?

I suppose the title asks the question in full. If I’d like to store some string representation of a value’s type, is there an expression that acts like the REPL’s :t or :type command?

Compiler support for this was proposed in Proposal: Compiler-Solved TypeName Constraint · Issue #3787 · purescript/purescript · GitHub.

For a limited set of types, and only those types that can participate in instance resolution (so, no row or record types, no quantified or constrained types, etc.), you can of course cobble together something like this without compiler support, though you probably won’t enjoy it.

class TypeAsString :: forall k. k -> Constraint
class TypeAsString t where
  typeAsString :: Proxy t -> String

instance TypeAsString Int where
  typeAsString _ = "Int"

instance TypeAsString String where
  typeAsString _ = "String"

instance TypeAsString a => TypeAsString (Array a) where
  typeAsString _ = "(Array " <> typeAsString (Proxy :: _ a) <> ")"

instance (TypeAsString a, TypeAsString b) => TypeAsString (Either a b) where
  typeAsString _ = "(Either " <> typeAsString (Proxy :: _ a) <> " " <> typeAsString (Proxy :: _ b) <> ")"

main :: Effect Unit
main = log $ typeAsString (Proxy :: _ (Either (Array Int) String))
1 Like

Couldn’t Quote be used here, too?

1 Like

That would let you talk about a Doc instead of a Type, but either way OP seems to want some way to reflect it into a String.

2 Likes

yeah the point of Quote is that you can’t get back to Symbol or String from it since it isn’t coherent: it will happily convert type variables to strings, print polymorphic types, etc., thus it is relegated to error messages/warnings.

1 Like

Thanks for the responses!

The discussion in the linked proposal explains why implementing this the “simple” way may have some repercussions as PS evolves. I wasn’t really thinking about type-level programming when I asked this, but I can see that supporting this would be used there.

Something like TypeAsString is what I’m currently using. It works for my needs, though it’s always nice to see if there are other/better ways to get something done.

Quote is super neat, checking that out now.