FsUnit and floating point equality

I started using FsUnit to test F # code. This allows you to express a statement in the style of F #, for example:

[<Test>]
member this.``Portugal voted for 23 countries in 2001 Eurovision contest``() =
    this.totalVotes 
    |> getYearVotesFromCountry "Portugal" 2001
    |> Seq.length
    |> should equal 23

The "should be 23" note that I get from FsUnit. Here, as FsUnit defines:

let equal x = new EqualConstraint (x)

With floating point numbers, this is not so simple. I have to use the EqualConstraint method with the Inside method. This naturally fits C #:

Assert.That(result).Is.EqualTo(1).Within(0.05);

Of course, I would like to be able to write in F #:

result |> should equal 1 within 0.05

But that does not work. I ended up defining a new function:

let almostEqual x = (new EqualConstraint(x)).Within(0.01)

or if I want to parameterize accuracy, I can specify it as the second argument:

let equalWithin x y = (new EqualConstraint(x)).Within(y)

. "" F #, . F # , , , "" , "".

?

+3
2

! , within 0.05 should equal . should, .

F # - +/-. , , :

0.9 |> should equal (1.0 +/- 0.5)

, equal. :

type Range = Within of float * float
let (+/-) (a:float) b = Within(a, b)

let equal x = 
  match box x with 
  | :? Range as r ->
      let (Within(x, within)) = r
      (new EqualConstraint(x)).Within(within)
  | _ ->
    new EqualConstraint(x)
+12

: F # ; let-bound ( "" , ).

, , should.equal , equal - should, . , . .

Well, I have nothing to offer. Personally, I don't like these syntactic sugars in libraries.

0
source

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


All Articles