我正在尝试以递归方式添加到Haskell中的二叉树。我正在关注Learn You A Haskell,只是做了一些修改,但我遇到了错误,我不明白:
data Male = Male { maleName :: String
, maleDOB :: Int
} deriving (Show, Read, Eq, Ord)
data Female = Female { femaleName :: String
, femaleDOB :: Int
} deriving (Show, Read, Eq, Ord)
data FamilyTree a = EmptyTree
| Node a (FamilyTree Female) (FamilyTree Male)
deriving (Show, Read, Eq, Ord)
singleton :: a -> FamilyTree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> FamilyTree a -> FamilyTree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
以下是我收到的错误消息:
Couldn't match type `Female' with `Male'
Expected type: Male
Actual type: a
In the first argument of `treeInsert', namely `x'
In the third argument of `Node', namely `(treeInsert x right)'
In the expression: Node a left (treeInsert x right)
我对Haskell很陌生,无法理解这里发生的事情。任何指向正确方向的指针都是受欢迎的!
答案 0 :(得分:2)
写作时
treeInsert :: Ord a => a -> FamilyTree a -> FamilyTree a
类型系统确保第一个参数的类型等于第二个参数的索引。这意味着您只能在以Male
开头的树中插入Male
。我想,这不是你想要的。
然而,这是一个很好的问题,我会回答它。
中的问题treeInsert :: Ord a => a -> FamilyTree a -> FamilyTree a
是a
远非一般。什么会
treeInsert :: Int -> FamilyTree Int -> FamilyTree Int
意思?您需要将a
限制为Female
或Male
。这是GADTs
的工作:
{-# LANGUAGE GADTs #-}
data Person a where
PFemale :: Female -> Person Female
PMale :: Male -> Person Male
Person
包含Female
或Male
,并在类型级别提供有关哪一个的信息。有了这个,我们可以定义
runPerson :: Person a -> a
runPerson (PFemale x) = x
runPerson (PMale x) = x
treeInsert :: Person a -> FamilyTree a -> FamilyTree a
treeInsert p EmptyTree = singleton (runPerson p)
treeInsert p@(PFemale x) (Node a left right)
| x == a = Node x left right
| otherwise = treeInsert p left
treeInsert p@(PMale x) (Node a left right)
| x == a = Node x left right
| otherwise = treeInsert p right
诀窍是,当您在Person a
a
上进行模式匹配时,会将其实例化为Female
或Male
,而不是其他内容。当a
为Female
时,您会继续插入&#34; Female
&#34;子树,否则 - 进入&#34; Male
&#34;。