简体   繁体   English

Haskell中嵌套空列表的列表

[英]list of nested empty lists in Haskell

Why is it possible to make such a list in Haskell: 为什么可以在Haskell中创建这样的列表:

slist = [ [], [[]], [[],[[]]] ]

As far I understand, every element has various types here (like in mathematics: Ø, {Ø} and so on). 据我所知,每个元素在这里都有各种类型(如数学:Ø,{Ø}等)。 And ghci says: 而且ghci说:

> :t []
[] :: [t]
> :t [[]]
[[]] :: [[t]]

formally, I see different notes. 正式地,我看到了不同的音符。

In other words, the first element is a simple empty list and the second one is a list of list (!) and so on. 换句话说,第一个元素是一个简单的空列表,第二个元素是列表(!)等等。

What is wrong? 怎么了? Why does Haskell consider them to be the same type? 为什么Haskell认为它们是同一类型?

You are right, that in a Haskell list, all elements must be of the same type. 你是对的,在Haskell列表中,所有元素必须是相同的类型。 And indeed, the type in your example is: 事实上,您的示例中的类型是:

> :t slist
slist :: [[[[a]]]]

But the empty list [] can have any type, as long as it's of the form [b] , but there are many possible b s. 但是空列表[]可以有任何类型,只要它的形式为[b] ,但有很多可能的b So there are many possible concrete types. 所以有很多可能的具体类型。 One of them is for b to be of type [[[a]]] , as in your slist . 其中一个是b类型[[[a]]] ,就像你的slist

Take a look at type of the first element of such a list: 看看这样一个列表的第一个元素的类型:

> head [ [], [[]], [[],[[]]] ]
[]
it :: [[[t]]]

It's not t , but it's [[[t]]] . 这不是t ,但它的[[[t]]]

Why I can possibility to make in Haskell such list 为什么我可以在Haskell中制作这样的列表

Because the is nothing wrong with the type of this expression. 因为这个表达式的类型没有错。

What is wrong? 怎么了? Why does Haskell consider them to be the same type? 为什么Haskell认为它们是同一类型?

t in the [[[[t]]]] is not a final type, it's type variable. t[[[[t]]]]是不是一个最终的类型,它的输入变量。 That's why the type of the first element of this list could be a or [b] or [[c]] or [[[t]]] . 这就是为什么这个列表的第一个元素的类型可以是a[b][[c]][[[t]]]

An empty list can be a list of any type. 空列表可以是任何类型的列表。 It can be a list of numbers, a list of strings, or a list of lists. 它可以是数字列表,字符串列表或列表列表。 I mean, why wouldn't you be allowed to have an empty list of lists or even an empty list of lists of lists? 我的意思是,为什么不允许你有一个空的列表列表,甚至是列表清单的空列表?

So in your list: 所以在你的清单中:

--a     b       c     d
[ [], [ [] ], [ [], [ [] ] ] ]

d is an empty list, c is an empty list of lists, b is an empty list of lists of lists and a is an empty list of lists of lists of lists. d是一个空列表, c是列表的空列表, b是列表的列表的空列表和a是列表的列表的列表的空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM