Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Hmmm replacing if/else statements with a map/dictionary with pointers to either data or functions. A little off topic here but how do you propose to do this? Assuming we know what polymorphism is. Your map/dictionary style is quite interesting.


For languages with first-class functions, it looks like this:

    # Algorithms
    def double(x): return x*2
    def square(x): return x*x
    def fact(x): return (x*fact(x-1) if x > 1 else 1)

    # Data
    choices = { 'A': double, 'B': square, 'C': fact }

    # I/O
    choice = raw_input('Choose A, B or C: ')
    x = input('Enter a number: ')
    if choice in choices:
        print choices[choice](x)
    else:
        print 'Initiating self-destruct sequence.'
It's actually similar to how a switch block works, if each case in the switch statement just calls a function or evaluates one expression.

Also worthwhile: Instead of functions, let the dictionary values be lists of arguments for another (multi-argument) function. Then the lookup is like choosing from a set of possible configurations for that function. A little redundancy is OK, since the table is so easy to read and edit.


Parse tables or regex compiling are a perfect example of this style. Lookup tables are another good example.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: