Why do all Haskell typeclasses have laws?

后端 未结 3 1348
既然无缘
既然无缘 2021-02-07 06:16

All the typeclasses in Typeclassopedia have associated laws, such as associativity or commutativity for certain operators. The definition of a \"law\" seems to be a constraint t

3条回答
  •  情歌与酒
    2021-02-07 07:07

    Yes and no. For instance the Show class does not have any laws associated with it, and it is certainly useful.

    However, typeclasses express interfaces. An interface needs to satisfy more than being just a bunch of functions - you want these functions to fulfill a specification. The specification is normally more complicated than what can be expressed in Haskell's type system. For example, take the Eq class. It only needs to provide us with a function, the type of which has to be a -> a -> Bool. That's the most that Haskell's type system will allow us to require from an instance of an Eq type. However, we would normally expect more from this function - you would probably want it to be an equivalence relation (reflexive, symmetric and transitive). So then you state these requirements as separate "laws".

提交回复
热议问题