OCaml 的选项类型在您的函数可能不返回任何内容的情况下非常有用。但是当我在很多地方使用它时,我发现在 Some
中始终处理 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
还有其他方法可以简洁地解构选项类型吗?
最佳答案
对于简单的情况,您可以一次匹配多项内容:
match t, it with
| Some t, _ -> (v, t)
| None, Some it -> (v, it)
| None, None -> failwith "Cannot infer local vars"
这是我一直在做的事情。我被告知编译器对这个结构很好(它实际上并没有生成额外的对)。
关于ocaml - 是否有其他方法可以解构 OCaml 中的选项类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14981967/