2012-08-10 117 views
5

我剛剛在Racket中發現pattern matching功能非常強大。Python中是否存在像這樣的模式匹配函數?

> (match '(1 2 3) [(list a b c) (list c b a)]) 

'(3 2 1) 

> (match '(1 2 3) [(list 1 a ...) a]) 

'(2 3) 

> (match '(1 2 3) 
    [(list 1 a ..3) a] 
    [_ 'else]) 

'else 

> (match '(1 2 3 4) 
    [(list 1 a ..3) a] 
    [_ 'else]) 

'(2 3 4) 

> (match '(1 2 3 4 5) 
    [(list 1 a ..3 5) a] 
    [_ 'else]) 

'(2 3 4) 

> (match '(1 (2) (2) (2) 5) 
    [(list 1 (list a) ..3 5) a] 
    [_ 'else]) 

'(2 2 2) 

在Python中有類似的語法糖或庫嗎?

回答

3

沒有沒有,蟒蛇的模式匹配僅僅是迭代拆包這樣的:

>>> (x, y) = (1, 2) 
>>> print x, y 
1 2 

還是在功能上的定義:

>>> def x((x, y)): 
    ... 

或者在Python 3:

>>> x, *y = (1, 2, 3) 
>>> print(x) 
1 
>>> print(y) 
[2, 3] 

但有一些external libraries實現模式匹配。

相關問題