I am looking for nice clean solution to map some conditions to different actions. Typical way is to use multiply if statements:
f1 = lambda x: print('f1(%s)' % x)
f2 = lambda x: print('f2(%s)' % x)
f3 = lambda x: print('f3(%s)' % x)
def non_functional_routing():
for x in range(100):
if 10>x>0:
f1(x)
if 20 > x >= 10:
f2(x)
if x >= 20:
f3(x)
non_functional_routing()
But I think I can make it more expressive in functional style:
def func_routing():
c1 = lambda x: 10>x>=0
c2 = lambda x: 20 > x >= 10
c3 = lambda x: x >= 20
routes = ((c1,f1),(c2,f2),(c3,f3))
for x in range(100):
(r[1] for r in routes if r[0](x)).__iter__().__next__()(x)
func_routing()
How do you prefer to implement such a thing? any nice solutions (functional style is preferable)?
Aucun commentaire:
Enregistrer un commentaire