4 ms·
You can do something similar in any language that support booleans as keys for dictionaries/hashtables/maps/associative arrays/... For instance in Lua: fu
by babarock 14y ago
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.
- reycharles 14y agoThere's a difference, though. This example evaluates every "branch".
- reikonomusha 14y agoMake it even more ridiculous and wrap every branch in a lambda function, then do test[true]()