How does Haskell handle overloading polymorphism?

前端 未结 6 1629
余生分开走
余生分开走 2020-12-29 06:38

I have a question about Haskell polymorphism.

As I\'ve learned, there are two types of polymorphism:

  1. Parametric: where you do not spe

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-29 06:57

    You specify the type signature of your function in the original type class, then you create multiple instances of that function that you wrote the signature for. So, in the example hammar posted you can think of a as being polymorphic, and the type specified in each instance (e.g. instance Fooable Bool) as being the type of a (in this case a is a Bool). So when you call the function foo with a Bool value, the instance of Fooable for a Bool value gets called.

    BTW, you can put multiple functions in the type class, and you can define functions in terms of other functions defined as well.

    e.g.

    class  Eq a  where
        (==), (/=)  ::  a -> a -> Bool
    
        x /= y  = not (x == y)
        x == y  = not (x /= y)
    

    It may not be obvious here, but if you define an instance of Eq, you only need to define == or /=, not both, since they are defined in terms of each other.

提交回复
热议问题