OOP接口和FP类型的区别 [英] Difference between OOP interfaces and FP type classes

查看:120
本文介绍了OOP接口和FP类型的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

Java的接口和Haskell的类型类:差异和相似之处?

当我开始学习haskell时,我被告知类型类比接口更强大/不同。



一年后,我广泛使用的接口和类型类,并且我还没有看到它们如何不同的例子或解释。这不是一个自然而然的启示,我已经错过了一些显而易见的事实,或者实际上并没有真正的区别。



搜索互联网并没有发现任何东西可观。所以,你有答案吗?

解决方案

你可以从多个角度看这个。其他人会不同意,但我认为OOP接口是开始理解类型类的好地方(当然,相比之下,从无所作为)。

人们喜欢从概念上指出,类的分类类型很像集合 - 支持这些操作的类型集合,以及不能在语言本身编码的其他期望。这是有道理的,偶尔也会声明一个没有方法的类型类,并说只有当你的类型符合某些要求时,才能让你的类型成为这个类的一个实例。对于OOP接口,这种情况很少发生。



从具体的差异来看,类型类比OOP接口更强大的方法有多种:




  • 最大的一点是,类型类将类型实现接口的声明与类型本身声明分开。使用OOP接口,可以列出类型在定义类型时实现的接口,并且以后无法添加更多接口。对于类型类,如果你创建了一个新的类型给模块层次结构给定类型可以实现但不知道的类型,你可以编写一个实例声明。如果你有不同的第三方的类型和类型类,你可以编写一个实例声明。在OOP接口的类似情况下,你大多只是被卡住了,尽管OOP语言已经发展出了设计模式(适配器)来解决这个限制。

  • 下一个最大的(当然是主观的)是,尽管在概念上,OOP接口是一堆可以在实现接口的对象上调用的方法,类型类是可以用于成员类型的一堆方法的类。区别很重要。因为类型方法是参照类型而不是对象来定义的,所以将具有多个类型对象的方法作为参数(相等和比较运算符)或返回该类型的对象作为结果没有任何障碍各种算术运算),甚至类型的常量(最小和最大边界)。 OOP接口不能做到这一点,而OOP语言已经发展了设计模式(例如虚拟克隆方法)来解决这个限制。 为类型定义;类型类也可以为所谓的类型构造函数定义。使用各种C派生的OOP语言中的模板和泛型定义的各种集合类型是类型构造器:List将类型T作为参数并构造类型List< T> ;. Type类可以为类型构造函数声明接口:say,对集合类型的映射操作,它在集合的每个元素上调用提供的函数,并将结果收集到集合的新副本中 - 可能具有不同的元素类型!如果一个给定的参数需要实现多个接口,使用类型类,可以很容易地列出哪些接口它应该是一个成员;使用OOP接口,只能将一个接口指定为给定指针或引用的类型。如果你需要它来实现更多,你唯一的选择是没有吸引力的,例如在签名中写入一个接口并将其转换为其他接口,或者为每个接口添加单独的参数并要求它们指向相同的对象。你甚至不能通过声明一个继承自你需要的新的空接口来解决它,因为一个类型不会被自动视为实现你的新接口,因为它实现了它的祖先。 (如果你可以在事后声明实现,这不会是一个问题,但是,你也不能这样做。) 的情况下,可以要求两个参数的类型实现特定的接口,它们是相同的类型。使用OOP接口,您只能指定第一部分。
  • 类型类的实例声明更加灵活。使用OOP接口,只能说我声明了一个X类型,它实现了接口Y,其中X和Y是特定的。对于类型类,可以说其元素类型满足这些条件的所有列表类型都是Y的成员。 (你也可以说所有类型都是X和Y的成员也是Z的成员,尽管在Haskell中有很多原因是有问题的。)


  • 所谓的超类约束比单纯的接口继承更加灵活。使用OOP接口,只能说对于实现此接口的类型,它还必须实现这些其他接口。这也是类型类最常见的情况,但超类约束也允许你说SomeTypeConstructor< ThisType>必须实现某某接口或应用于该类型的此类型函数的结果必须满足所谓的这是当前Haskell中的语言扩展(与类型函数一样),但是您可以声明类型类涉及多种类型。例如,一个同构类:可以无损地从一个转换到另一个的类对类。再次,OOP接口不可能实现。


  • 我相信还有更多。




值得注意的是,在添加泛型的OOP语言中,其中一些限制可以被删除(第四,第五,可能是第二点)。 b
$ b

另一方面,OOP接口可以做的事情有两个重要的事情,本质上类型类不会:


  • 运行时动态分派。在OOP语言中,传递和存储指向实现接口的对象的指针并在运行时调用其方法是微不足道的,该方法将根据对象的动态运行时类型进行解析。相比之下,类型约束默认情况下都是在编译时确定的 - 也许令人惊讶的是,在绝大多数情况下,这是您所需要的。如果您确实需要动态分派,那么您可以使用所谓的存在类型(目前是Haskell中的语言扩展):一个构造,它忘记了对象的类型,并且只能记住(根据您的选择)它遵守某些类型的类约束。从这一点来看,它的行为基本上与用OOP语言实现接口的对象的指针或引用完全相同,类型类在这方面没有不足。 (应该指出,如果你有两个实现相同类型类的存在和一个类型类方法,它需要两个类型的参数,你不能使用存在作为参数,因为你不知道是否存在的类型是相同的,但与OOP语言相比,首先不能有这样的方法,这并不算什么损失。)

  • 运行时将对象转换为接口。在OOP语言中,你可以在运行时获取指针或引用,并测试它是否实现了一个接口,如果有,则将其转换到该接口。类型类本身没有任何等价的东西(这在某些方面是一个优点,因为它保留了一个名为'parametricity'的属性,但我不会在这里进行讨论)。当然,没有什么能阻止你添加一个新的类型类(或增加一个现有的类)和方法来将类型的对象转换为你想要的任何类型类的存在。 (你也可以像图书馆一样实现这种功能,但涉及更多,我计划完成并将其上传到Hackage ,我保证!)

  • >


(我应该指出,虽然你可以做这些事情,但许多人认为模仿OOP这种方式很糟糕,并建议你更直接地使用解决方案,比如显式的函数记录,而不是类型类,对于全功能的第一类函数,这个选项不会那么强大。)

在操作上,OOP接口通常被实现通过在对象本身中存储一个或多个指针来指向对象实现的接口的函数指针表。类型类通常通过字典传递来实现(对于像Haskell一样通过装箱实现多态的语言,而不是像C ++那样的多实例多态):编译器隐式地将指针传递给函数表(以及常量)作为使用类型类的每个函数的隐藏参数,无论涉及多少个对象,函数都会获得一个副本(这就是为什么您需要执行上述第二点中提到的操作)。存在类型的实现看起来很像OOP语言所做的事情:指向类型类字典的指针与对象一起存储为证据,即已忘记类型是其成员。

如果您曾经阅读过有关C ++的概念提案(因为它最初是针对C ++ 11提出的),它基本上是Haskell为C ++重新构想的类型类模板。我有时会认为,拥有一种简单地使用C ++ - with-concepts的语言,将一半的面向对象和虚拟函数剔除,清理语法和其他瑕疵,并在需要运行时添加存在类型基于类型的动态调度。 (更新: Rust 基本上就是这样,还有很多其他好东西。)


Possible Duplicate:
Java's Interface and Haskell's type class: differences and similarities?

When I started learning haskell I was told that typeclasses are more powerful than/different to interfaces.

One year later, I've used interfaces and typeclasses extensively and I've yet to see an example or explanation of how they are different. It's either not a revelation that comes naturally, I've missed something obvious, or there is in actual fact no real difference.

Searching the internet hasn't turned up anything substantial. So SO, do you have the answer?

解决方案

You can look at this from multiple angles. Other people will disagree, but I think OOP interfaces are a good place to start from to understand type classes (certainly compared to starting from nothing at all).

People like to point out that conceptually, type classes classify types, much like sets - "the set of types which support these operations, along with other expectations which can't be encoded in the language itself". It makes sense and is occasionally done to declare a type class with no methods, saying "only make your type an instance of this class if it meets certain requirements". That happens very rarely with OOP interfaces.

In terms of concrete differences, there are multiple ways in which type classes are more powerful than OOP interfaces:

  • The biggest one is that typeclasses decouple the declaration that a type implements an interface from the declaration of the type itself. With OOP interfaces, you list the interfaces a type implements when you define it, and there's no way to add more later. With type classes, if you make a new type class which a given type "up the module hierarchy" could implement but doesn't know about, you can write an instance declaration. If you have a type and a type class from separate third parties which don't know about each other, you can write an instance declaration. In analogous cases with OOP interfaces, you're mostly just stuck, though OOP languages have evolved "design patterns" (adapter) to work around the limitation.

  • The next biggest one (this is subjective, of course) is that while conceptually, OOP interfaces are a bunch of methods which can be invoked on objects implementing the interface, type classes are a bunch of methods which can be used with types which are members of the class. The distinction is important. Because type class methods are defined with reference to the type, rather than the object, there's no obstacle to having methods with multiple objects of the type as parameters (equality and comparison operators), or which return an object of the type as a result (various arithmetic operations), or even constants of the type (minimum and maximum bound). OOP interfaces just can't do this, and OOP languages have evolved design patterns (e.g. virtual clone method) to work around the limitation.

  • OOP interfaces can only be defined for types; type classes can also be defined for what are called "type constructors". The various collection types defined using templates and generics in the various C-derived OOP languages are type constructors: List takes a type T as an argument and constructs the type List<T>. Type classes let you declare interfaces for type constructors: say, a mapping operation for collection types which calls a provided function on each element of a collection, and collects the results in a new copy of the collection - potentially with a different element type! Again, you can't do this with OOP interfaces.

  • If a given parameter needs to implement multiple interfaces, with type classes it's trivially easy to list which ones it should be a member of; with OOP interfaces, you can only specify a single interface as the type of a given pointer or reference. If you need it to implement more, your only options are unappealing ones like writing one interface in the signature and casting to the others, or adding separate parameters for each interface and requiring that they point to the same object. You can't even resolve it by declaring a new, empty interface which inherits from the ones you need, because a type won't automatically be considered as implementing your new interface just because it implements its ancestors. (If you could declare implementations after the fact, this wouldn't be such a problem, but yeah, you can't do that either.)

  • Sort of the reverse case of the one above, you can require that two parameters have types that implement a particular interface and that they be the same type. With OOP interfaces you can only specify the first part.

  • Instance declarations for type classes are more flexible. With OOP interfaces, you can only say "I'm declaring a type X, and it implements interface Y", where X and Y are specific. With type classes, you can say "all List types whose element types satisfy these conditions are members of Y". (You can also say "all types which are members of X and Y are also members of Z", although in Haskell this is problematic for a number of reasons.)

  • So-called "superclass constraints" are more flexible than mere interface inheritance. With OOP interfaces, you can only say "for a type to implement this interface, it must also implement these other interfaces". That's the most common case with type classes as well, but superclass constraints also let you say things like "SomeTypeConstructor<ThisType> must implement so-and-so interface", or "results of this type function applied to the type must satisfy so-and-so constraint", and so on.

  • This is a currently a language extension in Haskell (as are type functions), but you can declare type classes involving multiple types. For example, an isomorphism class: the class of pairs of types where you can losslessly convert from one to the other and back. Again, not possible with OOP interfaces.

  • I'm sure there's more.

It's worth noting that in OOP languages which add generics, some of these limitations can be erased (fourth, fifth, possibly second points).

To the other side, there's two significant things which OOP interfaces can do and type classes natively don't:

  • Runtime dynamic dispatch. In OOP languages, it's trivial to pass around and store pointers to an object implementing an interface, and invoke methods on it at runtime which will be resolved according to the dynamic, runtime type of the object. By contrast, type class constraints are by default all determined at compile time -- and perhaps surprisingly, in the vast majority of cases this is all you need. If you do need dynamic dispatch, you can use what are called existential types (which are currently a language extension in Haskell): a construct where it 'forgets' what the type of an object was, and only remembers (at your option) that it obeyed certain type class constraints. From that point, it behaves basically in the exact same way as pointers or references to objects implementing interfaces in OOP languages, and type classes have no deficit in this area. (It should be pointed out that if you have two existentials implementing the same type class, and a type class method which requires two parameters of its type, you can't use the existentials as parameters, because you can't know whether or not the existentials had the same type. But compared to OOP languages, which can't have such methods in the first place, this is no loss.)

  • Runtime casting of objects to interfaces. In OOP languages, you can take a pointer or reference at runtime and test whether it implements an interface, and 'cast' it to that interface if it does. Type classes don't natively have anything equivalent (which is in some respects an advantage, because it preserves a property called 'parametricity', but I won't get into that here). Of course, there's nothing stopping you from adding a new type class (or augmenting an existing one) with methods to cast objects of the type to existentials of whichever type classes you want. (You can also implement such a capability more generically as a library, but it's considerably more involved. I plan to finish it and upload it to Hackage someday, I promise!)

(I should point out that while you *can* do these things, many people consider emulating OOP that way bad style and suggest you use more straightforward solutions, such as explicit records of functions instead of type classes. With full first-class functions, that option is no less powerful.)

Operationally, OOP interfaces are usually implemented by storing a pointer or pointers in the object itself which point to tables of function pointers for the interfaces the object implements. Type classes are usually implemented (for languages which do polymorphism-by-boxing, like Haskell, rather than polymorphism-by-multiinstantiation, like C++) by "dictionary passing": the compiler implicitly passes the pointer to the table of functions (and constants) as a hidden parameter to each function which uses the type class, and the function gets one copy no matter how many objects are involved (which is why you get to do the things mentioned in the second point above). The implementation of existential types looks a lot like what OOP languages do: a pointer to the type class dictionary is stored along with the object as 'evidence' that the 'forgotten' type is a member of it.

If you've ever read about the 'concepts' proposal for C++ (as it was originally proposed for C++11), it's basically Haskell's type classes reimagined for C++'s templates. I sometimes think it would be nice to have a language which simply takes C++-with-concepts, rips out the object-oriented and virtual functions half of it, cleans up the syntax and other warts, and adds existential types for when you need runtime type-based dynamic dispatch. (Update: Rust is basically this, with many other nice things.)

这篇关于OOP接口和FP类型的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆