Home > other >  What is difference between normal functions and typeclass functions?
What is difference between normal functions and typeclass functions?

Time:02-14

class (Typeable e, Show e) => Exception e where
    toException   :: e -> SomeException
    fromException :: SomeException -> Maybe e

    toException = SomeException
    fromException (SomeException e) = cast e
data MyException1 = Exception1A | Exception1B
    deriving (Show)
instance Exception MyException1

data MyException2 = Exception2A | Exception2B
    deriving (Show)
instance Exception MyException2

It is able to define multiple exceptions. So, multiple fromException functions are able to be defined too. I think it is weird because two functions can have same name and same input.

fromException :: SomeException -> Maybe MyException1
fromException :: SomeException -> Maybe MyException2

Even if the reason why this behavior is ok is "Two functions have different type include return type (and expressions are evaluated based these all types)", it is weird, because I can't define normal functions that way.

f :: Integer -> Maybe Integer
f = cast

f :: Integer -> Maybe Char
f n = cast $ show n

What is difference between normal functions and type class functions?

CodePudding user response:

The fact that you cannot define normal functions that way is the whole difference.

The whole purpose of type classes is to allow overloading - that is, defining multiple different functions with different types, but same name. And have the compiler pick the right one automatically based on types expected in the context.

  • Related