我想要一个匹配声明,让我可以访问记录和的一些字段,如下所示:
| Some n {left = Some l; right = Some r} -> dostuff...
所以在这里,我可以参考记录(n
),它的字段是l
和右r
。这可能吗?
e.g。我想要这样的东西
let rec remove_node root v =
match root with
| None -> root
| Some n when v > n.value -> do_a...
| Some n when v < n.value -> do_b...
| Some n when {left = Some l; right = Some r} -> do_c...
| Some {right = Some r} -> do_d...
| Some {left} -> do_e...
但我现在正在写这个:
let rec remove_node root v =
match root with
| None -> root
| Some n ->
(match n with
| _ when v > n.value -> do_a...
| _ when v < n.value -> do_b...
| {left = Some l; right = Some r} -> do_c...
| {right = Some r} -> do_d...
| {left} -> do_e...
)
哪个不是很糟糕,但如果可能的话,我想避免嵌套匹配。
答案 0 :(得分:0)
Lee在上面的评论中指出,解决方案是在括号中使用as
,如下所示:
let rec remove_node root v =
match root with
| Some ({left = Some l; right = Some r} as n) -> dostuff...
(@ Lee,如果你想回答,那么我可以给你信任,我会删除这个并投票给你答案。)