English 中文(简体)
统一并检查浮动点数的平等
原标题:FsUnit and checking equality of floating point numbers

我开始使用FsUnit测试F#代码。 它可以在F#风格上表达主张,例如:

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

我从FsUnit那里获得的“可能等于23”。 在这里,联邦大学如何界定:

平等×=新的平等

浮动点数并不简单。 我必须在方法上实行平等。 C#:

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

当然,我想在F#中写一下:

result |> should equal 1 within 0.05

但这并不可行。 我最后确定了一项新的职能:

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

或者,如果我想降低精确度,我可以把它作为第二点:

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

但是,他们当中没有一人tty。 我想以更自然的方式界定F#的“随身”功能,以便与平等一起使用。 F#不支持超负荷的方法,因此,它像我这样认为,可以这样“平等”单独使用或与“随身”一起使用。

任何想法?

最佳回答

这是一个令人感兴趣的问题! 我不认为,你可以以任何方式将<条码>与0.05与<条码>的现有定义相匹配。 为此,你需要在<条码>中添加参数,但需要在图书馆中设置一定数量的参数。

通常在F#中写这种字句的一个办法是建立海关操作员+/。 请注意,你仍然需要使用母体,但认为:

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

运营商只是构造一种特殊类型的某种价值,需要在<条码>上明确处理。 执行:

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)
问题回答

术语说明:F#确实支持method超载;它不支持超载限量功能>(模块中定义的自由功能)。

比如,请将<代码>should. Equal with a dot, 以便quality is a means on the shouldbject, 您可以超负荷。 虽然这仍然有帮助,因为你可以超负荷处理好的论点。 Hmmm.

奥基先生,我没有什么帮助。 我个人不喜欢图书馆中的这类合成糖。





相关问题
F#: Storing and mapping a list of functions

I have a number of events that happen in a game. I want to control the time and order at which these events occur. For example: Event 1: Show some text on screen for N frames & play a sound ...

Creating Silverlight 3 applications with F#

Is there an easy way to create Silverlight 3 applications with F# (October CTP)? I have seen the F# for Silverlight, but that only works with the May CTP. I am using Visual Studio Integrated Shell ...

How To Change List of Chars To String?

In F# I want to transform a list of chars into a string. Consider the following code: let lChars = [ a ; b ; c ] If I simply do lChars.ToString, I get "[ a ; b ; c ]". I m trying to get "abc". I ...

Unzipping ZLIB compressed portions of a binary file

I m reading a file(a flash swf) from .Net 3.5 that has a header which states whether the body of the file/Stream is compressed or not. However, I m having problems-after I rewrap the basic File ...

Pretty print a tree

Let s say I have a binary tree data structure defined as follows type a tree = | Node of a tree * a * a tree | Nil I have an instance of a tree as follows: let x = Node (Node (...

F# String Pattern-Matching with Wildcards

As part of a project I have assigned myself as a way of improving my knowledge of F# and functional programming in general, I am attempting to write a string pattern-matching algorithm from scratch ...

热门标签