Quantcast
Viewing all articles
Browse latest Browse all 186

Safe alternatives to ToExpression

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

Viewing all articles
Browse latest Browse all 186

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>