模式匹配并基于模式返回新对象

Run*_* FS 1 f# pattern-matching

说我有一些像这样的代码

match exp with
| Addition(lhs,rhs,_) -> Addition(fix lhs,fix rhs)
| Subtraction(lhs,rhs,_) -> Subtraction(fix lhs,fix rhs)
Run Code Online (Sandbox Code Playgroud)

有什么方法可以让我做类似的事情

match exp with
| Addition(lhs,rhs,_)
| Subtraction(lhs,rhs,_) -> X(fix lhs,fix rhs)
Run Code Online (Sandbox Code Playgroud)

其中X基于匹配的实际模式

Bri*_*ian 7

我喜欢@kvb的回答.

这确实表明您可能想要重新定义DU,但是:

type Op = | Add | Sub
type Expr = | Binary of Op * Expr * Expr
Run Code Online (Sandbox Code Playgroud)


kvb*_*kvb 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)
| _ -> ...
Run Code Online (Sandbox Code Playgroud)