views:

75

answers:

2

Say I've got some code like this

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

is there any way that would allow me to do something like

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

where X be based on the actual pattern being matched

+5  A: 

You can use an active pattern:

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)
| _ -> ...
kvb
+7  A: 

I like @kvb's answer.

This does suggest that you may want to redefine the DU, though:

type Op = | Add | Sub
type Expr = | Binary of Op * Expr * Expr
Brian
which I probably should any way and thx for pointing it out :)
Rune FS