samedi 14 février 2015

pattern matching of variant tag in OCaml

I have the following OCaml substitution function.



let rec subst x a f =
match f with
| Var s -> if s = x then a else Var s
| Implies (f1, f2) -> Implies (subst x a f1, subst x a f2)
| And (f1, f2) -> And (subst x a f1, subst x a f2)
| Or (f1, f2) -> Or (subst x a f1, subst x a f2)
| True | False as e -> e


Some cases are almost identical and I'm wondering if there's a way to factorize them somehow.


Ideally, I'm thinking of a construct of the form:



match f with
| tag (f1, f2) -> tag (subst x a f1, subst x a f2)
| ...


that would match all my binary operations.


An other use case would be in a to_string function where we could have:



match f with
| tag (f1, f2) -> print_string ((tag_to_string tag) ^ ... )
| ...


I know this isn't possible in OCaml, but is there a pattern or a language construct that goes in that direction?


Aucun commentaire:

Enregistrer un commentaire