Java – interpreting type classes in Haskell

I am a C / Java programmer. The main example I use in daily programming is OOP In some threads, I read a comment that type classes are inherently more intuitive than OOP Can anyone explain the concept of type class in simple words so that OOP people like me can understand it?

Solution

First of all, I always doubt that this or that program structure is more intuitive Programming is counter intuitive, because people think naturally according to specific situations rather than general rules Changing this requires training and practice, otherwise it is called "learning programming"

Continuing to discuss this issue, the key difference between OO class and Haskell type class is that in OO, class (even interface class) is also the type and template of new type (descendant) In Haskell, type classes are just templates for new types More precisely, a type class describes a set of types that share a common interface, but it is not a type itself

Therefore, the type class "num" describes numeric types with addition, subtraction and multiplication operators The integer type is an instance of num, which means that integer is a member of a set of types that implement these operators

So I can write a summation function of this type:

sum :: Num a => [a] -> a

The bitwise operator to the left of "= >" says "sum" will apply to any type of "a", which is an instance of num The bit on the right indicates that it needs a list of values of type "a" and returns a value of type "a" Therefore, you can use it to summarize integer lists or double lists or complex lists, because they are all instances of "num" Of course, the '' operator will be used for the execution of "sum", which is why you need the "num" type constraint

But you can't write this:

sum :: [Num] -> Num

Because "num" is not a type

This difference between type and type is why we don't talk about inheritance and descendant types in Haskell There is an inheritance for type classes: you can declare one type class as a descendant of another The offspring here describe a subset of the types described by the parents

An important result of all this is that you cannot have heterogeneous lists in Haskell In the "sum" example, you can pass a list of integers or a list of doubles, but you cannot mix doubles and integers in the same list This looks like a tricky limitation; How do you implement the old example of "cars and trucks are models"? Several answers depend on the problem you actually want to solve, but the general principle is that you use first-order functions, explicitly use indirect methods, rather than implicitly use virtual functions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>