haskell中的树大小

时间:2016-12-10 12:43:18

标签: haskell

我有一个像这样的树的实现:

数据树a =空|节点a [Tree a]派生Show

我需要大小。

我认为此代码可以解决此问题,但我有一个错误:

size :: Tree a -> Int
size Empty       = 0
size (Node a ts) = 1 + [size t | t<-ts]

3 个答案:

答案 0 :(得分:2)

提示:

{} is Dictionary and [] is Array

答案 1 :(得分:1)

您的代码中显然有输入错误。

Couldn't match expected type ‘Int’ with actual type ‘[Int]’
• In the expression: 1 + [size t | t <- ts]
  In an equation for ‘size’:
      size (Node a ts) = 1 + [size t | t <- ts]

由于您需要Int,因此您必须找到将Int列表转换为Int的方法。

换句话说,你可以引入一个这样的洞:

size :: Tree a -> Int
size Empty         = 0
size (Node a ts) = 1 + _g [size t | t<-ts]  

导致错误消息:

• Found hole: _g :: [Int] -> Int
  Or perhaps ‘_g’ is mis-spelled, or not in scope
• In the expression: _g
  In the second argument of ‘(+)’, namely ‘_g [size t | t <- ts]’
  In the expression: 1 + _g [size t | t <- ts]
• Relevant bindings include
    ts :: [Tree a]
      (bound at /Users/jeeb/incubator/scratch/app/Main.hs:10:14)
    a :: a (bound at /Users/jeeb/incubator/scratch/app/Main.hs:10:12)
    size :: Tree a -> Int
      (bound at /Users/jeeb/incubator/scratch/app/Main.hs:9:1)

根据“大小”的含义,您应该可以使用正确的函数替换g

答案 2 :(得分:1)

size:: Tree a -> Int
size Empty = 0
size (Node a ts) = 1 + maximum[size t | t <- ts]

可能你想要子树的最大大小,所以我会使用预定义的最大函数来将每个分支转换成他的大小后得到它。