Reputation: 59
I am trying to define a data type in Haskell. This datatype will be called Node. It will be able to contain a parametric type a or Nothing. I defined it so:
data Node a = Node (Maybe a) deriving (Show)
When I load it in GHC the following works Node Nothing
However when I type this for example Node (6)
I get the following error:
Non type-variable argument in the constraint: Num (Maybe a)
(Use FlexibleContexts to permit this)
When checking that ‘it’ has the inferred type
it :: forall a. Num (Maybe a) => Node a
Why is that? what am I doing wrong?
Upvotes: 1
Views: 132
Reputation: 33881
The statement data Node a = Node (Maybe a) deriving (Show)
creates a data constructor (which is a function) of type Node :: Maybe a -> Node a
in other words, you need to pass a value of type Maybe a
to this function.
You have passed 6
which is not of type Maybe a
.
Instead you can pass a Just 6
value like so:
Node (Just 6)
.
Upvotes: 5
Reputation: 24314
You have defined your datatype using Maybe
, so you have to wrap the value in Just
:
Node (Just 6).
If you just want to have a type which can be either empty or have defined value, define it in the following way:
data Node b = Empty | Node b deriving (Show)
Upvotes: 4