Search code examples
dcommand-pattern

Switch cas Alternative in D


I have the following problem.

In the input consol I can input a string, and the system will take action based on such.

So if I input add_2_with_2, it will give me a 4, if I input sqrt_4 it will give me 2, etc. Generally, you will do this with a switch / case command, but the problem is, then I need a condition for each case. So if i want to ADITTIONALLY input cube_2, then I have to write a case for this.

However, I would like to do the same without having to explicitly write a case each time I insert a new command. So forexample, if in input "FUNCTION_1", then the program should look in a specific place, in a specific forlder / file, find out if the function is defined, and execute it. If not defined in the file / folder, then it should throw AN EXCEPTION. If I additionally want to input "FUNCTION_2", then i will define the function in the same file or folder (whatever is possible with D) and then let the original program to automatically search and execute.

Can this be done in D?

(sorry for stupid question and bad English)


Solution

  • Yes, you can, there's a few ways you can do it.

    1) You can call functions from inside the one program, and automatically find/map them using compile time reflection.

    I did this in my terminal emulator's utility program. See the source to see how I did it: https://github.com/adamdruppe/terminal-emulator/blob/master/utility.d

    To use it for your own purpose, you can remove the version() statements, change the module name, and write your own functions.

    2) You can also look for a script in a directory and run them that way. Use std.process and std.file to find a file and run it.