[英]Standard definition of list
I have a problem with definition of list.我对列表的定义有疑问。 Normally is list defined as data [a] = [] | a : [a]
通常列表定义为data [a] = [] | a : [a]
data [a] = [] | a : [a]
but if I write something like this on my code concrete I will to define data T a = N | a -> (T a)
data [a] = [] | a : [a]
但如果我在我的代码上写这样的东西,我会定义data T a = N | a -> (T a)
data T a = N | a -> (T a)
the interpreter give me an error: data T a = N | a -> (T a)
解释器给我一个错误:
Malformed head of type or class declaration类型或类声明的格式错误的头
Do you know what's wrong?你知道怎么回事吗? . .
It looks like your problem is that you tried to use ->
as an infix constructor like :
(In order to build a list using a -> b -> N
syntax).看起来您的问题是您尝试使用->
作为中缀构造函数,例如:
为了使用a -> b -> N
语法构建列表)。 This isn't allowed because custom infix constructors in Haskell must begin with the :
character.这是不允许的,因为 Haskell 中的自定义中缀构造函数必须以:
字符开头。
The reason for your strange error message is because ->
in Haskell is reserved for function types, as Jeff's answer explains你奇怪的错误消息的原因是因为->
在 Haskell 中是为函数类型保留的,正如杰夫的回答所解释的
Try this instead:试试这个:
-- Create a right-associative infix constructor.
data T a = N | a :-> (T a)
infixr :->
mylist :: T Int
mylist = 10 :-> 17 :-> N
--If we hadn't made the operator right associative,
-- we would need to use explicit parenthesis here
myotherlist :: T Int
myotherlist = 10 :-> (17 :-> N)
-- Example function
isempty :: T a -> Bool
isempty N = True
isempty (_ :-> _) = False
a -> T a
would mean that a is a function that returns something of T a
so I think that's the bit that's wrong. a -> T a
意味着 a 是一个返回T a
的函数,所以我认为这是错误的。 Try something like this.尝试这样的事情。
data T a = N | R a (T a)
N is the empty list (equivalent of []
) value and R is the value constructor (equivalent to :
) N 是空列表(相当于[]
)值,R 是值构造函数(相当于:
)
On the right hand side you need some way of carrying the a
value around.在右侧,您需要某种方式来携带a
值。 You can now right lists like.您现在可以正确列出喜欢的列表。
> N -- The empty List
> R 5 N -- a list with a single element and then the end
> R 7 (R 6 (R 5 N)) -- the list 7, 6, 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.