Created
September 22, 2017 16:50
-
-
Save jcrist/c382f9da34138985092707adf0d782c3 to your computer and use it in GitHub Desktop.
switch-case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_cache = {} | |
def case(x): | |
if x not in _cache: | |
_cache[x] = type("Case", (Exception,), {}) | |
return _cache[x] | |
def switch(x): | |
raise case(x) | |
def binop(op, left, right): | |
try: switch(op) | |
except case("+"): | |
return left + right | |
except case("-"): | |
return left - right | |
except case("*"): | |
return left * right | |
except case("/"): | |
return left / right | |
except: # default | |
raise ValueError("Unknown op %s" % op) | |
# In [1]: binop("*", 5, 6) | |
# Out[1]: 30 | |
# In [2]: binop("/", 5, 6) | |
# Out[2]: 0.8333333333333334 | |
# In [3]: binop("+", 5, 6) | |
# Out[3]: 11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment