[racket] What is the equivalent of ToExpression in Mathematica?

From: Danny Yoo (dyoo at cs.wpi.edu)
Date: Wed Feb 29 16:57:23 EST 2012

On Wed, Feb 29, 2012 at 4:33 PM, Ashok Bakthavathsalam
<ashokb at kggroup.com> wrote:
> Will eval-string work even if the string is the normal mathematical
> notation?
> For example, "1+1" or "8*74-2" ?

No, but there is an example in Racket's parser-tools library
(parser-tools/examples/calc) that will parse very simple arithmetic
expressions.

    https://github.com/plt/racket/blob/master/collects/parser-tools/examples/calc.rkt


It's not provided as a reusable library, unfortunately.  Still, here's
a quick-and-dirty example just to show what it can do:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket

;; Let's break abstractions!  Muhahaha...
(require (only-in rackunit require/expose))
(require/expose parser-tools/examples/calc (calc))


;; You'll see some output (1 and -2) up front: that's the test code
from loading the calc module.
;; Ignore it.

(printf "What's 3 + 4?\n")
(calc (open-input-string "3 + 4"))

(printf "also:\n")
(calc (open-input-string "8*74-2"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


When you run this, you'll see that calc is hardcoded to print some
test values up front.  What makes it somewhat un-reusable is the fact
that it isn't really a function:  'calc' prints to screen, rather than
return its computed value.

It shouldn't be too hard to clean up the example and make it a reusable library.


Posted on the users mailing list.