Haskell的代数数据类型 [英] Haskell's algebraic data types

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

问题描述



代数数据类型与通用类型类似,例如C#和Java中的哪一种方式,我正在试图充分了解所有Haskell的概念。他们又如何不同?对他们来说,什么是代数?



我熟悉普遍代数及其环和字段,但我只对Haskell的类型工作有一个模糊的想法。


< Haskell中的div class =h2_lin>解决方案

代数数据类型支持全参数多态性,这是更为技术上正确的泛型名称,作为一个简单的例子列表数据类型:

 数据列表a =缺点a(列出a)| Nil 

等效(尽可能多,忽略非严格评估等) / p>

 类列表< a> {
class Cons:List< a> {
a head;
列表< a>尾巴;
}
class Nil:List< a> {}
}

当然,Haskell的类型系统允许更多...有趣的使用类型参数,但这只是一个简单的例子。关于代数类型的名称,我真的从来没有完全确定他们被命名的确切原因,而是认为是由于类型系统的数学基础。我相信,这个原因归结为ADT的理论定义是一组构造函数的产物,但是我已经离开大学已经有几年了,所以我不能再记得详细信息。



p>

I'm trying to fully understand all of Haskell's concepts.

In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway?

I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.

解决方案

"Algebraic Data Types" in Haskell support full parametric polymorphism, which is the more technically correct name for generics, as a simple example the list data type:

 data List a = Cons a (List a) | Nil

Is equivalent (as much as is possible, and ignoring non-strict evaluation, etc) to

 class List<a> {
     class Cons : List<a> {
         a head;
         List<a> tail;
     }
     class Nil : List<a> {}
 }

Of course Haskell's type system allows more ... interesting use of type parameters but this is just a simple example. With regards to the "Algebraic Type" name, i've honestly never been entirely sure of the exact reason for them being named that, but have assumed that it's due the mathematical underpinnings of the type system. I believe that the reason boils down to the theoretical definition of an ADT being the "product of a set of constructors", however it's been a couple of years since i escaped university so i can no longer remember the specifics.

[Edit: Thanks to Chris Conway for pointing out my foolish error, ADT are of course sum types, the constructors providing the product/tuple of fields]

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

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