Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler rejects type signature of data constructor

Tags:

haskell

I am learning haskell. When I compile the code:

data Bintree a = Nulltree | Node (Bintree a) a (Bintree a)
Nulltree :: Bintree a

I get the following error:

Invalid type signature: Nulltree :: Bintree a Should be of form <variable> :: <type>

So how do I prevent this. I tried writing:

data Bintree a = Nulltree | Node (Bintree a) a (Bintree a)
Nulltree :: a -> Bintree a

but this gives the same error.

like image 888
abhinav mehta Avatar asked Nov 17 '25 05:11

abhinav mehta


1 Answers

In standard Haskell, you cannot give type signatures to data constructors. The line

data Bintree a = Nulltree | Node (Bintree a) a (Bintree a)

implies that Nulltree :: BinTree a. You don't need to say it yourself, and you can't. Using the GADTSyntax language extension, you could instead write

data Bintree a where
  Nulltree :: BinTree a
  Node :: Bintree a -> a -> Bintree a -> Bintree a

(Thanks to chi for pointing out that GADTSyntax is sufficient, and the not-so-beginner-friendly GADTs extension is not required.)

like image 72
dfeuer Avatar answered Nov 18 '25 19:11

dfeuer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!