mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[stdlib] Add `repr()` function and `Representable` trait

Open gabrieldemarmiesse opened this issue 10 months ago • 1 comments

This PR is a follow up on the discussion there:

https://github.com/modularml/mojo/issues/2207

There is no RepresentableRaising trait yet, this can come later on.

We assume here that 42 is the Mojo representation of Int(42) because this is how it materializes. Same we assume that "hello" is the Mojo string representation of String("hello") because StringLiteral materializes into String.

We could have used Int(42) and String("hello") as Mojo representations but that seems very cumbersome and not aligned with the evolution of the language. The discussion is still open for other types.

The __repr__ implementation for String is very simplistic and I believe it's enough as a start, we can push the complexity in other separate PRs (handling \ and so on). I will open an issue when this PR is merged requesting contributor help to improve it.

I will create another issue after this PR is merged to track the conformance of (all?) library types to the Representable trait.

gabrieldemarmiesse avatar Apr 20 '24 19:04 gabrieldemarmiesse

Is Representable equivalent to Stringable mentioned in #2207?

Upd: It seems __repr__ is close to Debug in rust, and __str__ to Display in rust

jayzhan211 avatar Apr 21 '24 03:04 jayzhan211

✅🟣 This contribution has been merged 🟣✅

Hey @gabrieldemarmiesse,

Thanks so much again for the contribution! 🎉

We're moving to a new infrastructure for merging contributions to Mojo (we're using a tool called Copybara), and your contribution has now been merged into our internal copy of the Mojo Standard Library. I've added the "merged-internally" label on this PR.

The changes in this PR will appear here in the mojo repo nightly branch when we do our next outbound synchronization at the time that the next Mojo nightly is released. That should happen within the next 24 hours.

Please let me know if you have any questions or concerns.

JoeLoser avatar May 01 '24 02:05 JoeLoser

Thanks for merging and fixing the conflicts. I made two follow-up issues:

  • https://github.com/modularml/mojo/issues/2458
  • https://github.com/modularml/mojo/issues/2459

gabrieldemarmiesse avatar May 01 '24 09:05 gabrieldemarmiesse

🎉 🔥 This landed in tonight's nightly release in https://github.com/modularml/mojo/pull/2480!

Thanks again for the contribution!

JoeLoser avatar May 03 '24 03:05 JoeLoser

another thing about repr, it takes non-printable characters and gives the representation of them, such as \n. I already did this in one of my side projects, so I can add it to stdlib.

helehex avatar May 03 '24 06:05 helehex