本文介绍了在F#的Choice之上构建Either(或Result)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据Scott Wlaschin的 blog ,并从此堆栈溢出发布中获得额外帮助.我最后输入

I built a monad for success/failure based on information in Scott Wlaschin's blog with extra help from this stack overflow posting. I ended up with a type

type Result<'a> = 
| Success of 'a
| Error of string

我现在意识到这等效于F#中的Choice和Haskell中的Either.我想重用代码而不是保留自己的代码,但只想更改实现,而不必更改我现有的代码.我想将我的现有名称与Choice的实现一起使用. (或者也许是fsharpx中的扩展Choice).

I now realize that this is equivalent of Choice in F#, and Either in haskell. I'd like to reuse code instead of keeping my own, but would like to just change the implementation and not have to change my existing code. I'd like to use my existing names along with the implementation of Choice. (Or maybe the expanded Choice in fsharpx.)

我尝试过

type Result<'a> = Choice<'a, string>
let Success = Choice1Of2
let Error = Choice2Of2

这几乎可以用,但是当我在比赛中使用错误"时,出现错误未定义模式识别符'错误'.

This almost works, but when I use Error in a match, I get an error "The pattern discriminator 'Error' is not defined.

    match getMetaPropertyValue doc name with
    | Error msg -> ()
    | Success value -> value

推荐答案

您还需要一个活动模式:

You need also an active pattern:

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

这就是我此处的方法

这篇关于在F#的Choice之上构建Either(或Result)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:15