3 ms·
Trying again: With this, it would be possible for a user to create a switch/case statement of their own. n = 3 switch n: case 1:
by pwmanagerdied 17y ago
Trying again: With this, it would be possible for a user to create a switch/case statement of their own.
n = 3
switch n:
case 1:
print("n is one")
case 2:
print("n is two")
default:
print("n is neither one or two")
by injecting "case" into the namespace of a block in "switch", we'd only have to add one identifier to the global namespace. Here's what some of the implementation code might look like.
@macro
def switch(value):
@macro
def _switch(block):
cases = dict()
def line_callback(value):
if isinstance(value, SwitchCase):
cases[SwitchCase.value] = SwithCase.block
elif isinstance(value, DefaultCase):
default = DefaultCase.block
block(line_callback=line_callback)
try:
result_block = cases[value]
except KeyError:
result_block = default
return(result_block())
return(_switch)
I wasn't thinking of it exclusively as a data structure tool, but also possibly as a way to create your own flow control operations and such.
This might not be the most compelling possible example in the world, but I hope it helps.