8

What is the best way to convert an expression to a string in a reversible manner?

I need a toStr function so that it is always true that

ToExpression@toStr[expr] === expr

ToString is not satisfactory because it may use special, irreversible formatting. Example:

ToString[Graphics[{Circle[{0,0}]}]]
(* "-Graphics-" *)

In this case the problem is that it uses OutputForm by default. Requesting InputForm would solve this. But then consider

Format[x, InputForm] = "foo"

ToString[x, InputForm]
(* "foo" *)

x does exist as a proper expression in-memory. It can be written to disk by exporting to MX and then reliably re-imported. I am looking for the same functionality, but through strings.


Note: I am aware that there are some expressions which can't be safely cycled through a string, or even through Compress or through MathLink. An example would be

asc = <| a -> 1|>
a = 5;

asc
(* <| a -> 1|> *)

ToExpression@ToString[asc]  (* or use Uncompress@Compress[...] if you like *)
(* <| 5 -> 1 |> *)

I am not aiming to solve these types of difficulties, which are separate from my main problem.

Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263

1 Answers1

3

This may fail in some obvious way, but it works on the example you give

toStr = ToString@*FullForm

For example with the following

testcases = {Graphics[{Circle[{0, 0}]}], Series[Sin[x], {x, 0, 3}], Integrate[f[x], x]}

I have

strs = toStr/@testcases
results = ToExpression /@ strs
testcases === results
(* True *)
mikado
  • 16,741
  • 2
  • 20
  • 54