sdgfsdh
sdgfsdh

Reputation: 37131

Prevent shadowing of Ok and Error with FParsec?

Suppose I have a test like this:

module MyTests

open Xunit
open FParsec
open FsUnit.Xunit
open MyParsers

[<Fact>]
let ``pfoo works as expected`` () =
  let text = "blahblahblah"

  let actual =
    match run pfoo text with
    | Success (x, _, _) -> Result.Ok x
    | Failure (s, _, _) -> Result.Error s

  let expected : Result<Foo, string> =
    Result.Ok
      {
        Foo = "blahblahblah"
      }

  expected
  |> should equal actual

open FParsec will shadow Ok so that I need to fully qualify it like Result.Ok.

This is pretty annoying. Is there a good way to "open" Result again so that I can write Ok unqualified?

Upvotes: 1

Views: 54

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80915

It's not Result that you need to "open", but Microsoft.FSharp.Core, which is the module in which Result and both its constructors are defined. This module is open by default, but you can open it again to have its definitions closer in the scope:

open Xunit
open FParsec
open FsUnit.Xunit
open MyParsers
open Microsoft.FSharp.Core

Alternatively, you can alias just the Ok identifier:

let Ok = Result.Ok

let x = Ok "foo"  // x : Result<string, _>

I prefer this latter method, because it minimizes the impact surface and thus reduces the chance of unexpected surprises.

The downside is that the aliased Ok won't work for pattern matching:

match x with 
| Ok y -> ... // This is Ok from FParsec

If you need pattern matching as well, you'll have to alias the matcher too:

let (|Ok|Error|) x = match x with | Result.Ok o -> Ok o | Result.Error e -> Error e

At which point I would probably fall back to reopening the module.

Upvotes: 4

Related Questions