1

In the Fortran program, is it possible to read an expression including the variables ? For example, the input file is (if necessary, we can change the input form of the expression,e.g.,the binary form), 2(a-4b) It should be noted that the input expression has a very simple form and it only contains integer or fraction or some variables,like the following in the list, {0,232,-2/5a,3a-b,b/9} Here 2a means 2*a

The Fortran program is

Program test
implicit none
real(kind=8)::a,b,exp 
a=10.
b=3.
! open file and read the input expression
! that is, exp=2*(a-4*b) 
write(*,*) exp  ! we can get exp=-4.0
end program 

For the complicated expressions, it is obviously not a good idea for Fortran. I just want to know, in this simple input expression case, is it possible to find a better way ?

Fortranner
  • 2,525
  • 2
  • 22
  • 25
Orders
  • 169
  • 7
  • You tagged the question with the [tag:regex] tag. Does your question has anything to do with regular expressions? If yes, could you please clarify, it's not obvious. – Andrew Savinykh Jun 18 '14 at 03:42
  • No. I would say just "no", but more characters are required. – M. S. B. Jun 18 '14 at 03:43
  • What you need instead of writing `a=10 b=3` is to use an hash table. you can see here how to implement it: http://fortranwiki.org/fortran/show/Hash+tables – Casimir et Hippolyte Jun 18 '14 at 04:12

2 Answers2

2

A site with tests of three expression evaluators in Fortran is http://www.angelfire.com/ab5/extensao/report.htm . Only the link to the "Brazilian" one works. There is also a Sourceforge project fparser http://fparser.sourceforge.net/ .

Fortranner
  • 2,525
  • 2
  • 22
  • 25
1

Fortran cannot do this unless you write code that can parse the arbitrary expression, substitute and solve, which is a bit of work (see the comment below for details). Fortran is compiled and there is no way to load source on the fly, compile and run it, which is essentially what you are asking. You might look into a language such as Lisp where doing this is should be somewhat trivial. Likewise any scripted language will have facilities to evaluate code, which can do what you are asking.

casey
  • 6,855
  • 1
  • 24
  • 37
  • Expression evaluators are easy to write. See this SO article for how to write general parsers, which applies just fine to expressions: http://stackoverflow.com/a/2336769/120163 As the "parser" runs, it can evaluate the expression to compute the answer needed; this is an easy extension. – Ira Baxter Jun 18 '14 at 17:11