https://wiki.haskell.org/Polymorphism说
Ad-hoc polymorphism refers to when a value is able to adopt any one of several types because it, or a value it uses, has been given a separate definition for each of those types. For example, the + operator essentially does something entirely different when applied to floating-point values as compared to when applied to integers – in Python it can even be applied to strings as well. Most languages support at least some ad-hoc polymorphism, but in languages like C it is restricted to only built-in functions and types. Other languages like C++ allow programmers to provide their own overloading, supplying multiple definitions of a single function, to be disambiguated by the types of the arguments. In Haskell, this is achieved via the system of type classes and class instances.
Despite the similarity of the name, Haskell's type classes are quite different from the classes of most object-oriented languages. They have more in common with interfaces, in that they specify a series of methods or values by their type signature, to be implemented by an instance declaration.
这是否意味着类型类是实现重载的一种方式,即临时多态性?
面向对象语言(例如 Java、C#)中的接口(interface)属于哪种多态性,即临时多态性(即重载)或子类型多态性?
谢谢。
最佳答案
类型 没有类型层次结构,但是 类型类 已。
我不会将类型类视为类继承,因为您没有父结构,您只有签名。它们可能被视为 OOP 语言的经典接口(interface),有点……
但正如你引用的文字所说:
For example, the
(+)
operator essentially does something entirely different when applied to floating-point values as compared to when applied to integers
像
(+)
这样简单的事情函数,跟类型都不是这样。您在这里有一个
TypeClass
Num
的层次结构尊重。例如plus :: Num a => a -> a -> a
plus x y = x + y
你有(我能数出来)四种直接亚型
Integral
(由 Int
和 Integral
实现)和 Fractional
(由 Float
和 Double
实现)。 Integral
和 Fractional
类型类是 Num
的子类型类型类。所以,看看这个函数类型签名:
(/) :: Fractional a => a -> a -> a
(div) :: Integral a => a -> a -> a
(+) :: Num a => a -> a -> a
每一个都有自己的实现,并限制您可以在子类型和父类(super class)型的类型层次结构中使用的数据类型,总是在谈论
Typeclass
而不是 类型本身 .关于与OOP的关系:
例如,在 Java 中,类型和类是完全不同的东西。看:
List<String> xs = new ArrayList<>();
List<String> ys = new LinkedList<>();
xs.add("Haskell");
ys.add("Forever");
那里的类型是
List
,但这些列表的行为由 给出类(class) (ArrayList 或 LinkedList)。更重要的是,您可以执行以下操作:
ArrayList<String> ls = new ArrayList<>();
ls.add("something);
有效,类型和类相同。
另一方面,在 Haskell 中不是这样,
(+)
方法行为由 给出根据类型类实现类型 .有一个经典有用的例子
Typeclass
Haskell 中的层次结构:关于oop - 接口(interface)属于即席多态性(即重载)还是子类型多态性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102313/