Building Either (or Result) on top of a selection in F #

I built a monad for success / failure based on the information in the Scott Wlaschin blog with additional help from this posting . I finished with type

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

Now I understand that this is equivalent to selecting in F # as well as in haskell. I would like to reuse the code instead of saving my own, but I would just like to change the implementation and not change my existing code. I would like to use my existing names along with the Choice implementation. (Or maybe advanced selection in fsharpx.)

I tried

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

This almost works, but when I use Error in coincidence, I get the error "Pattern discriminator" Error "is not defined.

  match getMetaPropertyValue doc name with | Error msg -> () | Success value -> value 
+5
source share
2 answers

You also need an active template:

 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 

Then for 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 

The way I did it here .

+8
source

You want let Error = Choice2Of2<string> . Note the uppercase O

0
source

Source: https://habr.com/ru/post/1212971/


All Articles