Zulip Chat Archive
Stream: general
Topic: Repr vs ToString
Violeta Hernández (Oct 26 2024 at 13:10):
Say there's a type with two sorts of textual representations, one of which is easy to parse back but hard to read, and the other which is harder to parse back but much easier to read.
Violeta Hernández (Oct 26 2024 at 13:10):
Am I correct in saying the former should be a Repr
instance and the latter should be ToString
?
Violeta Hernández (Oct 26 2024 at 13:10):
Or, how does this generally work?
Sofia Rodrigues (Oct 26 2024 at 16:09):
Well, I believe Repr
is meant to represent the exact code used to build the structure. For example, in the datetime library PR, Markus (one of the members of Lean FRO leading the efforts to improve the Std) told me to make the Repr
of a DateTime
look like date("2024-10-24T13:05:20")
that is exactly the macro used to create the DateTime
and then to use ToString
for a human readable output that sometimes is not so easy to parse. So yeah, I think that your ideas are kinda like correct ~~
The Repr
documentation says:
A typeclass that specifies the standard way of turning values of some type into Format.
When rendered this Format should be as close as possible to something that can be parsed as the input value.
Sofia Rodrigues (Oct 26 2024 at 16:14):
And I think that someone needs to create a PR explaining this in the docstrings of ToString just to add some clarity.
Kyle Miller (Oct 26 2024 at 16:28):
Yeah, ToString
is meant to be some sort of coercion to String
, giving some sort of natural representation, with no concern for parsing. For example, the ToString
instance for String
is the identity function (it's already a string), but the Repr
instance, which is supposed to be parseable, wraps it in quotation marks and transforms the string to use escape sequences when necessary.
Violeta Hernández (Oct 26 2024 at 16:29):
Is there a way to make #eval
default to the ToString
representation rather than Repr
? (Is this desirable?)
Kyle Miller (Oct 26 2024 at 16:33):
Do #eval toString <| e
instead of #eval e
, if it's a pure value
Kyle Miller (Oct 26 2024 at 16:33):
In the next release, #eval
will use the ToExpr
instance over Repr
or ToString
. It tries each of these in order.
Kyle Miller (Oct 26 2024 at 16:33):
This way the result will be pretty printed just like in the Infoview.
Violeta Hernández (Oct 26 2024 at 16:34):
Nice!
Last updated: May 02 2025 at 03:31 UTC