2016-12-10 7 views
0

私はこのようなツリーの実装を持っています:haskellのツリーサイズ

データツリーa = Empty |ノードa [ツリーa]の導出表示

と私はサイズを取得する必要があります。

私はこのコードは、この問題を解決することができると思うが、私はエラーを持っている:

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

番号とリストを追加しようとしています。リスト内の数字を合計する方法について考えてみませんか? – molbdnilo

+0

しかし、この種のリストはint noを返しますか? – gon91

+1

intを返すリストはありません。リストはリストです。 – molbdnilo

答えて

2

ヒント:

> 1 + [2,3,4] 
<interactive>:8:1: error: 
    • Non type-variable argument in the constraint: Num [t] 
     (Use FlexibleContexts to permit this) 
    • When checking the inferred type 
     it :: forall t. (Num [t], Num t) => [t] 

> 1 + sum [2,3,4] 
10 
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をしたいので、あなたはIntIntのリストを変換する方法を見つける必要があります。

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を正しい機能で置き換えてください。私はそれが後の彼のサイズに分岐ごとに変換取得するための関数定義済みの最大値を使用するよう

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

は、おそらくあなたは、サブツリーの最大サイズが欲しいです。

+0

それは最大で、深さです。 –