What is the proper way to convert Mathematica expressions losslessly to a string (a string kept in memory, not exported to a file)?
I am looking for a textual representation that
SparseArray
, Graph
, Dispatch
, CompiledFunction
, etc. intact. E.g. cycling a SparseArray
through this representation should keep it sparse (and not convert it to a normal list).Is ToString[expr, FullForm]
sufficient for this? What about ToString[expr, InputForm]
?
Note 1: This came up while trying to work around some bugs in Graph
where the internal representation gets corrupted occasionally. But I'm interested in an answer to the general question above.
Note 2: Save
will surely do this, but it writes to files (probably possible to solve this using streams), and it only write definitions associated with symbols.
If you are not going to perform some string manipulations on the resulting string, you may consider Compress
and Uncompress
as an alternative to ToString
. While I don't know about cases where ToString[expr,InputForm]
- ToExpression
cycles would break, I can easily imagine that they exist. The Compress
solution seems more robust, as Uncompress
invoked on Compress
-ed string is guaranteed to reconstruct the original expression. An added advantage of Compress
is that it is pretty memory-efficient - I used it a few times to save large amounts of numerical data in the notebook, without saving them to disk.
Should Compress
exhibit round-tripping problems, ExportString
and ImportString
might present a useful alternative -- particularly, if they are used in conjunction with the Mathematica-native MX
format:
string = ExportString[originalExpr, "MX"]
recoveredExpr = ImportString[string, "MX"]
Note that the MX
format is not generally transferable between Mathematica instances, but that might not matter for the described in-memory application.
ExpressionML
is another Mathematica-related export format, but it is distinctly not a compact format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With