functionprogramming-languagesfunction-pointersprogram-flow

controlling program flow without if-else / switch-case statements


Let's say I have 1000 functions defined as follows

void func dummy1(int a);
void func dummy2(int a, int aa);
void func dummy3(int a, int aa, int aaa);
.
.
.
void func dummy1000(int a, int aa, int aaa, ...);

I want to write a function that takes an integer, n (n < 1000) and calls nth dummy function (in case of 10, dummy10) with exactly n arguments(arguments can be any integer, let's say 0) as required. I know this can be achieved by writing a switch case statement with 1000 cases which is not plausible.

In my opinion, this cannot be achieved without recompilation at run time so languages like java, c, c++ will never let such a thing happen.

Hopefully, there is a way to do this. If so I am curious.

Note: This is not something that I will ever use, I asked question just because of my curiosity.


Solution

  • In modern functional languages, you can make a list of functions which take a list as an argument. This will arguably solve your problem, but it is also arguably cheating, as it is not quite the statically-typed implementation your question seems to imply. However, it is pretty much what dynamic languages such as Python, Ruby, or Perl do when using "manual" argument handling...

    Anyway, the following is in Haskell: it supplies the nth function (from its first argument fs) a list of n copies of the second argument (x), and returns the result. Of course, you will need to put together the list of functions somehow, but unlike a switch statement this list will be reusable as a first-class argument.

    selectApplyFunction :: [ [Int] -> a ] -> Int -> Int -> a
    selectApplyFunction fs x n = (fs !! (n-1)) (replicate n x)
    
    dummy1 [a] = 5 * a
    dummy2 [a, b] = (a + 3) * b
    dummy3 [a, b, c] = (a*b*c) / (a*b + b*c + c*a)
    ...
    myFunctionList = [ dummy1, dummy2, dummy3, ... ]
    
    -- (myfunction n) provides n copies of the number 42 to the n'th function
    myFunction = selectApplyFunction myFunctionList 42
    
    -- call the 666'th function with 666 copies of 42
    result = myFunction 666
    

    Of course, you will get an exception if n is greater than the number of functions, or if the function can't handle the list it is given. Note, too, that it is poor Haskell style -- mainly because of the way it abuses lists to (abusively) solve your problem...