【发布时间】:2015-02-14 23:48:25
【问题描述】:
我有以下 OCaml 替换函数。
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
有些情况几乎相同,我想知道是否有办法以某种方式分解它们。
理想情况下,我正在考虑以下形式的构造:
match f with
| tag (f1, f2) -> tag (subst x a f1, subst x a f2)
| ...
这将匹配我所有的二进制操作。
另一个用例是在我们可以拥有的 to_string 函数中:
match f with
| tag (f1, f2) -> print_string ((tag_to_string tag) ^ ... )
| ...
我知道这在 OCaml 中是不可能的,但是有没有朝着这个方向发展的模式或语言结构?
【问题讨论】:
-
虽然没有在 Ocaml 中实现,但您可能想阅读that blog post 了解与您描述的类似的假设功能。
标签: design-patterns pattern-matching ocaml variant