2010-04-27 64 views
1

说我遇到这样模式匹配,并返回基于模式的新对象

match exp with 
| Addition(lhs,rhs,_) -> Addition(fix lhs,fix rhs) 
| Subtraction(lhs,rhs,_) -> Subtraction(fix lhs,fix rhs) 

一些代码有没有什么办法可以让我做这样

match exp with 
| Addition(lhs,rhs,_) 
| Subtraction(lhs,rhs,_) -> X(fix lhs,fix rhs) 

东西,其中X是根据实际匹配的图案

回答

5

您可以使用有效图案:

let (|Binary|_|) = function 
| Addition(e1,e2) -> Some(Addition, e1, e2) 
| Subtraction(e1,e2) -> Some(Subtraction, e1, e2) 
| _ -> None 

let rec fix = function 
| Binary(con,lhs,rhs) -> con(fix lhs, fix rhs) 
| _ -> ... 
7

我喜欢@ kvb的回答。

这确实表明,你可能要重新定义了杜,虽然:

type Op = | Add | Sub 
type Expr = | Binary of Op * Expr * Expr 
+0

这也许我应该指出来任何方式和THX :) – 2010-04-27 18:39:52