为什么 Haskell 代数数据类型是“封闭的"? [英] Why are Haskell algebraic data types "closed"?

查看:23
本文介绍了为什么 Haskell 代数数据类型是“封闭的"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我,但 Haskell 中的代数数据类型似乎在许多情况下很有用,您将在 OO 语言中使用类和继承.但是有一个很大的区别:代数数据类型一旦声明,就不能扩展到其他地方.它是封闭的".在 OO 中,您可以扩展已经定义的类.例如:

Correct me if I'm wrong, but it seems like algebraic data types in Haskell are useful in many of the cases where you would use classes and inheritance in OO languages. But there is a big difference: once an algebraic data type is declared, it can not be extended elsewhere. It is "closed". In OO, you can extend already defined classes. For example:

data Maybe a = Nothing | Just a

我无法在不修改此声明的情况下稍后以某种方式向此类型添加另一个选项.那么这个系统有什么好处呢?面向对象的方式似乎更具可扩展性.

There is no way that I can somehow add another option to this type later on without modifying this declaration. So what are the benefits of this system? It seems like the OO way would be much more extensible.

推荐答案

ADT 是封闭的这一事实使得编写完整的函数变得更加容易.这些函数总是为其类型的所有可能值产生结果,例如.

The fact that ADT are closed makes it a lot easier to write total functions. That are functions that always produce a result, for all possible values of its type, eg.

maybeToList :: Maybe a -> [a]
maybeToList Nothing  = []
maybeToList (Just x) = [x]

如果 Maybe 是打开的,有人可以添加一个额外的构造函数,maybeToList 函数会突然中断.

If Maybe were open, someone could add a extra constructor and the maybeToList function would suddenly break.

在 OO 中,这不是问题,当您使用继承来扩展类型时,因为当您调用没有特定重载的函数时,它只能使用超类的实现.即,如果 StudentPerson 的子类,您可以使用 Student 对象调用 printPerson(Person p) 就好了>.

In OO this isn't an issue, when you're using inheritance to extend a type, because when you call a function for which there is no specific overload, it can just use the implementation for a superclass. I.e., you can call printPerson(Person p) just fine with a Student object if Student is a subclass of Person.

在 Haskell 中,当您需要扩展类型时,通常会使用封装和类型类.例如:

In Haskell, you would usually use encapsulation and type classes when you need to extent your types. For example:

class Eq a where
   (==) :: a -> a -> Bool

instance Eq Bool where
  False == False = True
  False == True  = False
  True  == False = False
  True  == True  = True

instance Eq a => Eq [a] where
  []     == []     = True
  (x:xs) == (y:ys) = x == y && xs == ys
  _      == _      = False

现在,== 函数已经完全开放,您可以通过将其设为Eq 类的实例来添加您自己的类型.

Now, the == function is completely open, you can add your own types by making it an instance of the Eq class.

请注意,已经有关于可扩展数据类型的想法,但这绝对不是尚未成为 Haskell 的一部分.

Note that there has been work on the idea of extensible datatypes, but that is definitely not part of Haskell yet.

这篇关于为什么 Haskell 代数数据类型是“封闭的"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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