Abstract Data Types vs. Parametric Polymorphism in Haskell

不打扰是莪最后的温柔 提交于 2019-12-14 04:18:21

问题


I am trying to get a grip on the relationship between these two concepts.

First consider an example of an Abstract Data Type:

data Tree a = Nil 
            | Node { left  :: Tree a,
                     value :: a,
                     right :: Tree a }

According to Haskell wiki:

This type is abstract because it leaves some aspects of its structure undefined, to be provided by the user of the data type. This is a weak form of abstract data type. Source

Now consider the notion of parametric polymorphism:

Parametric polymorphism refers to when the type of a value contains one or more (unconstrained) type variables, so that the value may adopt any type that results from substituting those variables with concrete types. -- Source

Here an example of id :: a -> a is given:

For example, the function id :: a -> a contains an unconstrained type variable a in its type

Question: What is the formal relationship between these two concepts? In particular, are all instances of abstract data types also instances of parametric polymorphism? What about vice versa?


回答1:


Two things to realize. First, your example Tree is actually a parametric type, which is a special kind of abstract type. Second, parametric polymorphisms can be types or functions. With both of these things in mind, it is obvious that neither abstract types nor parametric polymorphisms are supersets of the other. However, any parametric polymorphism which is a type is also an abstract type. In otherwords, abstract types are a superset of parametrically polymorphic types (dunno if they're actually called that).




回答2:


The reason Tree is an abstract data type because it doesn't specify any of the details about how you implement it. How do you add a value to the tree? How do you remove a value? The type only defines the structure of the tree: it is either empty or a node that store a value of type a and references to two other trees.

Parametric polymorphism doesn't have anything to do with either the structure or the dynamics of the type. Instead, it refers to the fact that you have actually defined a family of related types. Whether you have a Tree Int, or a Tree Char, or a Tree (StateT (Int, Char) (MaybeT Float IO ())), the implementation will remain the same.



来源:https://stackoverflow.com/questions/36948114/abstract-data-types-vs-parametric-polymorphism-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!