2017-04-17 3 views
-3

を行使する、エラーがこれらの木は、左右のサイド木々の葉の数が複数でない場合には、第10章練習問題3Haskellのバイナリツリーは、Haskellではグラハムハットンの本プログラミングで

を解決するためにありましたバランスが取れていると言われています。 もちろん、それ自体はバランスがとれているようです。ツリーが均衡しているかどうかを判断する関数を定義します。 最初に、ツリー内の葉の数を数える関数を定義します。

data Tree = Leaf Int | Node Tree Tree 

leaves :: Tree -> Int 
leaves (Leaf _) = 1 leaves 
leaves (Node l r) = leaves l + leaves r 

balanced :: Tree -> Bool 
(-) :: Int -> Int -> Integer 
balanced (Leaf _) = True 
balanced (Node l r) = abs (leaves l - leaves r) <= 1 
&& balanced l && balanced r 

私はハスケルについて何も知らないが、私の教授は私に割り当てを与えた。ヘルプ

+1

'leaves(Leaf _)'はちょうど '1'である必要があります。私の提案はあなたが快適である他の言語でこの機能を実装しています。実装方法を理解すれば、この解決策を理解することがより簡単になります。 – karakfa

+0

申し訳ありません。番号1の隣にある葉は、誤植です。 –

+0

あなたの質問が分かりません。あなたは質問のあなたの課題に解決策を提供しました。 (しかし、あなたは '&& balanced l && balanced r'の部分を必要としません。 –

答えて

0

あなたのコードは大体よく見えますが、小さな誤りがあります。

leaves :: Tree -> Int 
leaves (Leaf _) = 1   -- not 1 leaves 
leaves (Node l r) = leaves l + leaves r 

balanced :: Tree -> Bool 
-- don't declare (-) here, it's already declared by the libraries! 
balanced (Leaf _) = True 
balanced (Node l r) = abs (leaves l - leaves r) <= 1 
    && balanced l && balanced r -- indent this more