Reputation: 383
For the following code I keep on getting a compiler error because I am writing (List _) and it is trying to pattern match over the list. How can I fix tihs?
data List a = Cons a (List a) | Empty
instance Monad List where
Empty >>= _ = Empty
Cons x (List _) >>= f = f x
Upvotes: 0
Views: 221
Reputation: 54979
data List a = Cons a (List a) | Empty
This defines a type constructor List
with two data constructors Cons
and Empty
. Cons
has two fields, one of type a
, and one of type List a
—which may, in turn, be either Empty
or a Cons
, and so on.
So when you write:
Cons x (List _) >>= f = f x
The compiler is looking for a data constructor called List
to pattern-match on, and there isn’t one—hence the error. If you just want to ignore the field, write:
Cons x _ >>= f = f x
Now of course this isn’t a proper Monad
instance for List
—it’s more like the one for Maybe
—but I’ll leave you to work through that on your own.
Upvotes: 7