banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

Haskell Type and TypeClass

Types#

:t value

You can view the type of data, Haskell is a strongly typed language.

The same goes for functions.

For example:

fun :: [Char] -> [Char]

For the function fun, the parameter must be a char array, which is equivalent to String.

Type Classes#

Type classes are used to define a common interface.

Provide a common set of characteristics for various types.

Similar to interfaces:

class typeclassname a where
    funtionname :: a -> a -> returntype

Can be compared to Java:

interface<T,R> name{
    R funtion(T t,T t);
}

Then implement instances of type classes

instance typeclassname type where
    funtionname arg arg = return

For example:

class EqualClass a where
    equalFun :: a->a->Bool


instance EqualClass Bool where
    equalFun True True = True
    equalFun True False = False
    equalFun False False = True
    equalFun _ _ = False
    --XNOR

Comparing to Java:

class interfaceImpl<Bool,Bool> implement interface{
    Bool funtion(Bool l, Bool r){
        retutn !(l^r);
        //XNOR
    }
}

Therefore, type classes are more like interfaces, allowing for different behaviors of functions under different class implementations.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.