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
- will preserve all information, including keeping special (and possibly atomic) objects, such as
SparseArray,Graph,Dispatch,CompiledFunction, etc. intact. E.g. cycling aSparseArraythrough this representation should keep it sparse (and not convert it to a normal list). - is relatively fast to cycle through (convert back and forth).
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
CompressandUncompressas an alternative toToString. While I don’t know about cases whereToString[expr,InputForm]–ToExpressioncycles would break, I can easily imagine that they exist. TheCompresssolution seems more robust, asUncompressinvoked onCompress-ed string is guaranteed to reconstruct the original expression. An added advantage ofCompressis 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.