我一直在使用多态变体来处理结果类型的错误(取自http://keleshev.com/composable-error-handling-in-ocaml),它非常适合详尽的检查。我最近遇到了在仿函数中注释结果类型的需要,但不确定是否可行。这是一个片段,对我要完成的工作有一些评论:
open Belt;
/* A quick example of what's working for us right now. This is fine and
the result error type is [> `Error1 | `Error2 ] */
let res = Result.flatMap(Result.Error(`Error1), _ => Result.Error(`Error2));
/* A really generic version of what what we're trying to do */
module type General = {
type t;
type error;
let res: Result.t(t, error);
};
module Make = (M: General) => {
let res = M.res;
};
module Specific1 =
Make({
type t = string;
type error = [ | `Specific1Error];
let res = Result.Error(`Specific1Error);
});
module Specific2 =
Make({
type t = int;
type error = [ | `Specific2Error];
let res = Result.Error(`Specific2Error);
});
/* This definitely doesn't compile because the two error types
aren't the same but wondering if anything above can be changed so it
understands the error type is [> `Specific1Error | `Specific2Error] */
let res = Result.flatMap(Specific1.res, _ => Specific2.res);