Haskell数据类型列表 [英] Haskell lists of datatypes
问题描述
data地方=国家
|州
| City String
导出显示
数据State = California
|纽约
派生显示
数据国家=美国
|加拿大
派生显示
我可以合法地列出[美国,加拿大]键入[国家]或类型为[州]的[国家]或[加利福尼亚州,纽约州]或类型为[地点]的[城市a,城市b]。
我需要做些什么才能制作[美国,纽约]等列表?纽约是一个地方的国家,美国是一个地方的国家,但ghci看到美国,所以它假设我正在制作一个国家的名单(纽约是一个国家,所以名单失败)。
我想我需要某种方式将国家或国家投放到某个地方,但是我对如何实现这一点感到茫然。
我试图避免将包含在State和Country中的数据放到Place类型中,我知道它会使其工作,但我拥有相当数量的真实数据,我宁愿不混杂
这里有更多的输出让我找出问题所在:
*主要> [州,州]
[州,州]
*主要> :t State
State :: Place
* Main> :t NewYork
NewYork :: State
这似乎意味着State是Place的有效构造函数,而数据状态指的是仅加利福尼亚或纽约的值。
如果您稍微更改程序,则:
数据地方=国家国家
| State State
| City String
导出显示
数据State = California
|纽约
派生显示
数据国家=美国
|加拿大
派生显示
然后您可以创建一个列表,例如[Country USA,State NewYork ]这是正确的类型[地方]。使用与第一个示例中相同的单词两次不会按照我原先认为的方式将State类型绑定在一起。
当然,使用构造方法State状态只是一个偏好问题,如果我喜欢,我可以轻松地在Place类型中做 AmericanState State
。
This is probably another easy Haskell question. If I have some "nested" data types, such as in this example code:
data Place = Country
| State
| City String
deriving Show
data State = California
| NewYork
deriving Show
data Country = USA
| Canada
deriving Show
I can legally make a list such as [USA, Canada] of type [Country], or [California, NewYork] of type [State], or [City "a", City "b"] of type [Place].
What do I have to do to make a list such as [USA, NewYork]? NewYork is a State which is a Place, and USA is a Country which is a Place, but ghci sees USA so it assumes I am making a list of Countrys (and NewYork is a State, so the list fails).
I think I need some way to cast a Country or State to a Place, but I'm at a loss on how to accomplish this.
I'm trying to avoid throwing the data contained within State and Country into the Place type, which I know would make it work, but I've got a decent amount of real data that I'd rather not jumble up like that.
Here's a little more output that led me to figure out the problem:
*Main> [State, State]
[State,State]
*Main> :t State
State :: Place
*Main> :t NewYork
NewYork :: State
This seems to imply that the word "State" is a valid constructor for Place, and that the data State refers to a value of only California or NewYork.
If you change the program slightly, to:
data Place = Country Country
| State State
| City String
deriving Show
data State = California
| NewYork
deriving Show
data Country = USA
| Canada
deriving Show
then you can make a list such as [Country USA, State NewYork] which is properly of type [Place]. Using the same word twice as in the first example does not "bind" the State type together in the way I had thought it would.
Of course, using the constructor State State is just a matter of preference, I could just as easily do AmericanState State
within the Place type if I were so inclined.
这篇关于Haskell数据类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!