python的函数模式匹配
splarnektit的Python项目详细描述
Splarnektity提供了一种有限但有价值的功能模式 与Python、a la OCaml、Erlang、Haskell等匹配另一种方式 考虑到这一点:python列表上的模式匹配。
下面是Splarnektity使用的一个快速示例:
from splarnektity import FMatch sexpr = ('person', ('name', 'john'), ('address', ('line1', '123 Townville'), ('zip', 54321)), ('age', 24), ('favorite foods', 'pizza', 'dorritos'), ) for x in sexpr[1:]: f = FMatch(x) V1, V2 = f.var(2) if f.when(('name', V1)): print 'name: ', V1.v elif f.when(('address', ('line1', V1), ('zip', V2))) and V2.int: print 'address line1: ', V1.v print 'address zip: ', V2.v elif f.when(('age', V1)) and V1.int: print 'age: ', V1.v elif f.when(('favorite foods', V1.others)): # variable length matching print 'favorite foods:', V1.v
此示例的结果是:
name: john address line1: 123 Townville address zip: 54321 age: 24 favorite foods: ('pizza', 'dorritos')