Haskell - 作为内置类型的元组和列表:它们实际上是如何声明的?
Haskell - Tuples and Lists as built-in types: how are they actually declared?
在 "A gentle introduction to Haskell" 的第 2 章中,解释了用户定义类型,然后是内置类型的概念,除了特殊语法外,与用户定义类型没有什么不同:
Earlier we introduced several "built-in" types such as lists, tuples, integers, and characters. We have also shown how new user-defined types can be defined. Aside from special syntax, are the built-in types in any way more special than the user-defined ones? The answer is no. (The special syntax is for convenience and for consistency with historical convention, but has no semantic consequences.)
所以你可以像下面这样定义一个元组:
data (a,b) = (a,b)
data (a,b,c) = (a,b,c)
data (a,b,c,d) = (a,b,c,d)
这当然不能,因为那需要无数次声明。那么这些类型实际上是如何实现的呢?特别是关于只有针对类型声明才能进行模式匹配的事实?
您在那里定义了 三个 元组类型,而不是 一个 因此您对无限数量的声明的论点没有削减。一个标准的 confoming Haskell 只需要支持有限数量的元组类型。因此有有限多个声明。
其实你可以定义:
data Pair a b = Pair a b
这与普通二元组同构。
既然GHC是开源的,我们就看看吧:
元组没有你想象的那么神奇:
来自https://github.com/ghc/ghc/blob/master/libraries/ghc-prim/GHC/Tuple.hs
data (a,b) = (a,b)
data (a,b,c) = (a,b,c)
data (a,b,c,d) = (a,b,c,d)
data (a,b,c,d,e) = (a,b,c,d,e)
data (a,b,c,d,e,f) = (a,b,c,d,e,f)
data (a,b,c,d,e,f,g) = (a,b,c,d,e,f,g)
-- and so on...
因此,元数不同的元组只是不同的数据类型,不支持元数很大的元组。
列表也在那里:
来自https://github.com/ghc/ghc/blob/master/libraries/ghc-prim/GHC/Types.hs#L101
data [] a = [] | a : [a]
但是列表有一点魔力(特殊语法)。
注意:我知道 GitHub 不是开发 GHC 的地方,但是在 Google 上搜索 "ghc source code" 没有得到正确的页面,而 GitHub 是最简单。
在 "A gentle introduction to Haskell" 的第 2 章中,解释了用户定义类型,然后是内置类型的概念,除了特殊语法外,与用户定义类型没有什么不同:
Earlier we introduced several "built-in" types such as lists, tuples, integers, and characters. We have also shown how new user-defined types can be defined. Aside from special syntax, are the built-in types in any way more special than the user-defined ones? The answer is no. (The special syntax is for convenience and for consistency with historical convention, but has no semantic consequences.)
所以你可以像下面这样定义一个元组:
data (a,b) = (a,b)
data (a,b,c) = (a,b,c)
data (a,b,c,d) = (a,b,c,d)
这当然不能,因为那需要无数次声明。那么这些类型实际上是如何实现的呢?特别是关于只有针对类型声明才能进行模式匹配的事实?
您在那里定义了 三个 元组类型,而不是 一个 因此您对无限数量的声明的论点没有削减。一个标准的 confoming Haskell 只需要支持有限数量的元组类型。因此有有限多个声明。
其实你可以定义:
data Pair a b = Pair a b
这与普通二元组同构。
既然GHC是开源的,我们就看看吧:
元组没有你想象的那么神奇:
来自https://github.com/ghc/ghc/blob/master/libraries/ghc-prim/GHC/Tuple.hs
data (a,b) = (a,b)
data (a,b,c) = (a,b,c)
data (a,b,c,d) = (a,b,c,d)
data (a,b,c,d,e) = (a,b,c,d,e)
data (a,b,c,d,e,f) = (a,b,c,d,e,f)
data (a,b,c,d,e,f,g) = (a,b,c,d,e,f,g)
-- and so on...
因此,元数不同的元组只是不同的数据类型,不支持元数很大的元组。
列表也在那里:
来自https://github.com/ghc/ghc/blob/master/libraries/ghc-prim/GHC/Types.hs#L101
data [] a = [] | a : [a]
但是列表有一点魔力(特殊语法)。
注意:我知道 GitHub 不是开发 GHC 的地方,但是在 Google 上搜索 "ghc source code" 没有得到正确的页面,而 GitHub 是最简单。