爲什麼
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
爲什麼不會在模式雷亞爾工作像這樣的嗎?
fun fact 0.0 = 1.0 | fact x = x * fact (x - 1.0)
它給出了錯誤:
Error: syntax error: inserting EQUALOP
回答
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 useReal.==
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的文章,其中總結了一些陷阱。
- 1. 這個Standard ML bubblesort的循環爲什麼只執行一次?
- 2. 爲什麼我無法在MFC中比較CString
- 3. 爲什麼我的比較程序無法正常工作?
- 4. Java:爲什麼我無法讀取和比較文本文件?
- 5. 爲什麼我無法比較這些十六進制值?
- 6. 什麼比較方法比較好?
- 7. 比較器爲什麼要實現Serializable?
- 8. 爲什麼NSNumber比較方法不同?
- 9. 爲什麼整數比較比字符串比較快?
- 10. 是什麼導致此Standard-ML類型錯誤?
- 11. 比較無法比較
- 12. 爲什麼set_symmetric_difference無法與比較器一起使用?
- 13. 比較兩個整數:爲什麼==真?
- 14. 爲什麼我使用簡單的json庫後無法比較字符串?
- 15. 爲什麼我無法比較getActionCommand()和匹配的字符串值?
- 16. pl-sql它無法比較兩個字符串?爲什麼
- 17. 爲什麼我們不能使用O-Notation來比較算法?
- 18. 爲什麼我的日期比較在JavaScript中不起作用?
- 19. 在MySQL中,爲什麼我的NULL值不能正確比較?
- 20. 爲什麼我在BASH中的比較工作?
- 21. 爲什麼字符串比較在我的代碼中失敗?
- 22. 爲什麼字符串實現可比較而不是比較器接口
- 23. 我的比較器有什麼問題?
- 24. 我想比較2個數組。爲什麼它不起作用?
- 25. 無法比較php
- 26. 爲什麼我無法
- 27. 爲什麼Backbone比較器不能比較兩個對象?
- 28. 爲什麼我無法在Haskell中使用id的Functor實例?
- 29. 爲什麼我無法在JBoss上的Solr中實例化DataImportHandler?
- 30. 與整數比較相比,爲什麼字符串比較如此之快?
而不是對這個問題的答案作爲對不同問題的答案的一部分,在問題再次被問到時,這裏更容易連接。 –
[cs.SE]網站有像這樣的問題的'reference-question'標籤。這樣的標籤會有幫助嗎? –
@AntonTrunov:我不知道。這聽起來很有用,但我可能不會自己拿出來使用它。也許這是一種文化事物。也許在常規的StackOverflow中有相同的東西嗎? –