3

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

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. We can derive more than one type class, but my question was I want to use the statement 'class (Eq a, Show a) => C a where', with this how can i resolve the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.