Reputation: 155
I am trying to define a multi-way tree data type in ghci. Each node has a key and a value. Here is the related code:
data Tree k v = Empty |
N {key::k,
value::v} [Tree k v]
deriving (Show, Eq)
Here is corresponding output from Ghci:
Not in scope: `key'
Not in scope: `value'
I checked the syntax of the record by defining the tree node record separately using the following code:
data Node k v = Node { key::k
, value::v}
deriving (Show, Eq)
This works as expected. What is causing my Tree data type definition to throw this error? Am I missing something related to record syntax when used to define an alternate value constructor?
Upvotes: 1
Views: 976
Reputation: 116139
If you want to use a separate node type, you may be looking for something like
data Tree k v = Empty | N (Node k v) [Tree k v]
deriving (Show, Eq)
data Node k v = Node { key::k
, value::v}
deriving (Show, Eq)
Upvotes: 1
Reputation: 54058
When using the record syntax with ADTs, all constructors must have the same fields. Additionally, you're attempting to combine record and normal constructor syntax with Node { key :: k, value :: v } [Tree k v]
. Instead, you'll have to resort to normal positional arguments to your constructor like
data Tree k v
= Emtpy
| N k v [Tree k v]
deriving (Eq, Show)
You could use record syntax with ADTs as
data Tree k v
= RedNode { key :: k, val :: v, children :: [Tree k v] }
| BlackNode { key :: k, val :: v, children :: [Tree k v] }
deriving (Eq, Show)
But I would recommend making a separate data type as
data Color = Red | Black deriving (Eq, Show)
data Tree k v = Node
{ color :: Color
, key :: k
, val :: v
, children :: [Tree k v]
} deriving (Eq, Show)
Because then if you extend Color
, you have less typing, and I would argue that it's more idiomatic.
Upvotes: 4