0

I would like to define a function as follows:

double f ( double x ){
    return what_certain_string_says_to_do_on_x;
}

That behaves as the intuition suggests: if such string is equal to "sin(x)", the resulting function will be the usual sine, and so on. For sake of simplicity, assume to always have a variable named "certain_string" that always contains well-defined instructions.

Does anyone have some suggestion?

The only "solution" I see is to write a simple script that rewrite the C source code by replacing the line "return what_certain_string_says_to_do_on_x;" with the explicit characters contained in the string, and then recompile. It works, but I would like to obtain something simpler and quicker.

Thanks a lot in advance for any kind of help.

  • One solution I see is that you *parse* the string into a set of instructions and then execute these instructions one by one. The solution should depend on where you got the problem from. Is it a class or course about *parsing*? About loading external libraries dynamically? Self-modifying code? Please give us more details about the source of the problem. – Some programmer dude Aug 30 '16 at 11:00
  • Possible solution: use an existing script execution library like python, lua – Garf365 Aug 30 '16 at 11:54

1 Answers1

0

The most obvious solution to this problem is to create a hash table, whose keys are the set of supported function names (e.g "sin") and whose values are pointers to the matching functions. A procedure would have to be called to populate this hash table before any usage. In 'f()' you would then use the 'certain_string' to look up the matching function pointer, then call that function on 'x' via that pointer.

PMar
  • 1