是否有其他方法来解构OCaml中的选项类型?(Are there other ways to deconstruct option types in OCaml?)

OCaml的选项类型在有可能不会返回任何内容的情况下非常有用。 但是当我在很多地方使用它时,我觉得在match ... with处理Some Case和None情况会很麻烦match ... with

例如,

let env2 = List.map (fun ((it,ie),v,t) -> match t with | Some t -> (v,t) | None -> begin match it with | Some it -> (v,it) | None -> failwith "Cannot infer local vars" end) ls_res in

有没有其他方法可以简洁地解构选项类型?

OCaml's option type is really useful in cases where you have functions that might not return anything. But when I use this in many places, I find it cumbersome to handle the Some case and the None case all the time in a match ... with.

For example,

let env2 = List.map (fun ((it,ie),v,t) -> match t with | Some t -> (v,t) | None -> begin match it with | Some it -> (v,it) | None -> failwith "Cannot infer local vars" end) ls_res in

Are there any other ways to deconstruct the option type in a concise manner?

最满意答案

对于简单的情况,你可以同时匹配几件事情:

match t, it with | Some t, _ -> (v, t) | None, Some it -> (v, it) | None, None -> failwith "Cannot infer local vars"

这是我一直在做的事情。 我被告知编译器对这个构造很好(它实际上并不会生成一对额外的对)。

For simple cases, you can match several things at once:

match t, it with | Some t, _ -> (v, t) | None, Some it -> (v, it) | None, None -> failwith "Cannot infer local vars"

This is something I do all the time. I'm told the compiler is good with this construct (it doesn't actually generate an extra pair).

更多推荐