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

You can do something similar in any language that support booleans as keys for dictionaries/hashtables/maps/associative arrays/...

For instance in Lua:

    function abs(x)
        test = {
           [true]=-x,
           [x>0]=x,
           [x==0]=0}
        return test[true]
    end

    > print (abs(-3))
    3
To understand this code, think that `test[true]` is overwritten at initialization time by the last predicate to evaluate to True.

It's not the best way to do this, but maybe it'will help understand the above construct.



There's a difference, though. This example evaluates every "branch".


Make it even more ridiculous and wrap every branch in a lambda function, then do

    test[true]()


That would only evaluate the original [true] key, though, right?


No, `test[true]` will be reassigned to the given function each time the condition evaluates to true. Calling `test[true]()` will execute that given function.




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

Search: