Szabolcs
Szabolcs

Reputation: 25703

Preserving Mathematica expressions in a textual form

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

  1. will preserve all information, including keeping special (and possibly atomic) objects, such as 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).
  2. 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.

Upvotes: 5

Views: 469

Answers (2)

WReach
WReach

Reputation: 18271

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.

Upvotes: 5

Leonid Shifrin
Leonid Shifrin

Reputation: 22579

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.

Upvotes: 8

Related Questions