1

I am looking for something similar to ToExpression that is available in Mathematica. I just want to convert a string to an expression, and evaluate the expression. As a first pass, my strings will include only numbers and arithmetic operators, and not even parentheses.

If I need to write it, please point me in the direction of the appropriate pre-defined modules/definitions which I should use.

3 Answers 3

2

Maybe you can use this parser for infix expressions.

http://planet.racket-lang.org/package-source/soegaard/infix.plt/1/0/planet-docs/manual/index.html

Here is a small example (it takes a while for the library to install - it seems it old Schematics test suite takes forever to install these days - I need to switch to a builtin one).

#lang at-exp racket
(require (planet soegaard/infix)
         (planet soegaard/infix/parser))
(display (format "1+2*3 is ~a\n" @${1+2*3} ))

(parse-expression #'here (open-input-string "1+2*3"))

The output will be:

1+2*3 is 7
.#<syntax:6:21 (#%infix (+ 1 (* 2 3)))>

The function parse-expression parses the expression in the string and returns a syntax-object that resembles the output of ToExpression.

1

Does the section on dynamic evaluation apply to your question? You can parse strings into expressions by using a combination of read and open-input-string. The resulting expressions can be evaluated, with or without the help of a sandbox.

5
  • 1
    Nice work! I can't believe you answered that question without saying "eval". D'oh! Commented Mar 1, 2012 at 0:45
  • Uh oh. Did I screw up? I'm tone-deaf on the Internet... :(
    – dyoo
    Commented Mar 1, 2012 at 1:19
  • 1
    Nope, I was genuinely amused. See, the joke was that I said eval, while congratulating you for not saying ... uh, cf. E.B. White's comment about humor and the frog :). Commented Mar 1, 2012 at 16:47
  • @dyoo Is there some sample code that uses a combination of "read" and "open-input-string" that would serve as an example? Commented Mar 7, 2012 at 16:12
  • open-input-string takes a string and produces an input port. read takes an input port and produces an s-expression. (define an-expr (read (open-input-string "(prn 'hi)")))), for example, will have an-expr refer to a value that we can process more easily than a string, since it has structure. Then we've got libraries, like the ones cited in the answer, that can evaluate this structured expression.
    – dyoo
    Commented Mar 7, 2012 at 19:13
1

http://docs.racket-lang.org/guide/eval.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.