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 :
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'
Not in scope: data constructor 'MyList'
I can't figure out how to get it to work.
Your (reasonable) definition of MyList
:
data MyList a = Nil | Cons a (MyList a)
...states that there are two constructors.
Nil
(taking no arguments), and Cons
, which takes two arguments: the first of type a
, the second of type MyList a
So to pattern match, you have to write something like Cons item rest
, eg
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 _
.
Notice how a
, Int
and MyList a
are types. On the other hand, item
, 0
and 1
, rest
, and even Nil
and Cons item rest
are all instances of those types.
mylen :: MyList a -> Int
mylen Nil = 0
mylen (Cons _ next) = 1 + mylen next
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.