Encapsulating data definitions in Haskell

和自甴很熟 提交于 2020-01-05 09:19:11

问题


I am trying to define a data type using other data types like this:

data A = Something String | SomethingElse Int

data B = Another B | YetAnother A

data C = A | B

x :: [ C ]
x = [ YetAnother (SomethingElse 0), Something "Hello World" ]

But this is giving me an error saying that I cannot have a type A when expecting a type B. Why is this?


回答1:


You're missing the data constructors for C.

data A = Something String
       | SomethingElse Int

data B = Another    B
       | YetAnother A

data C = C0 A
       | C1 B

x :: [ C ]
x = [ C1 (YetAnother (SomethingElse 0))
    , C0 (Something "Hello World")
     ]



回答2:


The A and B in data C = A | B are declarations of new data constructors, not references to your existing types A and B. (Constructors are not optional in data declarations.)




回答3:


Haskell does not have true "union" types, unions in Haskell must be tagged with constructors. (see Wikipedia > Tagged union).

Either is the general-purpose tagged union type in Haskell, where data is tagged as Left or Right.

data Either a b = Left a | Right b


来源:https://stackoverflow.com/questions/10553803/encapsulating-data-definitions-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!