在haskell中查找二叉树中变量的出现次数

时间:2012-04-04 10:58:55

标签: haskell binary-tree

我想在任何树中找到某个数字的出现次数。这里是我的代码,但它给出了一个错误,我无法找到它为什么会发生。

data Tree a = Empty | Node (a ,Tree a,Tree a) deriving (Show)

occurst _ Empty = 0     -- this line occurs error
occurst a ( Node (x,left,right) ) = if x==Empty then 0
            else if a==x then 1 + (occurst a left) + (occurst a right)
            else (occurst a left) + (occurst a right)  


j=let t = Node (3 , Node (2 , Node (1 , Empty , Empty ) , Node (1 , Empty , Empty )),Node     (1 , Node (2 , Node (1 , Empty , Empty ) , Node (1 , Empty , Empty )),Node    (1,Empty,Empty)))  
  in occurst 1 t

错误信息是:

ERROR "treeExample.hs":95 - Cannot infer instance
*** Instance   : Eq (Tree a)
*** Expression : occurst

输入输出必须是:

occurst 1 t -> 6
occurst 2 t -> 2
occurst 3 t ->1
occurst 4 t ->0

3 个答案:

答案 0 :(得分:3)

您可以非常简洁地编写您的功能:

occurst _ Empty = 0   
occurst a ( Node (x,left,right) ) = 
   fromEnum (x==a) + (occurst a left) + (occurst a right)  

fromEnumEnum转换为Int,幸运的是Bool实际上只有Enum,但False映射为0和True到1。

答案 1 :(得分:2)

行中有一个错误

occurst a ( Node (x,left,right) ) = if x==Empty then 0

你说xTree ...真的不知道if是什么

这个将按预期工作:

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

occurst _ Empty = 0
occurst a ( Node (x,left,right) ) =
            if a==x then 1 + (occurst a left) + (occurst a right)
            else (occurst a left) + (occurst a right) 
BTW:我没有更改你的命名,也没有更改你的基本算法,但请注意,这个不是非常友好的堆栈,因为它不是尾递归的。

答案 2 :(得分:1)

这是一个尾递归版本:

data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)

occurst x t = go 0 [t] where
  go n [] = n
  go n (t:ts) = case t of
                  Empty      -> go n ts
                  Node a l r -> let n' = n + fromEnum (a==x)
                                in n' `seq` go n' (l:r:ts)

j = occurst 1 t where
  t = (Node 3
        (Node 2
          (Node 1 Empty Empty)
          (Node 1 Empty Empty ))
        (Node 1
          (Node 2
            (Node 1 Empty Empty)
            (Node 1 Empty Empty))
          (Node 1 Empty Empty)))