2016-12-30 59 views
2
  1. 爲什麼1.0 = 2.0不工作?是不是真的一個平等的類型?爲什麼我無法比較Standard ML中的實數?

    它給人的錯誤:

    Error: operator and operand don't agree [equality type required] 
        operator domain: ''Z * ''Z 
        operand:   real * real 
        in expression: 
        1.0 = 2.0 
    
  2. 爲什麼不會在模式雷亞爾工作像這樣的嗎?

    fun fact 0.0 = 1.0 
        | fact x = x * fact (x - 1.0) 
    

    它給出了錯誤:

    Error: syntax error: inserting EQUALOP 
    
+1

而不是對這個問題的答案作爲對不同問題的答案的一部分,在問題再次被問到時,這裏更容易連接。 –

+1

[cs.SE]網站有像這樣的問題的'reference-question'標籤。這樣的標籤會有幫助嗎? –

+1

@AntonTrunov:我不知道。這聽起來很有用,但我可能不會自己拿出來使用它。也許這是一種文化事物。也許在常規的StackOverflow中有相同的東西嗎? –

回答

4

Why doesn't 1.0 = 2.0 work? Isn't real an equality type?

號的類型變量''Z指示的=的操作數必須具有平等的類型。

Why won't reals in patterns work [...]?

模式匹配隱含地依賴於測試的相等性。神祕的錯誤信息syntax error: inserting EQUALOP表明SML/NJ解析器不允許在期望模式的情況下使用浮點文字,因此程序員不能接收更有意義的類型錯誤。

要精心,

http://www.smlnj.org/doc/FAQ/faq.txt

Q: Is real an equality type?

A: It was in SML '90 and SML/NJ 0.93, but it is not in SML '97 and SML/NJ 110. So 1.0 = 1.0 will cause a type error because "=" demands arguments that have an equality type. Also, real literals cannot be used in patterns.

http://mlton.org/PolymorphicEquality

The one ground type that can not be compared is real. So, 13.0 = 14.0 is not type correct. One can use Real.== to compare reals for equality, but beware that this has different algebraic properties than polymorphic equality.

http://sml-family.org/Basis/real.html

Deciding if real should be an equality type, and if so, what should equality mean, was also problematic. IEEE specifies that the sign of zeros be ignored in comparisons, and that equality evaluate to false if either argument is NaN.

These constraints are disturbing to the SML programmer. The former implies that 0 = ~0 is true while r/0 = r/~0 is false. The latter implies such anomalies as r = r is false, or that, for a ref cell rr, we could have rr = rr but not have !rr = !rr. We accepted the unsigned comparison of zeros, but felt that the reflexive property of equality, structural equality, and the equivalence of <> and not o = ought to be preserved.

簡短版本:不要使用相等比較實數。執行epsilon測試。我會推薦閱讀關於http://floating-point-gui.de/errors/comparison的文章,其中總結了一些陷阱。

相關問題