[英]Haskell beginner - defining and using a type
I am trying to do the equivalent of this correctly working code : 我正在尝试等效于此正确工作的代码:
len :: [a] -> Int
len [] = 0
len (x:xs) = 1 + len xs
But for the type MyList that I am defining as : 但是对于我定义为的MyList类型:
data MyList a = Nil | Cons a (MyList a)
Here is my attempt : 这是我的尝试:
mylen :: (MyList a) -> Int
mylen Nil = 0
mylen (Cons a (MyList a)) = 1 + mylen (MyList a)
But I get these errors: 但是我得到这些错误:
Conflicting definitions for 'a' “ a”的定义相互矛盾
Not in scope: data constructor 'MyList' 不在范围内:数据构造函数“ MyList”
I can't figure out how to get it to work. 我不知道如何使它工作。
Your (reasonable) definition of MyList
: 您对MyList
(合理的)定义:
data MyList a = Nil | Cons a (MyList a)
...states that there are two constructors. ...说明有两个构造函数。
Nil
(taking no arguments), and Nil
(不带任何参数),和 Cons
, which takes two arguments: the first of type a
, the second of type MyList a
Cons
,它有两个参数:第一个是a
类型,第二个是MyList a
类型 So to pattern match, you have to write something like Cons item rest
, eg 因此,要进行模式匹配,您必须编写类似Cons item rest
,例如
mylen :: (MyList a) -> Int
mylen Nil = 0
mylen (Cons item rest) = 1 + mylen rest
But since you never use item
, it is customary to replace it with _
. 但是由于您从不使用item
,因此习惯上用_
代替它。
Notice how a
, Int
and MyList a
are types. 注意a
, Int
和MyList a
是如何类型的。 On the other hand, item
, 0
and 1
, rest
, and even Nil
and Cons item rest
are all instances of those types. 另一方面, item
, 0
和1
, rest
,甚至Nil
和Cons item rest
都是这些类型的实例。
mylen :: MyList a -> Int
mylen Nil = 0
mylen (Cons _ next) = 1 + mylen next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.