简体   繁体   中英

Haskell: type classes: multiple inheritance example

I came to know that we can achieve multiple inheritance using type classes. I had written small haskell code, but unable to figure out the problem.

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE StandaloneDeriving #-}

class (Eq a, Show a) => C a where
    getHashCode :: a -> Integer
    getHashCode obj = 123


type Id = Int
type Name = String

data Employee = Employee Id Name deriving C

When i tried to load above code, I am getting following error. Any help on this.

 No instance for (Eq Employee)
      arising from the 'deriving' clause of a data type declaration
   Possible fix:
      use a standalone 'deriving instance' declaration,
        so you can specify the instance context yourself
    When deriving the instance for (C Employee)
Failed, modules loaded: none.

I searched google some time, but unable to found good example for multiple inheritance. it will be helpful if you provide some info, example on multiple inheritance in Haskell.

Reference: https://www.haskell.org/tutorial/classes.html

Saying

class (Eq a, Show a) => C a where

does not mean that types that implement C automatically implement Eq and Show , it means that they must first implement Eq and Show before they can implement C .

A class in Haskell is not the same as a class in Java, either, it's closer to an interface, but it can't be used in the same ways (and shouldn't). Haskell doesn't actually have a concept of inheritance or classes in the OOP sense, as it's not an OOP language.

However, if you want to have Eq and Show instances automatically for a type, just add them to the deriving clause of the data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM