简体   繁体   中英

How do type classes work in Haskell?

I am really confused about classes in haskell. If I had the code:

class GetResult n where res :: n -> Int
class (GetResult n) => Model n where
                                     starting :: Int -> [Int] -> n
                                     starting i j = .....
                                     test :: n -> n
                                     test n = ......

What type is n? What type would starting output and test take as input?

Your confusion might be caused by the fact that type classes in Haskell have nothing to do with classes in OO. Most importantly type classes don't describe objects, they describe types.

A type class describes a set of methods. You can implement those methods for a given type to make that type an instance of the class. So your type class definition of GetResult can be read as "A type n can be made an instance of GetResult by implementing the method res of type n -> Int ". So n is simply the type that wants to become an instance of GetResult .

As an example if you wanted to make Int an instance of GetResult , you could use the following instance declaration:

instance GetResult Int where
    res :: Int -> Int
    res i = i

In this case n would be Int .

n is a type variable, not any particular type. Particular types can be made instances of GetResult and Model , and each instance will "fill in the blanks" in the types of the functions defined in the class.

So the full type of starting is (you can get this from ghci with :t starting ):

starting :: Model n => Int -> [Int] -> n

You can read this as "for any type which is an instance of Model , starting takes an Int and a [Int] and returns a value of that type". Likewise test takes any type which is an instance of Model and returns a value of the same type.

At any particular call of starting , the type returned will be determined by the context; it will return a value of whatever type its return value is used as in that context (assuming a suitable instance exists).

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