Why isn't every type part of Eq in Haskell?

后端 未结 7 907
故里飘歌
故里飘歌 2020-12-31 04:48

Or rather, why isn\'t (==) usable on every data type? Why do we have to derive Eq ourseleves? In other languages, such as Python, C++, and surely o

7条回答
  •  隐瞒了意图╮
    2020-12-31 05:34

    Consider the following Python example:

    >>> 2 == 2
    True
    >> {} == {}
    True
    >>> set() == set()
    True
    >>> [1,2,3] == [1,2,3]
    True
    >>> (lambda x: x) == (lambda x: x)
    False
    

    False? o_O This of course makes sense if you realize that Python == compares pointer values, except when it doesn't.

    >>> f = (lambda x: x)
    >>> f == f
    True
    

    Haskell encourages == to always represent structural equality (and it always will if you use deriving Eq. Since nobody really knows a completely sound and tractable way to declare for certain whether or not two functions are structurally equivalent, there is no Eq instance for functions. By extension, any data structure that stores a function in it cannot be an instance of Eq.

提交回复
热议问题