-1

I want make a function as I type and read it as a function. For example, if I type x+y, then f(x,y)=x+y. Is this possible? The following code does not work.

real function f(x,y)
real x,y
write(6,*) "type f(x,y)"
read*, f
return
end
7
  • Possible duplicate: stackoverflow.com/questions/7326828/… Commented Jun 13, 2013 at 2:56
  • "does not work" is not very helpful. Also, you seem to have forgotten a closing quote.
    – DaveP
    Commented Jun 13, 2013 at 3:41
  • @DaveP Edited the typo. Coding is okay but if I run the program, it stops and does not give any message. If I delete the 3rd line and type "x+y", then it gives an error message that what I typed is not real.
    – Gobi
    Commented Jun 13, 2013 at 4:09
  • Should f be ignoring the x and y passed to it?
    – Justin L.
    Commented Jun 13, 2013 at 4:32
  • I do not think that this is possible.
    – Kyle Kanos
    Commented Jun 13, 2013 at 12:32

2 Answers 2

1

Yes, you can, but your syntax is a bit off.

      PROGRAM READFUNC
        REAL x,y,F,res

        res = F(x,y)

        WRITE(*,*) res
      END

      REAL FUNCTION F(x,y)
        REAL x,y

        WRITE (*,*) "Type in"
        READ (*,*) F

        RETURN
      END

note that I compiled this w/ gfortran so I'm not sure if it uses any F90+ extensions or not.

EDIT After reading your edits, I see that this isn't what you want; you want some kind of eval/parser. In general this is not a trivial thing. You're going to have to do some kind of token parsing work.

However there are libraries that can do this for you that are already written.

See this article for an example of where to look for more research.

5
  • I tested this program. Coding is okay, but it has no response after I run it.
    – Gobi
    Commented Jun 13, 2013 at 5:59
  • What compiler are you using?
    – Justin L.
    Commented Jun 13, 2013 at 6:04
  • Isn't that a recursive write? stackoverflow.com/questions/7646278/…
    – Deditos
    Commented Jun 13, 2013 at 9:09
  • @Deditos It probably is; my lack of access to non-gfortran compilers betrays me. If you separate out the function call into an assignment and then a write then it should be non-recursive.
    – Justin L.
    Commented Jun 13, 2013 at 16:08
  • This is not recursion. Inside function f() f is a real variable and the above works just fine if the user keys in the number to be returned by the function.
    – agentp
    Commented Jun 14, 2013 at 18:19
0
     F(X,Y)=X+Y
 99  READ(*,*)X,Y
     WRITE(*,*)F(X,Y)
     GO TO 99

You enter 3 4 or 3,4 and you get out 7

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