How do you read an expression?

new topic     » goto parent     » topic index » view thread      » older message » newer message

Andrew Baron asks:
> Hi all, I am a little new at Euphoria and would like to know how I
> might convert a user input of say: x^2+3*4 to a expression that
> would get 'x' from a for loop.
> This is for a graphing program that I wrote in BASIC and want to convert.
> The expression could be just 'x' or even '2x^4+3x^2-9x+7'

There's no simple way in Euphoria to read in a string containing an
mathematical expression with variables, and evaluate it.

There is however a tricky way to do this.

You could have a program something like:

1. ask user for input
2. read in his input string
3. write out a file, expr.e, that you create with open(), puts() etc.
   as:
       global function user(atom x)
          return  2*power(x,4) + 3*power(x,2) - 9*x + 7  -- plug in user's strin
g
       end function

-- expr.e will have been created by the time Euphoria tries
-- to include it:
include expr.e

procedure plot(atom x, atom y)
-- your graphing routine
end procedure

for x=0.0 to 100.0 by 1.0 do
    -- call user() function in the expr.e file that you just created
    plot(x, user(x))
end for

The program would probably just do one plot each time. It would
be hard to loop around and get another expression from the user since an
include statment can't be inside a loop.
The general idea is that you can create a .e file
just before Euphoria tries to include it. This trick might
be used for other purposes as well, such as selecting
from several possible versions of a .e file using a
system("copy ...", 2) command just before the include statement.

I hope this hasn't confused you too much!

-- Rob Craig
   Rapid Deployment Software

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu