Background
Conversion from string/boxes to expression is quite common. Very often the goal would be a simple switch from "1"
to 1
. Or "foo"
to foo
Mindless ToExpression
can lead to evaluation caused by unexpected input or by someone's bad will. E.g. 1 + ToExpression["1"]
is fine but 1 + ToExpression["Quit[]"]
not anymore.
Ideally the function's signature should be foo[_String] -> _expectedHead | $Failed
. But unevaluated will do too.
Example
An example could be Symbol
returning symbols of strings containing valid symbol's names. If we need $Failed
it could be enhanced
Symbol[str] /. Verbatim[Symbol][_String] -> $Failed
Questions
What other alternatives are there?
What if there is no alternative and we need to cook up a custom interpreter? Can we do better than:
Interpreter["Integer"] @ "Evaluate @ Print[1]"
or
ToExpression["1+1", StandardForm, HoldComplete] //
Replace[HoldComplete[Except[_Integer]] -> {$Failed}] // First
Symbol
. For numbers, I do not think there is an alternative that is safe, fast, and robust.FromDigits
is safe, but not robust (use it on strings).ToExpression
is fast, but not safe or robust.Internal`StringToDouble
is fast, but not robust (no error reporting).Interpeter
can do a lot, it is safe, and I think it is robust. But it is awfully slow. Finally, we could simply useRead
andStringToStream
. $\endgroup$