我根据 Scott Wlaschin 中的信息构建了一个成功/失败的 monadblog http://fsharpforfunandprofit.com/posts/computation-expressions-wrapper-types/得到额外的帮助堆栈溢出发布 https://stackoverflow.com/questions/21801144/wrangling-trywith-in-computation-expressions。我最终得到了一个类型
type Result<'a> =
| Success of 'a
| Error of string
我现在意识到这相当于 F# 中的 Choice 和 haskell 中的 Either。我想重用代码而不是保留自己的代码,但只想更改实现而不必更改现有代码。我想在实施 Choice 的同时使用我现有的名称。 (或者可能是 fsharpx 中的扩展选项。)
我努力了
type Result<'a> = Choice<'a, string>
let Success = Choice1Of2
let Error = Choice2Of2
这几乎有效,但是当我在匹配中使用 Error 时,我收到错误“未定义模式鉴别器‘Error’。
match getMetaPropertyValue doc name with
| Error msg -> ()
| Success value -> value
您还需要一个活动模式:
type Result<'a> = Choice<'a,string>
let Success x :Result<'a> = Choice1Of2 x
let Error x :Result<'a> = Choice2Of2 x
let (|Success|Error|) = function Choice1Of2 x -> Success x | Choice2Of2 x -> Error x
那么对于Either
:
type Either<'a,'b> = Choice<'b,'a>
let Right x :Either<'a,'b> = Choice1Of2 x
let Left x :Either<'a,'b> = Choice2Of2 x
let (|Right|Left|) = function Choice1Of2 x -> Right x | Choice2Of2 x -> Left x
我就是这样做的here https://github.com/gmpl/FsControl/blob/master/FsControl.Core/Samples/Haskell.fsx#L30-33.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)