带有自定义数据的Haskell二叉搜索树

时间:2017-11-17 14:45:16

标签: haskell tree

我想创建自定义数据类型Book的二叉搜索树。 Book有两个属性,name和page。我想使用属性页作为树的节点。我一直坚持定义树。任何人都可以帮助我任何资源吗?这是我尝试过的代码(它不起作用)

import System.IO  
import Data.List  

data Book = Book{
    name:: String,
    page::Int
}deriving (Show)

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

singleton :: (Book _ x) -> Tree x   
singleton (Book _ x) = Node x EmptyTree EmptyTree  

treeInsert :: (Ord a) => a -> Tree a -> Tree a  
treeInsert (Book _ x) EmptyTree = singleton (Book _ x)
treeInsert (Book _ x) (Node a left right)   
    | x == a = Node x left right  
    | x < a  = Node a (treeInsert (Book _ x) left) right  
    | x > a  = Node a left (treeInsert (Book _ x) right)  

2 个答案:

答案 0 :(得分:0)

也许我们找出正确的类型签名。

我认为您希望TreeBook排序page

如果我们希望Tree只保留Book,我们就不需要对其进行参数化。但是,由于您确实参数化Tree,我们假设它可以保留的不仅仅是Book

在这种情况下,我们希望:

singleton :: a -> Tree a
treeInsert :: Ord a => a -> Tree a -> Tree a

a可以是Book,或任何其他合适的类型。但是,为了使treeInsertBook一起使用,我们需要Book拥有Ord个实例。

singleton函数只将整个a放入Node

singleton a = Node a EmptyTree EmptyTree

请注意,Book未出现在此定义中,因为它适用于所有类型。

insertTree函数也不会提及Book,但它会利用它所需的Ord实例。

修改

如果您希望Tree仅与Book一起使用,则应将其定义为:

data Tree = EmptyTree | Node Book Tree Tree

然后函数的类型签名变为:

singleton :: Book -> Tree
insertTree :: Book -> Tree -> Tree

singleton的实施与上述相同(只需将整个Book放入Node)。

由于insertTree现在知道它正在处理Book,因此它不再需要Ord实例,因为它只能获得page

它将开始:

treeInsert b EmptyTree = singleton b
treeInsert b (Node a l r)
    | page b == page a = ...

答案 1 :(得分:0)

我建议您使用所有图书实体,并为Ord制作Book个实例。

instance Eq Book where
    (Book _ n1) == (Book _ n2) = n1 == n2

instance Ord Book where
    (Book _ n1) > (Book _ n2) = n1 > n2

将代码更改为:

data Book = Book {
    name :: String,
    page :: Int
} deriving (Show)

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

singleton :: a -> Tree a   
singleton x = Node x EmptyTree EmptyTree  

treeInsert :: (Ord a) => a -> Tree a -> Tree 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)

您会看到(Book _ n)类型不正确,Book是。

treeInsert Book实施Ord以后,我会使用任意类型的值.tooltip{ display: inline; position: relative; /** very important set to relative*/